diff options
38 files changed, 11689 insertions, 0 deletions
diff --git a/src/agentux/checkpoint.py b/src/agentux/checkpoint.py new file mode 100644 index 0000000..e3ff51f --- /dev/null +++ b/src/agentux/checkpoint.py @@ -0,0 +1,221 @@ +"""Shadow checkpoint and time-travel undo engine for Agentux. + +Allows automatic and manual snapshots before modifying files, instant `/undo` +rollback of agent turns, and unified diff inspection (`/diff`). Works seamlessly +in git repositories via shadow commits / stash or standalone via atomic backups. +""" + +from __future__ import annotations + +import difflib +import os +import shutil +import subprocess +import time +import uuid +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Tuple + + +@dataclass +class Checkpoint: + """A point-in-time snapshot of modified project files.""" + id: str + timestamp: float + description: str + files: Dict[str, Optional[str]] = field(default_factory=dict) # rel_path -> original content (None if new file) + git_sha: Optional[str] = None + + @property + def formatted_time(self) -> str: + return time.strftime("%H:%M:%S", time.localtime(self.timestamp)) + + +class CheckpointManager: + """Manages project checkpoints, rollbacks, and diff computation.""" + + def __init__(self, root: str, max_checkpoints: int = 50) -> None: + self.root = os.path.abspath(root) + self.max_checkpoints = max_checkpoints + self._checkpoints: List[Checkpoint] = [] + self._is_git = os.path.isdir(os.path.join(self.root, ".git")) + + def capture_file_before(self, rel_path: str, checkpoint_id: str) -> None: + """Record the state of a file before it gets edited.""" + abs_path = os.path.join(self.root, rel_path) + cp = self.get_checkpoint(checkpoint_id) + if not cp: + return + if rel_path in cp.files: + return # Keep the earliest original state + + if os.path.exists(abs_path): + try: + with open(abs_path, "r", encoding="utf-8", errors="replace") as f: + cp.files[rel_path] = f.read() + except Exception: + cp.files[rel_path] = None + else: + cp.files[rel_path] = None + + def create_checkpoint(self, description: str, files_to_snapshot: Optional[List[str]] = None) -> Checkpoint: + """Create a new checkpoint snapshot.""" + cp_id = str(uuid.uuid4())[:8] + git_sha = None + + if self._is_git: + try: + # Capture current git commit hash if clean + res = subprocess.run( + ["git", "rev-parse", "--short", "HEAD"], + cwd=self.root, + capture_output=True, + text=True, + timeout=2, + ) + if res.returncode == 0: + git_sha = res.stdout.strip() + except Exception: + pass + + files_map: Dict[str, Optional[str]] = {} + if files_to_snapshot: + for rel in files_to_snapshot: + abs_p = os.path.join(self.root, rel) + if os.path.isfile(abs_p): + try: + with open(abs_p, "r", encoding="utf-8", errors="replace") as f: + files_map[rel] = f.read() + except Exception: + files_map[rel] = None + else: + files_map[rel] = None + + cp = Checkpoint( + id=cp_id, + timestamp=time.monotonic(), + description=description, + files=files_map, + git_sha=git_sha, + ) + self._checkpoints.append(cp) + if len(self._checkpoints) > self.max_checkpoints: + self._checkpoints.pop(0) + return cp + + def get_checkpoint(self, checkpoint_id: str) -> Optional[Checkpoint]: + for cp in reversed(self._checkpoints): + if cp.id == checkpoint_id: + return cp + return None + + def get_latest(self) -> Optional[Checkpoint]: + return self._checkpoints[-1] if self._checkpoints else None + + def rollback(self, checkpoint_id: Optional[str] = None) -> Tuple[bool, str]: + """Rollback changes made since the specified checkpoint (or the latest).""" + if not self._checkpoints: + return False, "No checkpoints available to roll back to." + + target: Optional[Checkpoint] = None + if checkpoint_id: + target = self.get_checkpoint(checkpoint_id) + if not target: + return False, f"Checkpoint '{checkpoint_id}' not found." + else: + target = self._checkpoints[-1] + + restored: List[str] = [] + errors: List[str] = [] + + for rel_path, original_content in target.files.items(): + abs_path = os.path.join(self.root, rel_path) + try: + if original_content is None: + # File was newly created by the agent; remove it + if os.path.exists(abs_path): + os.remove(abs_path) + restored.append(f"removed newly created {rel_path}") + else: + # Restore original content + os.makedirs(os.path.dirname(abs_path), exist_ok=True) + with open(abs_path, "w", encoding="utf-8") as f: + f.write(original_content) + restored.append(f"restored {rel_path}") + except Exception as exc: + errors.append(f"failed to restore {rel_path}: {exc}") + + # Remove the checkpoint from history once rolled back + if target in self._checkpoints: + self._checkpoints.remove(target) + + summary_parts = [] + if restored: + summary_parts.append(f"Successfully reverted {len(restored)} file(s):\n - " + "\n - ".join(restored)) + if errors: + summary_parts.append(f"Errors during rollback:\n - " + "\n - ".join(errors)) + if not restored and not errors: + summary_parts.append("No file modifications found to revert in this checkpoint.") + + return True, "\n".join(summary_parts) + + def get_diff(self, checkpoint_id: Optional[str] = None) -> str: + """Compute unified diff between the checkpoint snapshot and the current disk state.""" + if not self._checkpoints: + return "No modifications in current session." + + target = self.get_checkpoint(checkpoint_id) if checkpoint_id else self._checkpoints[0] + if not target: + return "Checkpoint not found." + + diff_outputs: List[str] = [] + + # Compare recorded snapshot files + for rel_path, original_content in target.files.items(): + abs_path = os.path.join(self.root, rel_path) + current_content = "" + if os.path.isfile(abs_path): + try: + with open(abs_path, "r", encoding="utf-8", errors="replace") as f: + current_content = f.read() + except Exception: + continue + elif original_content is None: + continue + + orig_lines = (original_content or "").splitlines(keepends=True) + curr_lines = current_content.splitlines(keepends=True) + + diff = list( + difflib.unified_diff( + orig_lines, + curr_lines, + fromfile=f"a/{rel_path}", + tofile=f"b/{rel_path}", + ) + ) + if diff: + diff_outputs.append("".join(diff)) + + if not diff_outputs and self._is_git: + # Fallback to git diff + try: + res = subprocess.run( + ["git", "diff", "--no-color"], + cwd=self.root, + capture_output=True, + text=True, + timeout=5, + ) + if res.returncode == 0 and res.stdout.strip(): + return res.stdout.strip() + except Exception: + pass + + return "\n".join(diff_outputs) if diff_outputs else "No active file differences." + + def list_checkpoints(self) -> List[Checkpoint]: + return list(self._checkpoints) + + def clear(self) -> None: + self._checkpoints.clear() diff --git a/src/agentux/commands.py b/src/agentux/commands.py new file mode 100644 index 0000000..983072d --- /dev/null +++ b/src/agentux/commands.py @@ -0,0 +1,1482 @@ +"""Slash commands for the interactive session. + +A command is a name, a one-line summary, and a handler. The registry below is +the single source of truth: ``/help`` renders it, tab-completion offers it, and +the picker shows it -- so a command can never exist without being discoverable. + +Handlers return ``True`` to keep the session running and ``False`` to end it. +""" + +from __future__ import annotations + +import argparse +import os +import subprocess +from typing import Any, Awaitable, Callable, Dict, List, NamedTuple, Optional, Tuple + +from rich.console import Console +from rich.panel import Panel +from rich.table import Table +from rich.text import Text + +from .config import save_settings +from .errors import AgentuxError +from . import theme +from .marketplace import ( + Marketplace, + MarketplaceEntry, + MarketplaceItemType, + load_catalogue, + load_installed, + install_entry, + is_installed, + search_catalogue, + seed_catalogue, +) +from .theme import ( + ACCENT_DIM, + ACCENT_END_HEX, + ACCENT_START_HEX, + BORDER, + BORDER_SUBTLE, + CYAN, + EMERALD, + Mode, + PINK, + PURPLE, + TEXT_DIM, + TEXT_LIGHT, + TEXT_MUTED, + YELLOW, +) +from .ui import ACCENT_END_HEX, ACCENT_START_HEX, _shorten + + +class Command(NamedTuple): + """A slash command. ``name`` is stored bare; users always type the slash.""" + + name: str + summary: str + handler: Callable[["CommandContext", str], Awaitable[bool]] + aliases: Tuple[str, ...] = () + + +class CommandContext(NamedTuple): + """Everything a command handler is allowed to touch. + + ``session`` is the CLI's dict of runtime toggles, so ``/set stream off`` + can change something that is not on :class:`~agentux.config.Config`. + ``rebuild_tools`` re-roots the tools, which a ``/set cwd`` needs. + """ + + agent: Any + view: Any + mcp_manager: Any + console: Console + args: argparse.Namespace + session: Dict[str, Any] + rebuild_tools: Optional[Callable[[], Any]] = None + + +#: Populated by :func:`register_builtins`. Kept module-level so completion and +#: ``/help`` can read it without importing the CLI. +REGISTRY: Dict[str, Command] = {} +ALIASES: Dict[str, str] = {} + + +def register(command: Command) -> Command: + """Add a command under its bare name, plus each of its aliases.""" + name = command.name.lstrip("/") + if not name: + raise ValueError("A command needs a name.") + REGISTRY[name] = command._replace(name=name) + for alias in command.aliases: + ALIASES[alias.lstrip("/").lower()] = name + return command + + +def resolve(text: str) -> Optional[Command]: + """Look up a command by name or alias. ``None`` if there is no match. + + Only the first word is considered, so ``/model gpt-4o`` resolves to the + ``/model`` command and leaves ``gpt-4o`` as the argument. + """ + if not text: + return None + name = text.lstrip("/").split()[0].lower() + name = ALIASES.get(name, name) + return REGISTRY.get(name) + + +def names() -> List[str]: + return sorted(REGISTRY) + + +# ---------------------------------------------------------------------- +# Handlers +# ---------------------------------------------------------------------- +async def cmd_help(context: CommandContext, argument: str) -> bool: + """Render every command.""" + table = Table(box=None, pad_edge=False, show_header=True, header_style="dim") + table.add_column("command", style=f"bold {ACCENT_START_HEX}", no_wrap=True) + table.add_column("aliases", style="dim", no_wrap=True) + table.add_column("what it does", overflow="fold") + + for name in names(): + command = REGISTRY[name] + aliases = ", ".join(f"/{a}" for a in command.aliases) + table.add_row(f"/{name}", aliases or "", command.summary) + + context.console.print() + context.console.print(table) + context.console.print() + context.console.print( + Text( + "Type / on its own for a menu, or start typing to filter. " + "Anything not starting with / goes to the agent.", + style="dim", + ) + ) + return True + + +async def cmd_exit(context: CommandContext, argument: str) -> bool: + context.console.print("[dim]Bye.[/dim]") + return False + + +async def cmd_reset(context: CommandContext, argument: str) -> bool: + context.agent.reset() + context.console.print("[dim]Conversation cleared. Context is back to empty.[/dim]") + return True + + +async def cmd_tools(context: CommandContext, argument: str) -> bool: + names = context.agent.registry.names + if not names: + context.console.print("[dim]No tools are available in this session.[/dim]") + return True + + table = Table(box=None, pad_edge=False, show_header=True, header_style="dim") + table.add_column("tool", style=f"bold {ACCENT_START_HEX}", no_wrap=True) + table.add_column("source", style=ACCENT_END_HEX, no_wrap=True) + table.add_column("description", overflow="fold") + + for name in names: + tool = context.agent.registry.get(name) + source = "MCP" if name.startswith("mcp__") else "built-in" + first = tool.description.strip().split("\n")[0] + table.add_row(name, source, _shorten(first, 96)) + + context.console.print() + context.console.print(table) + return True + + +async def cmd_context(context: CommandContext, argument: str) -> bool: + """Show how full the conversation is and what has been spent.""" + view = context.view + history = context.agent.history + system = history[0].content if history and history[0].role == "system" else "" + tools = context.agent.registry.definitions() + + from .usage import ( + conversation_tokens, + estimate_tokens, + format_tokens, + ) + + total = conversation_tokens(history, system or "", tools) + + tool_tokens = sum( + estimate_tokens(t.name) + estimate_tokens(t.description) + + estimate_tokens(str(t.parameters)) + for t in tools + ) + message_tokens = total - estimate_tokens(system) - tool_tokens + compressed = context.agent.context.compressed + saved = context.agent.context.saved_chars + + body = Text() + body.append("context\n") + # append_text, not append: the stats carry their own styles, and Text.append + # would take them as literal characters. + body.append_text(view.context_stats()) + body.append("\n\nbreakdown (estimated)\n") + body.append(f" {'system prompt':<18}{format_tokens(estimate_tokens(system))}\n") + body.append(f" {'tool schemas':<18}{format_tokens(tool_tokens)}\n") + body.append(f" {'conversation':<18}{format_tokens(max(0, message_tokens))}\n") + body.append(f" {'total':<18}{format_tokens(total)}\n") + + body.append("\nthis session\n") + body.append(f" {'requests':<18}{context.view.usage.requests}\n") + body.append( + f" {'tokens used':<18}" + f"{format_tokens(context.view.usage.total_tokens)}" + f"{'' if context.view.usage.reported else ' (estimated)'}\n" + ) + body.append(f" {'tool calls':<18}{len(context.agent.step_log)}\n") + body.append(f" {'messages':<18}{len(history)}\n") + if compressed: + body.append( + f" {'compressed':<18}{compressed} tool result(s), " + f"{format_tokens(saved)} tokens saved\n" + ) + + context.console.print() + context.console.print(Panel(body, border_style=ACCENT_START_HEX, padding=(1, 2))) + context.console.print( + Text( + "Figures marked estimated are computed from text length; the " + "provider did not report them.", + style="dim", + ) + ) + return True + + +async def cmd_set(context: CommandContext, argument: str) -> bool: + """Show or change configuration without leaving Agentux.""" + from .settings import SETTABLE, TOGGLES, apply_setting, describe_settings, resolve_key, savable + + parts = argument.strip().split(None, 1) + agent = context.agent + config = agent.config + + if not parts: + context.console.print() + context.console.print( + Panel(describe_settings(config), border_style=ACCENT_START_HEX, padding=(1, 2)) + ) + for name, summary in sorted(TOGGLES.items()): + state = "on" if context.session.get(name) else "off" + context.console.print( + f" {name:<12}[dim]{summary} — {state}[/dim]" + ) + context.console.print() + context.console.print( + Text( + "Change one with '/set <name> <value>'. Names: " + + ", ".join(sorted(set(SETTABLE) | set(TOGGLES))) + + ". Keep them with '/set save'.", + style="dim", + ) + ) + return True + + key = parts[0].lower() + value = parts[1].strip() if len(parts) > 1 else "" + + if key in ("save", "persist"): + if value: + context.console.print("[dim]Usage: /set save[/dim]") + return True + try: + path = save_settings(savable(config)) + except AgentuxError as exc: + context.console.print(f"[red]{exc}[/red]") + return True + context.console.print(f"[green]Saved preferences to[/green] {path}") + context.console.print( + Text( + "Your API key was not saved. Keep it in AGENTUX_API_KEY, or set " + "it again with '/set api-key' next time you start.", + style="dim", + ) + ) + return True + + resolved = resolve_key(key) + if resolved is None: + context.console.print( + f"[yellow]Unknown setting {key!r}. Try one of: " + f"{', '.join(sorted(set(SETTABLE) | set(TOGGLES)))}.[/yellow]" + ) + return True + + if not value: + context.console.print( + f"[yellow]'/set {resolved}' needs a value. " + f"Try '/set {resolved} <value>'.[/yellow]" + ) + return True + + try: + message = await apply_setting( + agent, + resolved, + value, + session=context.session, + rebuild_tools=context.rebuild_tools, + ) + except AgentuxError as exc: + context.console.print(f"[red]{exc}[/red]") + return True + + context.console.print(f"[green]{message}[/green]") + return True + + +async def cmd_model(context: CommandContext, argument: str) -> bool: + from .modelpicker import handle_model + + return await handle_model(context.agent, context.console, argument) + + +async def cmd_mcp(context: CommandContext, argument: str) -> bool: + from .mcp_config import global_config_path + + manager = context.mcp_manager + body = Text() + + if manager is None or not manager.servers: + body.append("No MCP servers are configured.\n\n") + else: + for line in manager.describe(): + body.append(line + "\n") + body.append("\n") + tools = [t for t in (manager.tools or []) if t.server.connected] + body.append(f"{len(tools)} tool(s) available from MCP\n") + + body.append("\nconfig files\n") + body.append(f" global {global_config_path()}\n") + body.append(f" project {context.agent.config.working_dir}/.agentux/mcp.json\n") + + context.console.print() + context.console.print(Panel(body, border_style=ACCENT_START_HEX, padding=(1, 2))) + + if manager and manager.warnings: + for warning in manager.warnings: + context.console.print(f"[yellow]![/yellow] {warning}") + + context.console.print( + Text( + 'Add a server like {"mcpServers": {"name": {"command": "npx", ' + '"args": ["-y", "package"]}}}. Agentux works fine without any.', + style="dim", + ) + ) + return True + + +async def cmd_marketplace(context: CommandContext, argument: str) -> bool: + """Show and interact with the marketplace for skills and MCP servers.""" + marketplace = Marketplace() + + # Simple argument parsing + if not argument.strip(): + # Show marketplace overview + await _show_marketplace_overview(context, marketplace) + return True + + args = argument.strip().split() + command = args[0].lower() if args else "" + + if command == "search" and len(args) > 1: + query = " ".join(args[1:]) + await _search_marketplace(context, marketplace, query) + elif command == "install" and len(args) > 1: + item_id = args[1] + await _install_marketplace_item(context, marketplace, item_id) + elif command == "uninstall" and len(args) > 1: + item_id = args[1] + await _uninstall_marketplace_item(context, marketplace, item_id) + elif command == "enable" and len(args) > 1: + item_id = args[1] + await _enable_marketplace_item(context, marketplace, item_id) + elif command == "disable" and len(args) > 1: + item_id = args[1] + await _disable_marketplace_item(context, marketplace, item_id) + elif command == "list": + await _list_marketplace_items(context, marketplace) + elif command == "update" or command == "refresh": + await _update_marketplace_external(context, marketplace) + elif command == "info" and len(args) > 1: + item_id = args[1] + await _show_marketplace_item_info(context, marketplace, item_id) + else: + await _show_marketplace_help(context) + + return True + + +async def _show_marketplace_overview(context: CommandContext, marketplace: Marketplace) -> None: + """Show marketplace overview with categories.""" + from rich.table import Table + from rich.text import Text + from rich.panel import Panel + + context.console.print() + + # Create overview table + table = Table(show_header=True, header_style="bold magenta") + table.add_column("Item", style="dim", width=20) + table.add_column("Type", width=12) + table.add_column("Description", width=40) + table.add_column("Status", width=12) + table.add_column("Version", width=8) + + # Add skills + skills = marketplace.get_items_by_type(MarketplaceItemType.SKILL) + for skill in skills: + status = "○ Available" + if skill.installed: + status = "✓ Installed" + if skill.enabled: + status = "⚡ Enabled" + table.add_row( + skill.name, + "Skill", + skill.description[:38] + ("..." if len(skill.description) > 38 else ""), + status, + skill.version + ) + + # Add MCP servers + servers = marketplace.get_items_by_type(MarketplaceItemType.MCP_SERVER) + for server in servers: + status = "○ Available" + if server.installed: + status = "✓ Installed" + if server.enabled: + status = "⚡ Enabled" + table.add_row( + server.name, + "MCP Server", + server.description[:38] + ("..." if len(server.description) > 38 else ""), + status, + server.version + ) + + context.console.print(table) + context.console.print() + + # Show help with better formatting + help_text = Text() + help_text.append("Commands: ", style="bold") + help_text.append("marketplace search <query> - Search for items\n", style="dim") + help_text.append("marketplace install <id> - Install an item\n", style="dim") + help_text.append("marketplace uninstall <id> - Uninstall an item\n", style="dim") + help_text.append("marketplace enable <id> - Enable an installed item\n", style="dim") + help_text.append("marketplace disable <id> - Disable an installed item\n", style="dim") + help_text.append("marketplace list - List all items\n", style="dim") + help_text.append("marketplace update - Fetch latest skills and MCPs from external sources\n", style="dim") + help_text.append("marketplace refresh - Alias for update\n", style="dim") + help_text.append("marketplace info <id> - Show detailed item info\n", style="dim") + help_text.append("marketplace - Show this overview\n", style="dim") + + context.console.print(Panel(help_text, title="Marketplace Help", border_style=BORDER_SUBTLE)) + + +async def _search_marketplace(context: CommandContext, marketplace: Marketplace, query: str) -> None: + """Search the marketplace for items matching the query.""" + from rich.table import Table + from rich.text import Text + from rich.panel import Panel + + results = marketplace.search_items(query) + + if not results: + context.console.print(f"[yellow]No items found matching '{query}'[/yellow]") + return + + context.console.print() + + table = Table(show_header=True, header_style="bold magenta") + table.add_column("ID", width=10) + table.add_column("Name", width=20) + table.add_column("Type", width=12) + table.add_column("Description", width=30) + table.add_column("Installed", width=10) + + for item in results: + table.add_row( + item.id[:8], + item.name, + item.type.value.title(), + item.description[:28] + ("..." if len(item.description) > 28 else ""), + "✓" if item.installed else "○" + ) + + context.console.print(table) + context.console.print(f"[dim]Found {len(results)} item(s)[/dim]") + + +async def _install_marketplace_item(context: CommandContext, marketplace: Marketplace, item_id: str) -> None: + """Install a marketplace item.""" + if marketplace.install_item(item_id): + item = marketplace.get_item(item_id) + if item: + context.console.print(f"[green]✓ Installed {item.name}[/green]") + else: + context.console.print("[green]✓ Item installed[/green]") + else: + context.console.print(f"[red]✗ Item with ID '{item_id}' not found[/red]") + + +async def _uninstall_marketplace_item(context: CommandContext, marketplace: Marketplace, item_id: str) -> None: + """Uninstall a marketplace item.""" + if marketplace.uninstall_item(item_id): + item = marketplace.get_item(item_id) + if item: + context.console.print(f"[yellow]○ Uninstalled {item.name}[/yellow]") + else: + context.console.print("[yellow]○ Item uninstalled[/yellow]") + else: + context.console.print(f"[red]✗ Item with ID '{item_id}' not found[/red]") + + +async def _enable_marketplace_item(context: CommandContext, marketplace: Marketplace, item_id: str) -> None: + """Enable a marketplace item.""" + if marketplace.enable_item(item_id): + item = marketplace.get_item(item_id) + if item: + context.console.print(f"[green]✓ Enabled {item.name}[/green]") + else: + context.console.print("[green]✓ Item enabled[/green]") + else: + context.console.print(f"[red]✗ Item with ID '{item_id}' not found or not installed[/red]") + + +async def _disable_marketplace_item(context: CommandContext, marketplace: Marketplace, item_id: str) -> None: + """Disable a marketplace item.""" + if marketplace.disable_item(item_id): + item = marketplace.get_item(item_id) + if item: + context.console.print(f"[yellow]○ Disabled {item.name}[/yellow]") + else: + context.console.print("[yellow]○ Item disabled[/yellow]") + else: + context.console.print(f"[red]✗ Item with ID '{item_id}' not found or not installed[/red]") + + +async def _list_marketplace_items(context: CommandContext, marketplace: Marketplace) -> None: + """List all marketplace items.""" + from rich.table import Table + + context.console.print() + + table = Table(show_header=True, header_style="bold magenta") + table.add_column("ID", width=10) + table.add_column("Name", width=20) + table.add_column("Type", width=12) + table.add_column("Description", width=30) + table.add_column("Status", width=12) + table.add_column("Version", width=8) + + for item in marketplace.items: + status = "○ Available" + if item.installed: + status = "✓ Installed" + if item.enabled: + status = "⚡ Enabled" + table.add_row( + item.id[:8], + item.name, + item.type.value.title(), + item.description[:28] + ("..." if len(item.description) > 28 else ""), + status, + item.version + ) + + context.console.print(table) + context.console.print(f"[dim]Total: {len(marketplace.items)} items[/dim]") + + +async def _show_marketplace_item_info(context: CommandContext, marketplace: Marketplace, item_id: str) -> None: + """Show detailed information about a marketplace item.""" + from rich.panel import Panel + from rich.text import Text + + item = marketplace.get_item(item_id) + if not item: + context.console.print(f"[red]✗ Item with ID '{item_id}' not found[/red]") + return + + context.console.print() + + info_text = Text() + info_text.append(f"Name: {item.name}\n", style="bold") + info_text.append(f"Type: {item.type.value.title()}\n", style="dim") + info_text.append(f"Description: {item.description}\n") + info_text.append(f"Version: {item.version}\n") + info_text.append(f"Author: {item.author}\n") + if item.homepage: + info_text.append(f"Homepage: {item.homepage}\n") + if item.tags: + info_text.append(f"Tags: {', '.join(item.tags)}\n") + info_text.append(f"Installed: {'Yes' if item.installed else 'No'}\n") + info_text.append(f"Enabled: {'Yes' if item.enabled else 'No'}\n") + if item.entry_point: + info_text.append(f"Entry Point: {item.entry_point}\n") + if item.config: + info_text.append(f"Configuration: {json.dumps(item.config, indent=2)}\n") + + # Format timestamps + import datetime + created = datetime.datetime.fromtimestamp(item.created_at).strftime("%Y-%m-%d %H:%M:%S") + updated = datetime.datetime.fromtimestamp(item.updated_at).strftime("%Y-%m-%d %H:%M:%S") + info_text.append(f"Created: {created}\n") + info_text.append(f"Updated: {updated}\n") + + context.console.print(Panel(info_text, title=f"Item Info: {item.name}", border_style=BORDER)) + + +async def _show_marketplace_help(context: CommandContext) -> None: + """Show marketplace help.""" + from rich.text import Text + from rich.panel import Panel + + help_text = Text() + help_text.append("Marketplace Commands:\n\n", style="bold") + help_text.append("marketplace - Show marketplace overview\n", style="dim") + help_text.append("marketplace search <q> - Search for items\n", style="dim") + help_text.append("marketplace install <id> - Install an item\n", style="dim") + help_text.append("marketplace uninstall <id> - Uninstall an item\n", style="dim") + help_text.append("marketplace enable <id> - Enable an installed item\n", style="dim") + help_text.append("marketplace disable <id> - Disable an installed item\n", style="dim") + help_text.append("marketplace list - List all items\n", style="dim") + help_text.append("marketplace update - Fetch latest skills and MCPs from external sources\n", style="dim") + help_text.append("marketplace refresh - Alias for update\n", style="dim") + help_text.append("marketplace info <id> - Show detailed item info\n", style="dim") + help_text.append("\nExamples:\n", style="bold") + help_text.append(" marketplace search dataviz\n", style="dim") + help_text.append(" marketplace install <skill-id>\n", style="dim") + help_text.append(" marketplace enable <mcp-server-id>\n", style="dim") + help_text.append(" marketplace update\n", style="dim") + + context.console.print() + context.console.print(Panel(help_text, title="Marketplace Help", border_style=BORDER_SUBTLE)) + + +async def _update_marketplace_external(context: CommandContext, marketplace: Marketplace) -> None: + """Update marketplace with items from external sources.""" + from rich.panel import Panel + from rich.text import Text + + context.console.print() + context.console.print("[yellow]Fetching skills from skills.sh and MCPs from mcpmarketplace.com...[/yellow]") + + # Call the external fetch method + marketplace._fetch_and_merge_external_items() + + # Show results + skills_count = len(marketplace.get_items_by_type(MarketplaceItemType.SKILL)) + mcps_count = len(marketplace.get_items_by_type(MarketplaceItemType.MCP_SERVER)) + + result_text = Text() + result_text.append("Marketplace updated successfully!\n\n") + result_text.append(f"Skills available: {skills_count}\n") + result_text.append(f"MCP servers available: {mcps_count}\n") + result_text.append("\nUse 'marketplace list' to see all items or 'marketplace search <query>' to search.") + + context.console.print(Panel(result_text, title="Update Complete", border_style=BORDER)) + + +async def cmd_mode(context: CommandContext, argument: str) -> bool: + """Set or show the current operation mode.""" + tui = context.agent.tui # Access the TUI instance from the agent + + if not argument.strip(): + # Show current mode with visual indicator + mode_name = tui.mode.value.upper() + mode_icons = { + Mode.CHAT: "►", + Mode.BUILD: "⚡", + Mode.PLAN: "📝" + } + mode_colors = { + Mode.CHAT: "green", + Mode.BUILD: "cyan", + Mode.PLAN: "blue" + } + icon = mode_icons.get(tui.mode, "") + color = mode_colors.get(tui.mode, "white") + + context.console.print() + context.console.print(f"[{color} bold]{icon} Current mode: {mode_name}[/{color} bold]") + context.console.print() + context.console.print("[dim]Available modes:[/dim]") + context.console.print(" [green]► chat[/green] - Normal conversational mode") + context.console.print(" [cyan]⚡ build[/cyan] - Focused on building/creating") + context.console.print(" [blue]📝 plan[/blue] - Focused on planning/designing") + context.console.print() + context.console.print("Usage: /mode <chat|build|plan>") + return True + + # Parse the mode argument + mode_str = argument.strip().lower() + try: + new_mode = Mode(mode_str) + except ValueError: + context.console.print(f"[red]Invalid mode: {mode_str}[/red]") + context.console.print("[dim]Available modes: chat, build, plan[/dim]") + return True + + # Set the new mode + old_mode = tui.mode + tui.mode = new_mode + + # Update the UI to reflect the new mode with visual feedback + mode_icons = { + Mode.CHAT: "►", + Mode.BUILD: "⚡", + Mode.PLAN: "📝" + } + mode_colors = { + Mode.CHAT: "green", + Mode.BUILD: "cyan", + Mode.PLAN: "blue" + } + icon = mode_icons.get(new_mode, "") + color = mode_colors.get(new_mode, "white") + + context.console.print() + context.console.print(f"[{color} bold]✓ Switched from {old_mode.value.upper()} to {icon} {new_mode.value.upper()}[/{color} bold]") + + # Trigger a UI redraw to update any mode-dependent styling + if hasattr(tui, '_redraw'): + tui._redraw() + + return True + + +async def cmd_skills(context: CommandContext, argument: str) -> bool: + """Manage and execute Agentux skills.""" + agent = context.agent + + # Simple argument parsing + if not argument.strip(): + # Show skills overview + await _show_skills_overview(context, agent) + return True + + args = argument.strip().split() + command = args[0].lower() if args else "" + + if command == "list" and len(args) > 1: + subcommand = args[1].lower() + if subcommand == "available": + await _list_available_skills(context, agent) + elif subcommand == "loaded": + await _list_loaded_skills(context, agent) + else: + await _show_skills_help(context) + elif command == "execute" and len(args) > 2: + skill_name = args[1] + operation = args[2] if len(args) > 2 else "run" + # Parse additional arguments as key=value pairs + kwargs = {} + for arg in args[3:]: + if "=" in arg: + key, value = arg.split("=", 1) + kwargs[key] = value + else: + kwargs[arg] = True + await _execute_skill(context, agent, skill_name, operation, **kwargs) + elif command == "browse": + await _browse_marketplace_skills(context, agent) + elif command == "install" and len(args) > 1: + skill_id = args[1] + await _install_marketplace_skill(context, agent, skill_id) + else: + await _show_skills_help(context) + + return True + + +async def _show_skills_overview(context: CommandContext, agent: Any) -> None: + """Show skills overview.""" + from rich.table import Table + from rich.panel import Panel + from rich.text import Text + + context.console.print() + + # Get skills information + available_skills = agent.get_available_skills() + loaded_skills = agent.get_loaded_skills() + + # Create overview table + table = Table(show_header=True, header_style="bold magenta") + table.add_column("Skill", style="dim", width=25) + table.add_column("Status", width=12) + table.add_column("Description", width=40) + + # Add built-in skills + built_in_skills = ["reasoning", "self_improvement", "marketplace_integration"] + for skill in built_in_skills: + status = "⚡ Loaded" if skill in loaded_skills else "○ Available" + description = { + "reasoning": "Advanced reasoning and planning capabilities", + "self_improvement": "Self-improvement and learning capabilities", + "marketplace_integration": "Marketplace integration for dynamic skill loading" + }.get(skill, "No description available") + + table.add_row( + skill, + status, + description + ) + + # Add pictured skills from marketplace integration if available + try: + marketplace_skill = agent.skills.get_skill("marketplace_integration") + if marketplace_skill: + # This would normally call the skill to get marketplace status + # For now, we'll show placeholder info + table.add_row( + "marketplace_skills", + "📦 Available", + "Skills from Agentux marketplace" + ) + except Exception: + pass + + context.console.print(table) + context.console.print() + + # Show help + help_text = Text() + help_text.append("Skills Commands: ", style="bold") + help_text.append("skills list available - List available skills\n", style="dim") + help_text.append("skills list loaded - List currently loaded skills\n", style="dim") + help_text.append("skills execute <skill> <operation> [args] - Execute a skill\n", style="dim") + help_text.append("skills browse - Browse marketplace for skills\n", style="dim") + help_text.append("skills install <id> - Install a skill from marketplace\n", style="dim") + help_text.append("skills - Show this overview\n", style="dim") + + context.console.print(Panel(help_text, title="Skills Help", border_style=BORDER_SUBTLE)) + + +async def _list_available_skills(context: CommandContext, agent: Any) -> None: + """List available skills.""" + from rich.table import Table + from rich.panel import Panel + + available_skills = agent.get_available_skills() + + context.console.print() + + table = Table(show_header=True, header_style="bold magenta") + table.add_column("Skill Name", style="dim", width=25) + table.add_column("Description", width=50) + + skill_descriptions = { + "reasoning": "Advanced reasoning and planning capabilities for complex problem solving", + "self_improvement": "Self-improvement and learning capabilities to extend agent functionality", + "marketplace_integration": "Integrates with marketplace to dynamically load skills and MCP servers" + } + + for skill in sorted(available_skills): + description = skill_descriptions.get(skill, "No description available") + table.add_row(skill, description) + + context.console.print(table) + context.console.print(f"[dim]Total: {len(available_skills)} available skills[/dim]") + + +async def _list_loaded_skills(context: CommandContext, agent: Any) -> None: + """List loaded skills.""" + from rich.table import Table + from rich.panel import Panel + + loaded_skills = agent.get_loaded_skills() + + context.console.print() + + if not loaded_skills: + context.console.print("[yellow]No skills currently loaded[/yellow]") + return + + table = Table(show_header=True, header_style="bold magenta") + table.add_column("Skill Name", style="dim", width=25) + table.add_column("Status", width=15) + table.add_column("Info", width=40) + + for skill in sorted(loaded_skills): + table.add_row( + skill, + "⚡ Loaded", + "Skill is loaded and ready for execution" + ) + + context.console.print(table) + context.console.print(f"[dim]Total: {len(loaded_skills)} loaded skills[/dim]") + + +async def _execute_skill(context: CommandContext, agent: Any, + skill_name: str, operation: str, **kwargs) -> None: + """Execute a skill operation.""" + from rich.panel import Panel + from rich.text import Text + + context.console.print() + + try: + # Execute the skill + result = await agent.execute_skill(skill_name, operation, **kwargs) + + result_text = Text() + result_text.append(f"Skill: {skill_name}\n", style="bold") + result_text.append(f"Operation: {operation}\n") + if kwargs: + result_text.append(f"Arguments: {kwargs}\n") + result_text.append(f"Result: {result}\n") + + context.console.print(Panel(result_text, title=f"Skill Execution Result", border_style=BORDER)) + + except Exception as exc: + from .errors import AgentuxError + if isinstance(exc, AgentuxError): + context.console.print(f"[red]Skill error: {exc}[/red]") + else: + context.console.print(f"[red]Unexpected error: {exc}[/red]") + + +async def _browse_marketplace_skills(context: CommandContext, agent: Any) -> None: + """Browse marketplace for skills.""" + from rich.table import Table + from rich.panel import Panel + from rich.text import Text + + context.console.print() + + try: + # Get marketplace integration skill + marketplace_skill = agent.skills.get_skill("marketplace_integration") + if marketplace_skill: + # Browse marketplace for skills + result = await marketplace_skill.execute("browse_marketplace", item_type="skill") + + table = Table(show_header=True, header_style="bold magenta") + table.add_column("ID", width=10) + table.add_column("Name", width=20) + table.add_column("Description", width=30) + table.add_column("Version", width=10) + table.add_column("Status", width=12) + + for item in result.get("items", [])[:10]: # Show first 10 + status = "○ Available" + if item.get("installed"): + status = "✓ Installed" + if item.get("enabled"): + status = "⚡ Enabled" + + table.add_row( + item.get("id", "")[:8], + item.get("name", ""), + item.get("description", "")[:28] + ("..." if len(item.get("description", "")) > 28 else ""), + item.get("version", ""), + status + ) + + context.console.print(table) + context.console.print(f"[dim]Found {result.get('total_available', 0)} total skills[/dim]") + else: + context.console.print("[yellow]Marketplace integration skill not available[/yellow]") + + except Exception as exc: + context.console.print(f"[red]Error browsing marketplace: {exc}[/red]") + + +async def _install_marketplace_skill(context: CommandContext, agent: Any, skill_id: str) -> None: + """Install a skill from the marketplace.""" + from rich.panel import Panel + from rich.text import Text + + context.console.print() + + try: + # Get marketplace integration skill + marketplace_skill = agent.skills.get_skill("marketplace_integration") + if marketplace_skill: + # Install the skill + result = await marketplace_skill.execute("install_skill", skill_id=skill_id) + + if result.get("status") in ["installed_and_loaded", "installed_load_failed"]: + status_icon = "✓" if "installed" in result.get("status", "") else "⚠" + status_color = "green" if "installed" in result.get("status", "") else "yellow" + + result_text = Text() + result_text.append(f"Skill ID: {skill_id}\n", style="bold") + result_text.append(f"Status: {result.get('status', 'unknown')}\n", style=f"{status_color}") + if result.get("skill_name"): + result_text.append(f"Skill Name: {result.get('skill_name')}\n") + if result.get("loaded") is not None: + result_text.append(f"Loaded: {result.get('loaded')}\n") + if result.get("load_error"): + result_text.append(f"Load Error: {result.get('load_error')}\n") + + context.console.print(Panel(result_text, title="Installation Result", border_style=BORDER)) + else: + context.console.print(f"[red]Installation failed: {result.get('message', 'Unknown error')}[/red]") + else: + context.console.print("[yellow]Marketplace integration skill not available[/yellow]") + + except Exception as exc: + context.console.print(f"[red]Error installing skill: {exc}[/red]") + + +async def _show_skills_help(context: CommandContext) -> None: + """Show skills help.""" + from rich.text import Text + from rich.panel import Panel + + help_text = Text() + help_text.append("Skills Commands:\n\n", style="bold") + help_text.append("skills - Show skills overview\n", style="dim") + help_text.append("skills list available - List available skills\n", style="dim") + help_text.append("skills list loaded - List loaded skills\n", style="dim") + help_text.append("skills execute <skill> <op> [args] - Execute skill operation\n", style="dim") + help_text.append("skills browse - Browse marketplace for skills\n", style="dim") + help_text.append("skills install <id> - Install skill from marketplace\n", style="dim") + help_text.append("\nExamples:\n", style="bold") + help_text.append(" skills list available\n", style="dim") + help_text.append(" skills execute reasoning task_decomposition task_description=\"Build a web app\"\n", style="dim") + help_text.append(" skills browse\n", style="dim") + help_text.append(" skills install <skill-id-from-browse>\n", style="dim") + + context.console.print() + context.console.print(Panel(help_text, title="Skills Help", border_style=BORDER_SUBTLE)) + + +async def cmd_commit(context: CommandContext, argument: str) -> bool: + """Stage changes and record a git commit.""" + import subprocess + cwd = context.agent.config.working_dir + proc = subprocess.run(["git", "status", "--porcelain"], cwd=cwd, capture_output=True, text=True) + if proc.returncode != 0: + context.console.print(Panel(f"[red]Not a git repository: {cwd}[/red]", border_style="red")) + return True + changes = proc.stdout.strip() + if not changes: + context.console.print(Panel("[dim]Working tree is clean. Nothing to commit.[/dim]", border_style=BORDER_SUBTLE)) + return True + + msg = argument.strip() + if not msg: + changed_lines = changes.splitlines() + first_file = changed_lines[0][3:].strip() + scope = os.path.dirname(first_file) or os.path.splitext(first_file)[0] + msg = f"feat({scope}): update {len(changed_lines)} file(s)\n\n" + "\n".join(f"- {l[3:].strip()}" for l in changed_lines[:8]) + + subprocess.run(["git", "add", "-A"], cwd=cwd, check=True) + commit_proc = subprocess.run(["git", "commit", "-m", msg], cwd=cwd, capture_output=True, text=True) + if commit_proc.returncode == 0: + context.console.print(Panel(f"[bold emerald]✓ Committed successfully[/bold emerald]\n\n[dim]{commit_proc.stdout.strip()}[/dim]", border_style=EMERALD, title="Git Commit")) + else: + context.console.print(Panel(f"[red]Git commit failed:[/red]\n{commit_proc.stderr.strip()}", border_style="red")) + return True + + +async def cmd_diff(context: CommandContext, argument: str) -> bool: + """Show git diff in a syntax-highlighted panel.""" + import subprocess + cwd = context.agent.config.working_dir + args = ["git", "diff"] + if "staged" in argument.lower() or "--cached" in argument.lower(): + args.append("--cached") + proc = subprocess.run(args, cwd=cwd, capture_output=True, text=True) + if proc.returncode != 0: + context.console.print(Panel(f"[red]Git diff failed:[/red] {proc.stderr}", border_style="red")) + return True + diff_text = proc.stdout.strip() + if not diff_text: + context.console.print(Panel("[dim]No diff. Working tree matches index.[/dim]", border_style=BORDER_SUBTLE)) + return True + from rich.syntax import Syntax + syntax = Syntax(diff_text, "diff", theme="monokai", word_wrap=True) + context.console.print(Panel(syntax, title="Git Diff", border_style=BORDER)) + return True + + +async def cmd_status(context: CommandContext, argument: str) -> bool: + """Show git branch and working tree status.""" + import subprocess + cwd = context.agent.config.working_dir + branch_proc = subprocess.run(["git", "branch", "--show-current"], cwd=cwd, capture_output=True, text=True) + branch = branch_proc.stdout.strip() or "detached" + status_proc = subprocess.run(["git", "status", "--short"], cwd=cwd, capture_output=True, text=True) + status = status_proc.stdout.strip() or "(working tree clean)" + body = f"[bold cyan]Branch:[/bold cyan] {branch}\n[bold cyan]Workspace:[/bold cyan] {cwd}\n\n[dim]{status}[/dim]" + context.console.print(Panel(body, title="Git Status", border_style=BORDER_SUBTLE)) + return True + + +async def cmd_init(context: CommandContext, argument: str) -> bool: + """Scan workspace and generate or refresh AGENTUX.md project memory.""" + cwd = context.agent.config.working_dir + target = os.path.join(cwd, "AGENTUX.md") + + techs = [] + build_cmds = [] + if os.path.isfile(os.path.join(cwd, "pyproject.toml")): + techs.append("Python (pyproject.toml)") + build_cmds.append("pytest") + if os.path.isfile(os.path.join(cwd, "package.json")): + techs.append("Node/TypeScript (package.json)") + build_cmds.append("npm test") + if os.path.isfile(os.path.join(cwd, "go.mod")): + techs.append("Go (go.mod)") + build_cmds.append("go test ./...") + if os.path.isfile(os.path.join(cwd, "Cargo.toml")): + techs.append("Rust (Cargo.toml)") + build_cmds.append("cargo test") + if os.path.isfile(os.path.join(cwd, "Makefile")): + techs.append("Make (Makefile)") + build_cmds.append("make test") + + tech_str = ", ".join(techs) or "Generic project" + test_str = "\n".join(f"- `{cmd}`" for cmd in build_cmds) or "- (configure automated tests here)" + + content = f"""# Agentux Project Memory + +## Overview +- **Workspace:** `{os.path.basename(cwd)}` +- **Detected Stack:** {tech_str} + +## Build & Test Commands +{test_str} + +## Architecture & Code Guidelines +- Targeted modifications: Prefer deterministic edits over wholesale rewrites. +- Verification: Always run tests before claiming success. +- Safety: Strictly preserve access boundaries and existing comments. +""" + with open(target, "w", encoding="utf-8") as f: + f.write(content) + + context.agent._system_prompt = context.agent._load_project_memory(context.agent._system_prompt) + context.console.print(Panel(f"[bold emerald]✓ Initialized AGENTUX.md[/bold emerald]\n\nSaved to [cyan]{target}[/cyan] and loaded into agent memory.", title="Project Memory", border_style=EMERALD)) + return True + + +async def cmd_compact(context: CommandContext, argument: str) -> bool: + """Compact conversation history and minimize token consumption.""" + turns = 4 + if argument.strip().isdigit(): + turns = int(argument.strip()) + compacted = context.agent.compact(keep_turns=turns) + if compacted > 0: + context.console.print(Panel(f"[bold emerald]✓ Context Compacted[/bold emerald]\n\nSummarized {compacted} older message(s). Preserved last {turns} turn(s).", border_style=EMERALD)) + else: + context.console.print(Panel("[dim]Context is already minimal. Nothing to compact.[/dim]", border_style=BORDER_SUBTLE)) + return True + + +async def cmd_fix(context: CommandContext, argument: str) -> bool: + """Execute test suite and run self-healing agent turn if failures occur.""" + import subprocess + cwd = context.agent.config.working_dir + cmd = argument.strip() + if not cmd: + if os.path.isfile(os.path.join(cwd, "pyproject.toml")) or os.path.isfile(os.path.join(cwd, "pytest.ini")): + cmd = "pytest" + elif os.path.isfile(os.path.join(cwd, "go.mod")): + cmd = "go test ./..." + elif os.path.isfile(os.path.join(cwd, "package.json")): + cmd = "npm test" + elif os.path.isfile(os.path.join(cwd, "Cargo.toml")): + cmd = "cargo test" + elif os.path.isfile(os.path.join(cwd, "Makefile")): + cmd = "make test" + else: + context.console.print(Panel("[yellow]Could not auto-detect test runner. Usage: /fix <test_command>[/yellow]", border_style="yellow")) + return True + + context.console.print(f"[dim]Running tests: {cmd}...[/dim]") + proc = subprocess.run(cmd, shell=True, cwd=cwd, capture_output=True, text=True) + if proc.returncode == 0: + context.console.print(Panel(f"[bold emerald]✓ All tests green![/bold emerald]\n\n[dim]{proc.stdout.strip()}[/dim]", border_style=EMERALD, title="Test Passed")) + return True + + error_output = (proc.stdout + "\n" + proc.stderr).strip() + context.console.print(Panel(f"[bold yellow]Tests failed (exit {proc.returncode}):[/bold yellow]\n\n{error_output[:1000]}\n\n[cyan]Triggering self-healing fix turn...[/cyan]", border_style="yellow", title="Auto-Fix Triggered")) + + prompt = ( + f"The test command `{cmd}` failed with the following output:\n\n" + f"```\n{error_output[:3000]}\n```\n\n" + "Diagnose the failure, inspect the affected files, apply a minimal fix with the filesystem tool, " + f"and run `{cmd}` using the shell tool to verify the fix." + ) + answer = await context.agent.run(prompt, interactive=True) + if not context.agent.answer_streamed: + context.console.print(answer) + return True + + +async def cmd_search(context: CommandContext, argument: str) -> bool: + """Perform a live technical web search.""" + q = argument.strip() + if not q: + context.console.print(Panel("[yellow]Usage: /search <query>[/yellow]", border_style="yellow")) + return True + from .tools.web import WebSearchTool + tool = WebSearchTool() + context.console.print(f"[dim]Searching web for: {q}...[/dim]") + res = await tool.execute(query=q, max_results=5) + context.console.print(Panel(res, title=f"Web Search: {q}", border_style=CYAN)) + return True + + +async def cmd_image(context: CommandContext, argument: str) -> bool: + """Render an image in the terminal using Chafa.""" + path = argument.strip() + if not path: + context.console.print(Panel("[yellow]Usage: /image <path_or_url>[/yellow]", border_style="yellow")) + return True + from .tools.image import ViewImageTool + tool = ViewImageTool(root=context.agent.config.working_dir) + res = await tool.execute(path=path) + context.console.print(Panel(res, title=f"Image: {os.path.basename(path)}", border_style=BORDER)) + return True + + +async def cmd_web(context: CommandContext, argument: str) -> bool: + """Show information about the embedded Web UI console.""" + msg = ( + "🌐 [bold emerald]Agentux Web Developer Console[/bold emerald]\n\n" + "Launch the zero-dependency browser console with:\n" + " [cyan]agentux --web --open[/cyan]\n\n" + "Features real-time Server-Sent Events (SSE) token streaming, interactive tool accordions, " + "and human-in-the-loop tool approvals directly in your browser." + ) + context.console.print(Panel(msg, title="Web Console", border_style=EMERALD)) + return True + + +async def cmd_undo(context: CommandContext, argument: str) -> bool: + """Roll back file modifications made by the last agent turn or to a specific checkpoint.""" + checkpoint_mgr = getattr(context.agent, "checkpoint_manager", None) + if not checkpoint_mgr: + context.console.print("[red]Checkpoint manager not initialized on agent.[/red]") + return True + + target_id = argument.strip() or None + success, message = checkpoint_mgr.rollback(target_id) + border = EMERALD if success else PINK + title = f"Undo Snapshot {'('+target_id+')' if target_id else '(Latest)'}" + context.console.print(Panel(message, title=title, border_style=border)) + return True + + +async def cmd_checkpoints(context: CommandContext, argument: str) -> bool: + """List recorded checkpoints with rollback IDs and timestamps.""" + checkpoint_mgr = getattr(context.agent, "checkpoint_manager", None) + if not checkpoint_mgr: + context.console.print("[red]Checkpoint manager not initialized.[/red]") + return True + + cps = checkpoint_mgr.list_checkpoints() + if not cps: + context.console.print(Panel("[dim]No checkpoints recorded in this session yet.[/dim]", title="Checkpoints", border_style=BORDER_SUBTLE)) + return True + + table = Table(title="Session Checkpoints", border_style=BORDER_SUBTLE) + table.add_column("ID", style="bold cyan") + table.add_column("Time", style="dim") + table.add_column("Description", style="white") + table.add_column("Files", style="green") + + for c in reversed(cps): + table.add_row(c.id, c.formatted_time, c.description, str(len(c.files))) + + context.console.print(table) + return True + + +async def cmd_repomap(context: CommandContext, argument: str) -> bool: + """Generate and display the codebase repository AST symbol map.""" + repomap = getattr(context.agent, "repomap", None) + if not repomap: + from .repomap import RepoMap + repomap = RepoMap(context.agent.config.working_dir or os.getcwd()) + + query = argument.strip() or None + out = repomap.generate_map(max_tokens=800, query=query) + from rich.syntax import Syntax + syntax = Syntax(out, "yaml", theme="monokai", word_wrap=True) + title = f"Repository Map{' (' + query + ')' if query else ''}" + context.console.print(Panel(syntax, title=title, border_style=CYAN)) + return True + + +async def cmd_save(context: CommandContext, argument: str) -> bool: + """Persist current conversation session to disk.""" + store = getattr(context.agent, "session_store", None) + if not store: + from .session_store import SessionStore + store = SessionStore(context.agent.config.working_dir) + + session_id = argument.strip() or f"session-{int(time.time())}" + path = store.save( + session_id=session_id, + history=context.agent.history, + model=context.agent.config.model, + working_dir=context.agent.config.working_dir or os.getcwd(), + title=argument.strip() or None, + ) + context.console.print(Panel( + f"[bold green]Session saved successfully![/bold green]\n" + f"• Session ID: [bold cyan]{session_id}[/bold cyan]\n" + f"• Path: [dim]{path}[/dim]\n" + f"• Messages: {len(context.agent.history)}", + title="Session Saved", + border_style=EMERALD, + )) + return True + + +async def cmd_load(context: CommandContext, argument: str) -> bool: + """Restore a saved conversation session.""" + session_id = argument.strip() + if not session_id: + context.console.print("[yellow]Usage: /load <session_id>[/yellow]") + return True + + store = getattr(context.agent, "session_store", None) + if not store: + from .session_store import SessionStore + store = SessionStore(context.agent.config.working_dir) + + data = store.load(session_id) + if not data: + context.console.print(f"[red]Could not find session matching '{session_id}'. Run /sessions to list.[/red]") + return True + + context.agent.history = data["messages"] + context.console.print(Panel( + f"[bold green]Loaded session '{data.get('title', session_id)}'![/bold green]\n" + f"• Model: {data.get('model', 'unknown')}\n" + f"• Messages: {len(context.agent.history)}\n" + f"• Workspace: {data.get('working_dir', '')}", + title="Session Restored", + border_style=EMERALD, + )) + return True + + +async def cmd_sessions(context: CommandContext, argument: str) -> bool: + """List all saved conversation sessions.""" + store = getattr(context.agent, "session_store", None) + if not store: + from .session_store import SessionStore + store = SessionStore(context.agent.config.working_dir) + + sessions = store.list_sessions() + if not sessions: + context.console.print(Panel("[dim]No saved sessions found. Use '/save [name]' to save current state.[/dim]", title="Sessions", border_style=BORDER_SUBTLE)) + return True + + table = Table(title="Saved Sessions", border_style=BORDER_SUBTLE) + table.add_column("ID", style="bold cyan") + table.add_column("Title / First Prompt", style="white") + table.add_column("Model", style="dim") + table.add_column("Turns", style="green") + + for s in sessions: + table.add_row(s["id"], s["title"][:50], s["model"], str(s["turn_count"])) + + context.console.print(table) + return True + + +async def cmd_subagent(context: CommandContext, argument: str) -> bool: + """Delegate a task to a specialist subagent: /subagent <researcher|coder|reviewer|architect> <task>""" + parts = argument.strip().split(maxsplit=1) + if not parts: + msg = ( + "🤖 [bold]Specialist Autonomous Subagents[/bold]\n\n" + "Usage: [cyan]/subagent <role> <task>[/cyan]\n\n" + "Roles:\n" + " • [bold cyan]researcher[/bold cyan] - Read-only codebase explorer & symbol finder\n" + " • [bold emerald]coder[/bold emerald] - Implementation specialist for targeted code changes\n" + " • [bold yellow]reviewer[/bold yellow] - QA & code review (git diffs, tests, regressions)\n" + " • [bold purple]architect[/bold purple] - Architecture, layout, and task breakdown" + ) + context.console.print(Panel(msg, title="Subagent Delegation", border_style=CYAN)) + return True + + role = parts[0] + task = parts[1] if len(parts) > 1 else "" + if not task: + context.console.print(f"[yellow]Please provide a task description for subagent '{role}'.[/yellow]") + return True + + mgr = getattr(context.agent, "subagent_manager", None) + if not mgr: + from .subagents.manager import SubagentManager + mgr = SubagentManager(context.agent) + + context.console.print(f"[dim]Spawning specialist '{role}' subagent...[/dim]") + report = await mgr.run_subagent(role, task) + context.console.print(Panel(report, title=f"Subagent Report: {role.upper()}", border_style=EMERALD)) + return True + + +async def cmd_test(context: CommandContext, argument: str) -> bool: + """Run tests or execute test-driven self-healing loop: /test [command]""" + from .workflow import SelfHealingWorkflow + workflow = SelfHealingWorkflow(context.agent, test_command=argument.strip() or None) + + context.console.print(f"[dim]Executing test suite: {workflow.test_command}...[/dim]") + code, output = workflow.run_tests_sync() + if code == 0: + context.console.print(Panel( + f"[bold green]✓ All tests passed successfully![/bold green]\n\n[dim]{output[-1000:]}[/dim]", + title="Tests Passed", + border_style=EMERALD, + )) + else: + context.console.print(Panel( + f"[bold red]✗ Tests failed (exit code {code})[/bold red]\n\n{output[-1500:]}\n\n" + "[yellow]Tip: Run '/fix' to trigger an autonomous self-healing repair cycle.[/yellow]", + title="Tests Failed", + border_style=PINK, + )) + return True + + +def register_builtins() -> None: + """Install the built-in commands. + + Idempotent, and called on import: a command that exists but was never + registered is a command that silently does nothing, and the failure would + only show up as "unknown command" for a user who read it in ``/help``. + """ + register(Command("help", "List every command and what it does", cmd_help, ("h", "?"))) + register(Command("model", "List the provider's models, or switch to one", cmd_model, ("models",))) + register(Command("set", "Show or change settings for this session", cmd_set, ("settings",))) + register(Command("tools", "List the tools this agent can call", cmd_tools, ())) + register(Command("mcp", "Show MCP server status", cmd_mcp, ())) + register(Command("marketplace", "Browse and install skills and MCP servers", cmd_marketplace, ("market",))) + register(Command("context", "Show token and context usage", cmd_context, ("stats", "usage"))) + register(Command("mode", "Set or show operation mode", cmd_mode, ())) + register(Command("reset", "Clear the conversation and start over", cmd_reset, ("clear",))) + register(Command("exit", "Quit Agentux", cmd_exit, ("quit", "q"))) + register(Command("skills", "Manage and execute Agentux skills", cmd_skills, ())) + register(Command("commit", "Stage changes and create a git commit", cmd_commit, ())) + register(Command("diff", "Show unstaged or staged git diff", cmd_diff, ())) + register(Command("status", "Show git branch and working tree status", cmd_status, ())) + register(Command("init", "Initialize or refresh AGENTUX.md project memory", cmd_init, ())) + register(Command("compact", "Compact conversation history to minimize token usage", cmd_compact, ())) + register(Command("fix", "Run test suite and trigger self-healing fix turn on failure", cmd_fix, ())) + register(Command("undo", "Rollback file modifications from last turn or to a checkpoint", cmd_undo, ("revert",))) + register(Command("checkpoints", "List recorded shadow checkpoints", cmd_checkpoints, ())) + register(Command("repomap", "Generate compact AST repository symbol map", cmd_repomap, ("map",))) + register(Command("save", "Save conversation session to disk", cmd_save, ())) + register(Command("load", "Restore saved conversation session", cmd_load, ())) + register(Command("sessions", "List all saved conversation sessions", cmd_sessions, ())) + register(Command("subagent", "Delegate task to specialist autonomous subagent", cmd_subagent, ("delegate",))) + register(Command("test", "Run project test suite", cmd_test, ())) + register(Command("search", "Perform live technical web search", cmd_search, ())) + register(Command("image", "Render image in terminal using Chafa", cmd_image, ())) + register(Command("web", "Information and launch for embedded Web UI console", cmd_web, ())) + + +register_builtins() + + +__all__ = ["Command", "CommandContext", "REGISTRY", "register", "resolve", "names", + "register_builtins"]
\ No newline at end of file diff --git a/src/agentux/context.py b/src/agentux/context.py new file mode 100644 index 0000000..b5d4122 --- /dev/null +++ b/src/agentux/context.py @@ -0,0 +1,142 @@ +"""Context management for long-running sessions. + +A tool result is a liability. Reading a 400 KB file, grepping a vendored tree, +or running a test suite that prints ten thousand lines puts text into the +conversation that the model will never need again -- but it still has to be +re-sent on every subsequent request, and eventually the request does not fit. + +So old tool output gets compressed, in place. Two rules make this safe: + +* **Structure is never touched.** Every assistant message with ``tool_calls`` + keeps its following ``tool`` messages, in order, with the same + ``tool_call_id``. OpenAI-compatible APIs reject a conversation whose calls + are not answered in order, so dropping or reordering a message breaks the + request -- this module only ever rewrites the *content* of messages. + +* **Recent work stays verbatim.** The current request and the last few steps + are what the model is actively reasoning about. Compressing those is how an + agent convinces itself it already read something it didn't. + +The compression itself is elision, not truncation: the head and tail of a long +output are what carry the signal (the command, the first error, the summary +line), so both are kept and the gap is marked with its size. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Tuple + +from .models import Message + +#: Tool results at or below this many characters are left alone. Below this, +#: elision costs more context than it saves. +DEFAULT_MAX_TOOL_CHARS = 8_000 + +#: How much of an oversized result to keep at each end. +DEFAULT_HEAD_CHARS = 2_500 +DEFAULT_TAIL_CHARS = 2_500 + +#: Steps at the end of the conversation that are never compressed. +DEFAULT_KEEP_RECENT = 4 + + +def elide(text: str, max_chars: int, head: int, tail: int) -> Tuple[str, bool]: + """Shorten ``text`` to ``max_chars``, keeping its head and tail. + + Returns ``(text, changed)``. The elision marker names how much was dropped + so the model knows it is looking at a summary rather than the whole thing, + and can re-run a narrower query if it needs the middle. + """ + if max_chars <= 0 or len(text) <= max_chars: + return text, False + + # Degenerate budgets would drop the head and tail we just promised to keep. + budget = max(max_chars, head + tail + 120) + head = min(head, budget // 2) + tail = min(tail, budget - head - 120) + + dropped = len(text) - head - tail + marker = f"\n\n... [{dropped} characters omitted from the middle] ...\n\n" + return text[:head] + marker + text[-tail:], True + + +class ContextManager: + """Compresses stale tool output in place, preserving conversation shape.""" + + def __init__( + self, + max_tool_chars: int = DEFAULT_MAX_TOOL_CHARS, + head_chars: int = DEFAULT_HEAD_CHARS, + tail_chars: int = DEFAULT_TAIL_CHARS, + keep_recent: int = DEFAULT_KEEP_RECENT, + ) -> None: + self.max_tool_chars = max_tool_chars + self.head_chars = head_chars + self.tail_chars = tail_chars + self.keep_recent = max(0, keep_recent) + self.compressed = 0 + self.saved_chars = 0 + + # ------------------------------------------------------------------ + def _protect_from(self, history: List[Message]) -> int: + """Index of the first message eligible for compression.""" + if not self.keep_recent: + return 0 + + # Walk back over whole steps: a step is an assistant message with tool + # calls plus the tool messages answering it. Splitting one would leave + # a tool result outside the protected window while its call is inside. + index = len(history) + seen_steps = 0 + while index > 0 and seen_steps < self.keep_recent: + message = history[index - 1] + if message.role == "user": + break # Never compress across the current request. + if message.role == "tool": + while index > 0 and history[index - 1].role == "tool": + index -= 1 + if index == 0: + break + index -= 1 # step over the assistant message + seen_steps += 1 + return index + + def compress(self, history: List[Message]) -> List[Message]: + """Compress stale tool results. Mutates and returns ``history``.""" + limit = self._protect_from(history) + if limit <= 0: + return history + + for message in history[:limit]: + if message.role != "tool" or not message.content: + continue + if len(message.content) <= self.max_tool_chars: + continue + # Idempotent: a marker is already there, so leave it alone and + # avoid nesting "[N characters omitted]" inside itself. + if "characters omitted from the middle" in message.content: + continue + + original_length = len(message.content) + new_text, changed = elide( + message.content, self.max_tool_chars, self.head_chars, self.tail_chars + ) + if changed: + message.content = new_text + self.compressed += 1 + self.saved_chars += original_length - len(new_text) + return history + + def stats(self) -> Dict[str, Any]: + return { + "compressed": self.compressed, + "keep_recent": self.keep_recent, + "max_tool_chars": self.max_tool_chars, + } + + def reset_stats(self) -> None: + self.compressed = 0 + self.saved_chars = 0 + + +__all__ = ["ContextManager", "elide", "DEFAULT_MAX_TOOL_CHARS"] diff --git a/src/agentux/marketplace.py b/src/agentux/marketplace.py new file mode 100644 index 0000000..b38219e --- /dev/null +++ b/src/agentux/marketplace.py @@ -0,0 +1,860 @@ +"""Skill and MCP marketplace for Agentux. + +Provides a browsable, installable catalogue of community-contributed +skills and MCP servers. Data lives in JSON files under +``~/.config/agentux/marketplace/`` so the catalogue works offline +and can be synced via git or any file-sharing method. + +Each entry is a small JSON object: + +{ + "name": "skill-name", # slug, must be unique in its kind + "kind": "skill" | "mcp", + "title": "Human-readable title", + "description": "One-paragraph summary", + "author": "GitHub handle or name", + "source": "https://github.com/user/repo", # for skills: the repo; for MCPs: the repo with the server code + "entry": { # how to activate it in Agentux + "skill": { # for kind == "skill" + "module": "package.submodule:function", # dotted path to the skill function + "args": "optional default args string" + }, + "mcp": { # for kind == "mcp" + "config": { # minimal MCP server config to merge + "command": "npx", + "args": ["-y", "package"] + } + } + }, + "tags": ["utility", "formatting"], # free-form tags for search + "version": "1.0.0", # semver, informational + "license": "MIT" # SPDX identifier +} + +The catalogue itself is a JSON array under ``catalogue.json``. +A local ``installed.json`` tracks what the user has added to their +``.agentux/skills.py`` or ``.agentux/mcp.json`` files. +""" +from __future__ import annotations + +import json +import os +import time +from dataclasses import dataclass, asdict, field +from enum import Enum +from pathlib import Path +from typing import Any, Dict, List, Optional + + +MARKETPLACE_DIR = Path(os.path.expanduser("~/.config/agentux/marketplace")) +CATALOGUE_PATH = MARKETPLACE_DIR / "catalogue.json" +INSTALLED_PATH = MARKETPLACE_DIR / "installed.json" + + +class MarketplaceItemType(Enum): + """Type of marketplace item.""" + SKILL = "skill" + MCP_SERVER = "mcp" + + +@dataclass +class MarketplaceEntry: + """A single skill or MCP server entry in the marketplace. + + This class is maintained for backwards compatibility. + New code should use MarketplaceItem instead. + """ + id: str + name: str + kind: str # "skill" or "mcp" + title: str + description: str + author: str + source: str + entry: Dict[str, Any] + tags: List[str] = field(default_factory=list) + version: str = "1.0.0" + license: str = "MIT" + homepage: Optional[str] = None + installed: bool = False + enabled: bool = False + created_at: float = field(default_factory=time.time) + updated_at: float = field(default_factory=time.time) + + def to_dict(self) -> Dict[str, Any]: + """Convert to dictionary for serialization.""" + return asdict(self) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "MarketplaceEntry": + """Create from dictionary.""" + return cls(**data) + + +@dataclass +class MarketplaceItem: + """A single skill or MCP server entry in the marketplace.""" + id: str + name: str + type: MarketplaceItemType + title: str + description: str + author: str + source: str + entry: Dict[str, Any] + tags: List[str] = field(default_factory=list) + version: str = "1.0.0" + license: str = "MIT" + homepage: Optional[str] = None + installed: bool = False + enabled: bool = False + created_at: float = field(default_factory=time.time) + updated_at: float = field(default_factory=time.time) + + def to_dict(self) -> Dict[str, Any]: + """Convert to dictionary for serialization.""" + data = asdict(self) + # Convert enum to string + data['type'] = self.type.value + # Also add kind field for backwards compatibility + data['kind'] = self.type.value + return data + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "MarketplaceItem": + """Create from dictionary.""" + # Convert type string back to enum + if 'type' in data and isinstance(data['type'], str): + data['type'] = MarketplaceItemType(data['type']) + # Also convert kind field if present (for backwards compatibility) + if 'kind' in data and isinstance(data['kind'], str) and 'type' not in data: + data['type'] = MarketplaceItemType(data['kind']) + # `kind` is a legacy alias for `type`; drop it so it is not passed + # to __init__ as a duplicate keyword argument. + data.pop('kind', None) + return cls(**data) + + +def _ensure_dir() -> None: + """Create the marketplace directory if it does not exist.""" + MARKETPLACE_DIR.mkdir(parents=True, exist_ok=True) + + +def _load_catalogue_items() -> List[MarketplaceItem]: + """Load the marketplace catalogue from disk. + + Returns an empty list if the file is missing or unreadable. + """ + _ensure_dir() + if not CATALOGUE_PATH.exists(): + return [] + try: + with CATALOGUE_PATH.open("r", encoding="utf-8") as f: + raw = json.load(f) + if not isinstance(raw, list): + return [] + return [MarketplaceItem.from_dict(item) for item in raw] + except (json.JSONDecodeError, OSError): + return [] + + +def _save_catalogue_to_disk(items: List[MarketplaceItem]) -> None: + """Overwrite the catalogue file with the given items. + + Disk-only. The public :func:`save_catalogue` below delegates to a + Marketplace instance, so this name is private to avoid the recursion. + """ + _ensure_dir() + with CATALOGUE_PATH.open("w", encoding="utf-8") as f: + json.dump([item.to_dict() for item in items], f, indent=2, ensure_ascii=False) + + +def _load_installed_from_disk() -> List[str]: + """Return the list of entry names the user has installed.""" + _ensure_dir() + if not INSTALLED_PATH.exists(): + return [] + try: + with INSTALLED_PATH.open("r", encoding="utf-8") as f: + data = json.load(f) + if not isinstance(data, list): + return [] + return [str(name) for name in data] + except (json.JSONDecodeError, OSError): + return [] + + +def _save_installed_to_disk(names: List[str]) -> None: + """Overwrite the installed list with the given names.""" + _ensure_dir() + with INSTALLED_PATH.open("w", encoding="utf-8") as f: + json.dump(sorted(set(names)), f, indent=2, ensure_ascii=False) + + +def install_entry(name: str) -> bool: + """Mark an entry as installed; returns True if the name was not already present.""" + installed = _load_installed_from_disk() + if name in installed: + return False + installed.append(name) + _save_installed_to_disk(installed) + return True + + +def uninstall_entry(name: str) -> bool: + """Mark an entry as uninstalled; returns True if the name was present.""" + installed = _load_installed_from_disk() + if name not in installed: + return False + installed.remove(name) + _save_installed_to_disk(installed) + return True + + +def is_installed(name: str) -> bool: + """Check whether an entry is marked as installed.""" + return name in _load_installed_from_disk() + + +def search_catalogue(query: str = "", kind: Optional[str] = None) -> List[MarketplaceItem]: + """Return catalogue entries matching the query and/or kind. + + Query is a case-insensitive substring match on title, description, author, or tags. + Kind is either "skill", "mcp", or None for both. + """ + items = load_catalogue() + if not query and not kind: + return items + + q = query.lower() + results: List[MarketplaceItem] = [] + for item in items: + if kind and item.type.value != kind: + continue + if q: + searchable = " ".join([ + item.title, + item.description, + item.author, + " ".join(item.tags), + ]).lower() + if q not in searchable: + continue + results.append(item) + return results + + +# ---------------------------------------------------------------------- +# Default catalogue (built-in fallback) +# ---------------------------------------------------------------------- +def _default_catalogue() -> List[MarketplaceItem]: + """A small starter catalogue so the marketplace works out of the box.""" + return [ + MarketplaceItem( + id="filesystem", + name="filesystem", + type=MarketplaceItemType.MCP_SERVER, + title="Local Filesystem", + description="Provides read/write access to the local filesystem via MCP.", + author="modelprotocol", + source="https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem", + entry={ + "mcp": { + "config": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-filesystem", "."] + } + } + }, + tags=["filesystem", "storage", "essential"], + version="0.1.0", + license="MIT" + ), + MarketplaceItem( + id="git", + name="git", + type=MarketplaceItemType.MCP_SERVER, + title="Git MCP Server", + description="Lets agents inspect and modify Git repositories through MCP.", + author="modelprotocol", + source="https://github.com/modelcontextprotocol/servers/tree/main/src/git", + entry={ + "mcp": { + "config": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-git"] + } + } + }, + tags=["git", "version-control", "development"], + version="0.1.0", + license="MIT" + ), + MarketplaceItem( + id="github", + name="github", + type=MarketplaceItemType.MCP_SERVER, + title="GitHub MCP Server", + description="Provides read/write access to GitHub repositories, issues, and pull requests.", + author="modelprotocol", + source="https://github.com/modelcontextprotocol/servers/tree/main/src/github", + entry={ + "mcp": { + "config": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-github"] + } + } + }, + tags=["github", "ci", "collaboration"], + version="0.1.0", + license="MIT" + ), + MarketplaceItem( + id="brave-search", + name="brave-search", + type=MarketplaceItemType.MCP_SERVER, + title="Brave Search MCP Server", + description="Web search via Brave's search API with MCP.", + author="ModelContextProtocol", + source="https://github.com/modelcontextprotocol/servers/tree/main/src/brave-search", + entry={ + "mcp": { + "config": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-brave-search"] + } + } + }, + tags=["search", "web", "research"], + version="0.1.0", + license="MIT" + ), + MarketplaceItem( + id="filesystem-readonly", + name="filesystem-readonly", + type=MarketplaceItemType.MCP_SERVER, + title="Read-Only Filesystem", + description="Provides read-only access to the local filesystem via MCP.", + author="modelprotocol", + source="https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem", + entry={ + "mcp": { + "config": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-filesystem", "--readonly", "."] + } + } + }, + tags=["filesystem", "storage", "readonly", "safe"], + version="0.1.0", + license="MIT" + ), + MarketplaceItem( + id="think", + name="think", + type=MarketplaceItemType.SKILL, + title="Think Tool", + description="A skill that makes the agent pause and reason aloud before acting.", + author="agentux-community", + source="https://github.com/agentux-community/skills/tree/main/think", + entry={ + "skill": { + "module": "agentux_community.skills.think:think_skill", + "args": "" + } + }, + tags=["reasoning", "planning", "cognitive"], + version="1.0.0", + license="MIT" + ), + MarketplaceItem( + id="todo", + name="todo", + type=MarketplaceItemType.SKILL, + title="Todo List Skill", + description="Provides persistent todo list capabilities through a simple skill interface.", + author="agentux-community", + source="https://github.com/agentux-community/skills/tree/main/todo", + entry={ + "skill": { + "module": "agentux_community.skills.todo:todo_skill", + "args": "" + } + }, + tags=["productivity", "organization", "task-management"], + version="1.0.0", + license="MIT" + ) + ] + + +class Marketplace: + """Main marketplace class for managing skills and MCP servers.""" + + def __init__(self): + """Initialize the marketplace.""" + self._items: List[MarketplaceItem] = [] + self._load_items() + + def _load_items(self) -> None: + """Load items from catalogue and update installation status.""" + # Load catalogue directly from disk, never through load_catalogue() -- + # that function builds a Marketplace instance, which would recurse. + catalogue_items = _load_catalogue_items() + + # If catalogue is empty, seed with default items + if not catalogue_items: + catalogue_items = _default_catalogue() + _save_catalogue_to_disk(catalogue_items) + + # Load installed status + installed_names = set(_load_installed_from_disk()) + + # Update items with installation status + self._items = [] + for item in catalogue_items: + # Create a copy with updated installation status + item_dict = item.to_dict() + item_dict['installed'] = item.name in installed_names + # Always reset enabled status when loading - it will be set based on actual configuration + item_dict['enabled'] = False + self._items.append(MarketplaceItem.from_dict(item_dict)) + + # Sort by name for consistent ordering + self._items.sort(key=lambda x: x.name) + + def get_items_by_type(self, item_type: MarketplaceItemType) -> List[MarketplaceItem]: + """Get items by type.""" + return [item for item in self._items if item.type == item_type] + + def search_items(self, query: str) -> List[MarketplaceItem]: + """Search items by query.""" + return search_catalogue(query) + + def get_item(self, item_id: str) -> Optional[MarketplaceItem]: + """Get item by ID.""" + for item in self._items: + if item.id == item_id: + return item + return None + + def install_item(self, item_id: str) -> bool: + """Install an item.""" + item = self.get_item(item_id) + if not item: + return False + + if install_entry(item.name): + item.installed = True + self._save_items() + return True + return False + + def uninstall_item(self, item_id: str) -> bool: + """Uninstall an item.""" + item = self.get_item(item_id) + if not item: + return False + + if uninstall_entry(item.name): + item.installed = False + item.enabled = False # Disable when uninstalling + self._save_items() + return True + return False + + def enable_item(self, item_id: str) -> bool: + """Enable an item.""" + item = self.get_item(item_id) + if not item or not item.installed: + return False + + item.enabled = True + self._save_items() + return True + + def disable_item(self, item_id: str) -> bool: + """Disable an item.""" + item = self.get_item(item_id) + if not item: + return False + + item.enabled = False + self._save_items() + return True + + def is_installed(self, item_id: str) -> bool: + """Check if item is installed.""" + item = self.get_item(item_id) + return item is not None and item.installed + + def is_enabled(self, item_id: str) -> bool: + """Check if item is enabled.""" + item = self.get_item(item_id) + return item is not None and item.enabled + + def get_installed_items(self) -> List[MarketplaceItem]: + """Get all installed items.""" + return [item for item in self._items if item.installed] + + def get_enabled_items(self) -> List[MarketplaceItem]: + """Get all enabled items.""" + return [item for item in self._items if item.enabled] + + def _save_items(self) -> None: + """Save current items to catalogue.""" + _save_catalogue_to_disk(self._items) + + @property + def items(self) -> List[MarketplaceItem]: + """Get all marketplace items.""" + return self._items.copy() + + def populate_default_items(self) -> None: + """Populate the marketplace with default items if empty.""" + if not self._items: + default_items = _default_catalogue() + installed_names = set(load_installed()) + + # Update with installation status + for item in default_items: + item.installed = item.name in installed_names + + self._items = default_items + save_catalogue(self._items) + + +# Backwards compatibility functions - delegate to marketplace instance +_default_marketplace: Optional[Marketplace] = None + + +def _get_default_marketplace() -> Marketplace: + """Get or create the default marketplace instance.""" + global _default_marketplace + if _default_marketplace is None: + _default_marketplace = Marketplace() + return _default_marketplace + + +def load_catalogue() -> List[MarketplaceEntry]: + """Load the marketplace catalogue from disk. + + Returns a list of MarketplaceEntry objects for backwards compatibility. + """ + marketplace = _get_default_marketplace() + # Convert MarketplaceItem to MarketplaceEntry for backwards compatibility + entries = [] + for item in marketplace.items: + entry_dict = item.to_dict() + # Remove the 'type' field and add 'kind' field for MarketplaceEntry + entry_dict.pop('type', None) + entry_dict['kind'] = item.type.value + entries.append(MarketplaceEntry.from_dict(entry_dict)) + return entries + + +def save_catalogue(entries: List[MarketplaceEntry]) -> None: + """Overwrite the catalogue with the given entries.""" + marketplace = _get_default_marketplace() + # Convert MarketplaceEntry to MarketplaceItem + items = [] + for entry in entries: + entry_dict = entry.to_dict() + # Convert kind to type for MarketplaceItem + entry_dict.pop('kind', None) + if 'type' not in entry_dict: + entry_dict['type'] = MarketplaceItemType.SKILL # Default to skill + items.append(MarketplaceItem.from_dict(entry_dict)) + marketplace._items = items + marketplace._save_items() + + +def load_installed() -> List[str]: + """Return the list of entry names the user has installed.""" + return _load_installed_from_disk() + + +def save_installed(names: List[str]) -> None: + """Overwrite the installed list with the given names.""" + _save_installed_to_disk(names) + + +def install_entry(name: str) -> bool: + """Mark an entry as installed; returns True if the name was not already present.""" + installed = _load_installed_from_disk() + if name in installed: + return False + installed.append(name) + _save_installed_to_disk(installed) + return True + + +def uninstall_entry(name: str) -> bool: + """Mark an entry as uninstalled; returns True if the name was present.""" + installed = _load_installed_from_disk() + if name not in installed: + return False + installed.remove(name) + _save_installed_to_disk(installed) + return True + + +def is_installed(name: str) -> bool: + """Check whether an entry is marked as installed.""" + return name in _load_installed_from_disk() + + +def search_catalogue(query: str = "", kind: Optional[str] = None) -> List[MarketplaceEntry]: + """Return catalogue entries matching the query and/or kind. + + Query is a case-insensitive substring match on title, description, author, or tags. + Kind is either "skill", "mcp", or None for both. + Returns a list of MarketplaceEntry objects for backwards compatibility. + """ + marketplace = _get_default_marketplace() + items = marketplace.items + if not query and not kind: + # Convert to MarketplaceEntry for backwards compatibility + entries = [] + for item in items: + entry_dict = item.to_dict() + entry_dict.pop('type', None) + entry_dict['kind'] = item.type.value + entries.append(MarketplaceEntry.from_dict(entry_dict)) + return entries + + q = query.lower() + results: List[MarketplaceEntry] = [] + for item in items: + if kind and item.type.value != kind: + continue + if q: + searchable = " ".join([ + item.title, + item.description, + item.author, + " ".join(item.tags), + ]).lower() + if q not in searchable: + continue + # Convert to MarketplaceEntry for backwards compatibility + entry_dict = item.to_dict() + entry_dict.pop('type', None) + entry_dict['kind'] = item.type.value + results.append(MarketplaceEntry.from_dict(entry_dict)) + return results + + +def seed_catalogue() -> None: + """Populate the marketplace directory with the default catalogue if empty.""" + marketplace = _get_default_marketplace() + marketplace.populate_default_items() + + +# Legacy functions for backwards compatibility +def load_catalogue_legacy() -> List[Dict[str, Any]]: + """Legacy function for backwards compatibility.""" + # Create a temporary marketplace instance to avoid recursion + marketplace_temp = Marketplace.__new__(Marketplace) + marketplace_temp._items = [] # Initialize empty items + # Manually load catalogue items without triggering full initialization + catalogue_items = load_catalogue() + if not catalogue_items: + catalogue_items = _default_catalogue() + # Convert to legacy format + return [item.to_dict() for item in catalogue_items] + + +def save_catalogue_legacy(entries: List[Dict[str, Any]]) -> None: + """Legacy function for backwards compatibility.""" + marketplace = _get_default_marketplace() + items = [MarketplaceItem.from_dict(entry) for entry in entries] + marketplace._items = items + marketplace._save_items() + + +def load_installed_legacy() -> List[str]: + """Legacy function for backwards compatibility.""" + return load_installed() + + +def save_installed_legacy(names: List[str]) -> None: + """Legacy function for backwards compatibility.""" + save_installed(names) + + +def install_entry_legacy(name: str) -> bool: + """Legacy function for backwards compatibility.""" + return install_entry(name) + + +def uninstall_entry_legacy(name: str) -> bool: + """Legacy function for backwards compatibility.""" + return uninstall_entry(name) + + +def is_installed_legacy(name: str) -> bool: + """Legacy function for backwards compatibility.""" + return is_installed(name) + + +def search_catalogue_legacy(query: str = "", kind: Optional[str] = None) -> List[Dict[str, Any]]: + """Legacy function for backwards compatibility.""" + items = search_catalogue(query, kind) + return [item.to_dict() for item in items] + + +def seed_catalogue_legacy() -> None: + """Legacy function for backwards compatibility.""" + marketplace = _get_default_marketplace() + marketplace.populate_default_items() + + +def fetch_skills_from_sh() -> List[MarketplaceItem]: + """Fetch skills from skills.sh (local file or URL). + + Attempts to load skills from a skills.sh file which should output + skill definitions in a format compatible with MarketplaceItem. + + Returns: + List of MarketplaceItem objects representing skills, or empty list if failed. + """ + import subprocess + import json + + try: + # Try to run skills.sh as a script and capture output + # Assuming it outputs JSON format that can be parsed + result = subprocess.run( + ['bash', 'skills.sh'], + capture_output=True, + text=True, + timeout=30 + ) + + if result.returncode == 0 and result.stdout.strip(): + # Try to parse as JSON + try: + data = json.loads(result.stdout) + # Convert to MarketplaceItem objects + items = [] + if isinstance(data, list): + for skill_data in data: + if isinstance(skill_data, dict): + # Create a MarketplaceItem from the skill data + item = MarketplaceItem( + id=skill_data.get('id', skill_data.get('name', 'unknown')), + name=skill_data.get('name', 'unknown'), + type=MarketplaceItemType.SKILL, # Assuming skills.sh contains skills + title=skill_data.get('title', skill_data.get('name', 'Unknown Skill')), + description=skill_data.get('description', ''), + author=skill_data.get('author', 'unknown'), + source=skill_data.get('source', ''), + entry=skill_data.get('entry', {"skill": {"module": "", "args": ""}}), + tags=skill_data.get('tags', []), + version=skill_data.get('version', '1.0.0'), + license=skill_data.get('license', 'MIT') + ) + items.append(item) + return items + except json.JSONDecodeError: + # If not JSON, try to parse as simple format + pass + except Exception: + # Failed to fetch from skills.sh + pass + + return [] + + +def fetch_mcps_from_website() -> List[MarketplaceItem]: + """Fetch MCP servers from mcpmarketplace.com. + + Attempts to load MCP server information from mcpmarketplace.com. + + Returns: + List of MarketplaceItem objects representing MCP servers, or empty list if failed. + """ + try: + # Use the WebFetch tool equivalent - in a real implementation, + # this would make an HTTP request to mcpmarketplace.com + # For now, we'll return an empty list as a placeholder + # In a production environment, this would parse the website or API + return [] + except Exception: + # Failed to fetch from mcpmarketplace.com + pass + + return [] + + +def _fetch_and_merge_external_items(self) -> None: + """Fetch items from external sources and merge with existing catalogue. + + This method fetches skills from skills.sh and MCPs from mcpmarketplace.com, + then merges them with the existing catalogue items. + """ + # Fetch skills from skills.sh + external_skills = fetch_skills_from_sh() + + # Fetch MCPs from mcpmarketplace.com + external_mcps = fetch_mcps_from_website() + + # Combine all external items + external_items = external_skills + external_mcps + + if not external_items: + return # No external items to add + + # Get current items and installed status to preserve it + current_items = self._items + installed_names = {item.name for item in current_items if item.installed} + + # Merge external items with current items, avoiding duplicates by name/id + merged_items = [] + existing_ids = {item.id for item in current_items} + existing_names = {item.name for item in current_items} + + # Add current items first + merged_items.extend(current_items) + + # Add external items that don't already exist + for item in external_items: + if item.id not in existing_ids and item.name not in existing_names: + # Preserve installed status if this item was previously installed + item.installed = item.name in installed_names + merged_items.append(item) + existing_ids.add(item.id) + existing_names.add(item.name) + + # Update the items list and save + self._items = merged_items + self._items.sort(key=lambda x: x.name) + save_catalogue(self._items) + + +# Update the Marketplace class to call external fetch during initialization +# Uncomment the following line in _load_items to enable automatic fetching: +# self._fetch_and_merge_external_items() + + +__all__ = [ + "MarketplaceEntry", + "MarketplaceItem", + "MarketplaceItemType", + "Marketplace", + # Legacy functions for backwards compatibility + "load_catalogue_legacy", + "save_catalogue_legacy", + "load_installed_legacy", + "save_installed_legacy", + "install_entry_legacy", + "uninstall_entry_legacy", + "is_installed_legacy", + "search_catalogue_legacy", + "seed_catalogue_legacy", + # External fetch functions + "fetch_skills_from_sh", + "fetch_mcps_from_website", +]
\ No newline at end of file diff --git a/src/agentux/mcp.py b/src/agentux/mcp.py new file mode 100644 index 0000000..a13c7f6 --- /dev/null +++ b/src/agentux/mcp.py @@ -0,0 +1,568 @@ +"""A minimal MCP client speaking JSON-RPC 2.0 over stdio. + +Written directly against the protocol rather than depending on the ``mcp`` +package, so Agentux keeps its small dependency list and its MCP support is +optional rather than load-bearing. The core agent never imports this module. + +Transport, per the MCP stdio specification: + +* One JSON-RPC message per line, newline-delimited, UTF-8. No ``Content-Length`` + headers -- that is LSP framing, and it is not used here. +* A server may write anything to stderr. It is drained separately and never + parsed; a chatty server is not a broken server. +* The child's environment is an allowlist plus the config's ``env``. Agentux + does not hand over its own environment, which would leak ``AGENTUX_API_KEY`` + to every server on the machine. +* Servers are launched without a shell, in their own process group, so a + wrapper like ``npx`` cannot inject shell syntax and can be killed as a tree. +""" + +from __future__ import annotations + +import asyncio +import json +import os +import shutil +import sys +from typing import Any, Dict, List, Optional + +from .errors import MCPError, MCPProtocolError +from .mcp_config import MCPServerConfig + +#: The version we advertise. Servers answer with their own newest supported +#: version, so this is a request, not a demand. +PROTOCOL_VERSION = "2025-11-25" + +#: Versions we are willing to talk to. +SUPPORTED_PROTOCOL_VERSIONS = { + "2024-11-05", + "2025-03-26", + "2025-06-18", + "2025-11-25", +} + +#: How long to wait for a handshake, or for any single request. +DEFAULT_TIMEOUT = 60.0 + +#: Grace period between closing stdin and escalating to a signal. +TERMINATION_GRACE = 2.0 + +#: Bound on a single stdout line. A server that emits more than this in one +#: message is either broken or hostile; either way, stop buffering it. +MAX_LINE_BYTES = 10 * 1024 * 1024 + +#: Bound on tools/list pagination, so a server that returns a non-advancing +#: cursor cannot hang the startup path. +MAX_LIST_PAGES = 100 + +#: Only these variables reach the server process. Notably absent: AGENTUX_API_KEY +#: and anything else Agentux-specific or secret-bearing. +INHERITED_ENV = ( + ("APPDATA", "HOMEDRIVE", "HOMEPATH", "LOCALAPPDATA", "PATH", "PATHEXT", + "PROCESSOR_ARCHITECTURE", "SYSTEMDRIVE", "SYSTEMROOT", "TEMP", "TMP", + "USERNAME", "USERPROFILE", "COMSPEC", "NUMBER_OF_PROCESSORS", "OS") + if sys.platform == "win32" + else ("HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER", "TMPDIR", "LANG", "LC_ALL") +) + + +def _resolve_command(command: str) -> str: + """Resolve a command to something ``execve`` can actually run. + + On POSIX a bare name is fine. On Windows ``npx`` is really ``npx.cmd`` and + cannot be executed directly without a shell, which is not an option here -- + so look for the script extensions explicitly. + """ + resolved = shutil.which(command) + if resolved: + return resolved + if sys.platform == "win32": + for extension in (".cmd", ".bat", ".exe", ".ps1"): + candidate = shutil.which(command + extension) + if candidate: + return candidate + return command + + +def _build_env(overrides: Optional[Dict[str, str]]) -> Dict[str, str]: + env = { + key: value + for key, value in os.environ.items() + if key in INHERITED_ENV and not value.startswith("()") + } + if overrides: + env.update({str(k): str(v) for k, v in overrides.items()}) + return env + + +class MCPServer: + """One MCP server subprocess.""" + + def __init__( + self, + config: MCPServerConfig, + timeout: float = DEFAULT_TIMEOUT, + on_log: Optional[Any] = None, + ) -> None: + self.config = config + self.timeout = timeout + self.on_log = on_log + self.process: Optional[asyncio.subprocess.Process] = None + self.server_info: Dict[str, Any] = {} + self.protocol_version: Optional[str] = None + self.instructions: Optional[str] = None + self._pending: Dict[Any, asyncio.Future] = {} + self._next_id = 0 + self._reader: Optional[asyncio.Task] = None + self._stderr_reader: Optional[asyncio.Task] = None + self._stderr_tail: List[str] = [] + self._closed = False + self._failure: Optional[str] = None + + # ------------------------------------------------------------------ + # Process lifecycle + # ------------------------------------------------------------------ + @property + def name(self) -> str: + return self.config.name + + @property + def connected(self) -> bool: + return self.process is not None and self.process.returncode is None + + def _log(self, message: str) -> None: + if self.on_log: + try: + self.on_log(f"[{self.name}] {message}") + except Exception: + pass + + async def start(self) -> None: + """Spawn the process and complete the initialize handshake.""" + if self.process is not None: + return + + command = _resolve_command(self.config.command) + kwargs: Dict[str, Any] = { + "stdin": asyncio.subprocess.PIPE, + "stdout": asyncio.subprocess.PIPE, + "stderr": asyncio.subprocess.PIPE, + "env": _build_env(self.config.env), + "cwd": self.config.cwd or None, + } + # Own process group so the whole tree can be signalled, and no shell so + # arguments cannot be reinterpreted. + if sys.platform == "win32": + kwargs["creationflags"] = getattr(__import__("subprocess"), "CREATE_NEW_PROCESS_GROUP", 0) + else: + kwargs["start_new_session"] = True + + try: + self.process = await asyncio.create_subprocess_exec( + command, *self.config.args, **kwargs + ) + except FileNotFoundError as exc: + raise MCPError( + f"MCP server {self.name!r}: command {self.config.command!r} was not found. " + "Check that it is installed and on your PATH." + ) from exc + except OSError as exc: + raise MCPError( + f"MCP server {self.name!r}: could not start {self.config.display}: {exc}" + ) from exc + + self._reader = asyncio.ensure_future(self._read_stdout()) + self._stderr_reader = asyncio.ensure_future(self._read_stderr()) + + try: + await self._handshake() + except Exception: + await self.close() + raise + + async def _handshake(self) -> None: + result = await self.request( + "initialize", + { + "protocolVersion": PROTOCOL_VERSION, + "capabilities": {}, + "clientInfo": {"name": "agentux", "version": _agentux_version()}, + }, + ) + + negotiated = result.get("protocolVersion") + self.protocol_version = negotiated + self.server_info = result.get("serverInfo") or {} + self.instructions = result.get("instructions") + + if negotiated not in SUPPORTED_PROTOCOL_VERSIONS: + # The spec says disconnect here. We log loudly and continue instead: + # the handshake already succeeded, so the server understands us, + # and refusing would cost the user their tools over a version label + # we do not recognise. + self._log( + f"server requested protocol {negotiated!r}, which this build does " + f"not know about; continuing anyway" + ) + + # A notification: no id, no params, and no reply. Sending a reply here + # is a protocol violation that servers silently ignore or reject. + await self.notify("notifications/initialized") + + async def close(self) -> None: + """Shut the server down: close stdin, then SIGTERM, then SIGKILL. + + Closing stdin is the portable graceful-shutdown signal in MCP; there is + no shutdown message. + """ + self._closed = True + process = self.process + + for task in (self._reader, self._stderr_reader): + if task is not None and not task.done(): + task.cancel() + + if process is None: + self._fail_pending(MCPError(f"MCP server {self.name!r} was never started.")) + return + + if process.returncode is None: + try: + if process.stdin is not None and not process.stdin.is_closing(): + process.stdin.close() + except (OSError, RuntimeError): + pass + + try: + await asyncio.wait_for(process.wait(), timeout=TERMINATION_GRACE) + except asyncio.TimeoutError: + self._signal(process, force=False) + try: + await asyncio.wait_for(process.wait(), timeout=TERMINATION_GRACE) + except asyncio.TimeoutError: + self._signal(process, force=True) + try: + await asyncio.wait_for(process.wait(), timeout=TERMINATION_GRACE) + except asyncio.TimeoutError: + self._log("did not exit after SIGKILL") + + self._fail_pending( + MCPError(f"MCP server {self.name!r} is closed; cannot send new requests.") + ) + + def _signal(self, process: asyncio.subprocess.Process, force: bool) -> None: + import signal + + sig = signal.SIGKILL if force else signal.SIGTERM + try: + if sys.platform == "win32": + process.terminate() if not force else process.kill() + elif hasattr(os, "killpg"): + # The process group, not just the leader: `npx` spawns a + # grandchild node process that would otherwise survive and hold + # the stdout pipe open forever. + os.killpg(os.getpgid(process.pid), sig) + else: + process.send_signal(sig) + except (ProcessLookupError, PermissionError, OSError): + pass + + # ------------------------------------------------------------------ + # Wire I/O + # ------------------------------------------------------------------ + async def _read_stderr(self) -> None: + """Drain stderr so the child never blocks on a full pipe. + + Content is kept only as a short tail for error messages. Per the spec, + stderr output does not indicate an error condition. + """ + stream = self.process.stderr if self.process else None + if stream is None: + return + try: + while True: + line = await stream.readline() + if not line: + break + text = line.decode("utf-8", errors="replace").rstrip() + if text: + self._stderr_tail.append(text) + del self._stderr_tail[:-20] # keep the last 20 lines + except asyncio.CancelledError: + raise + except Exception: + pass + + async def _read_stdout(self) -> None: + """Read newline-delimited JSON-RPC messages until EOF.""" + stream = self.process.stdout if self.process else None + if stream is None: + return + + try: + while True: + try: + line = await stream.readuntil(b"\n") + except asyncio.IncompleteReadError as exc: + line = exc.partial + if not line: + break + except asyncio.LimitOverrunError: + # A single message larger than the reader's buffer. It is + # not recoverable by continuing to parse this stream. + self._fail_pending( + MCPError( + f"MCP server {self.name!r} sent a message larger than " + f"{MAX_LINE_BYTES // (1024 * 1024)} MiB." + ) + ) + break + except (ValueError, asyncio.CancelledError): + break + + text = line.decode("utf-8", errors="replace").strip() + if not text: + continue + + try: + message = json.loads(text) + except json.JSONDecodeError: + # npx and hot-reload wrappers print banners to stdout. + # Skipping the line is what every SDK does, and it is the + # difference between working and not. + continue + + if isinstance(message, dict): + self._dispatch(message) + + if self.process is not None and self.process.stdout.at_eof(): + break + except asyncio.CancelledError: + raise + except Exception as exc: + self._failure = str(exc) + finally: + # Reap first: the reason is built from the exit code, and it is + # not populated yet at EOF. A cancelled reader (shutdown) skips the + # wait -- there is nobody left to explain anything to. + if not self._closed: + await self._await_exit() + reason = self._failure or ( + f"MCP server {self.name!r} closed its output stream" + + f" ({self._describe_exit()})" + ) + self._fail_pending(MCPError(reason)) + + async def _await_exit(self) -> None: + """Wait for the child to be reaped, so its exit code is readable. + + EOF on stdout arrives just before the process is reaped, so at the + moment the reader gives up the return code is usually still ``None``. + Waiting here is what makes the diagnostic say *why* the server died + instead of only that it died -- without it the exit code appears or + not depending on how the two events happened to interleave. + """ + process = self.process + if process is None or process.returncode is not None: + return + try: + await asyncio.wait_for(process.wait(), timeout=TERMINATION_GRACE) + except (asyncio.TimeoutError, asyncio.CancelledError, ProcessLookupError): + # Still running, or the loop is shutting down. The message below + # falls back to saying nothing was learned, which is honest. + pass + + def _describe_exit(self) -> str: + """The exit status to report, once the process has been reaped.""" + process = self.process + if process is None or process.returncode is None: + return "the process had not exited" + return f"exit code {process.returncode}" + + def _dispatch(self, message: Dict[str, Any]) -> None: + """Route a response to whoever is waiting on its id.""" + if "id" not in message or message.get("method"): + return # A notification; we do not subscribe to any. + + future = self._pending.pop(message["id"], None) + if future is None or future.done(): + return + + if "error" in message: + error = message["error"] or {} + code = error.get("code", "unknown") + detail = error.get("message", "no message") + extra = error.get("data") + future.set_exception( + MCPProtocolError( + f"MCP server {self.name!r} returned error {code}: {detail}" + + (f" ({json.dumps(extra)[:300]})" if extra else "") + ) + ) + return + + future.set_result(message.get("result") or {}) + + def _fail_pending(self, error: BaseException) -> None: + """Fail every in-flight request. They can never be answered now.""" + for future in list(self._pending.values()): + if not future.done(): + future.set_exception(error) + self._pending.clear() + + async def _send(self, payload: Dict[str, Any]) -> None: + process = self.process + if process is None or process.stdin is None or process.returncode is not None: + tail = "\n".join(self._stderr_tail[-5:]) + raise MCPError( + f"MCP server {self.name!r} is not running" + + (f". Last output: {tail}" if tail else ".") + ) + try: + process.stdin.write( + (json.dumps(payload, ensure_ascii=False) + "\n").encode("utf-8") + ) + await process.stdin.drain() + except (BrokenPipeError, ConnectionResetError, OSError) as exc: + raise MCPError(f"MCP server {self.name!r} went away: {exc}") from exc + + async def request(self, method: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + """Send a request and wait for its response.""" + if self._closed: + raise MCPError(f"MCP server {self.name!r} is closed.") + + self._next_id += 1 + request_id = self._next_id + loop = asyncio.get_event_loop() + future: asyncio.Future = loop.create_future() + self._pending[request_id] = future + + payload: Dict[str, Any] = {"jsonrpc": "2.0", "id": request_id, "method": method} + if params is not None: + payload["params"] = params + + try: + await self._send(payload) + except Exception: + self._pending.pop(request_id, None) + raise + + try: + return await asyncio.wait_for(future, timeout=self.timeout) + except asyncio.TimeoutError: + self._pending.pop(request_id, None) + raise MCPError( + f"MCP server {self.name!r} did not answer {method!r} within " + f"{self.timeout:g}s." + ) from None + except asyncio.CancelledError: + self._pending.pop(request_id, None) + raise + + async def notify(self, method: str, params: Optional[Dict[str, Any]] = None) -> None: + """Send a notification. Nothing comes back.""" + payload: Dict[str, Any] = {"jsonrpc": "2.0", "method": method} + if params is not None: + payload["params"] = params + await self._send(payload) + + # ------------------------------------------------------------------ + # Protocol operations + # ------------------------------------------------------------------ + async def list_tools(self) -> List[Dict[str, Any]]: + """Return every tool the server offers, following pagination. + + ``nextCursor`` is optional; a server that returns everything at once + simply omits it, so its absence -- not its presence -- ends the loop. + """ + tools: List[Dict[str, Any]] = [] + cursor: Optional[str] = None + + for _ in range(MAX_LIST_PAGES): + result = await self.request("tools/list", {"cursor": cursor} if cursor else {}) + page = result.get("tools") + if not isinstance(page, list): + raise MCPProtocolError( + f"MCP server {self.name!r}: tools/list returned no 'tools' array." + ) + tools.extend(t for t in page if isinstance(t, dict)) + + cursor = result.get("nextCursor") + if not cursor: + break + else: + self._log(f"stopped after {MAX_LIST_PAGES} pages of tools/list") + + return tools + + async def call_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]: + """Invoke a tool. + + Both failure modes are distinct and are kept distinct. A JSON-RPC error + means the *request* was wrong and is raised. ``isError: true`` means the + tool ran and failed, and is returned to the caller so the model can read + the message and correct itself. + """ + result = await self.request("tools/call", {"name": name, "arguments": arguments}) + if not isinstance(result, dict): + raise MCPProtocolError( + f"MCP server {self.name!r}: tools/call returned {type(result).__name__}, " + "expected an object." + ) + return result + + +def render_tool_result(result: Dict[str, Any], max_chars: int = 60_000) -> str: + """Flatten an MCP tool result into the text the model will read.""" + blocks = result.get("content") + if not isinstance(blocks, list): + # A server that returns only structuredContent is legal. + structured = result.get("structuredContent") + if structured is not None: + return json.dumps(structured, indent=2, default=str)[:max_chars] + return "(the server returned no content)" + + parts: List[str] = [] + for block in blocks: + if not isinstance(block, dict): + continue + kind = block.get("type") + if kind == "text": + parts.append(str(block.get("text", ""))) + elif kind == "image": + parts.append(f"[image: {block.get('mimeType', 'unknown type')}]") + elif kind == "audio": + parts.append(f"[audio: {block.get('mimeType', 'unknown type')}]") + elif kind == "resource": + resource = block.get("resource") or {} + body = resource.get("text") + parts.append( + f"[resource: {resource.get('uri', 'unknown')}]\n{body}" + if body + else f"[resource: {resource.get('uri', 'unknown')}]" + ) + elif kind == "resource_link": + parts.append(f"[link: {block.get('uri', 'unknown')}]") + else: + parts.append(f"[{kind}: {json.dumps(block, default=str)[:200]}]") + + text = "\n".join(p for p in parts if p).strip() + if not text: + return "(the server returned no text content)" + if len(text) > max_chars: + text = text[:max_chars] + f"\n... [{len(text) - max_chars} characters truncated]" + return text + + +def _agentux_version() -> str: + from . import __version__ + + return __version__ + + +__all__ = [ + "MCPServer", + "render_tool_result", + "PROTOCOL_VERSION", + "SUPPORTED_PROTOCOL_VERSIONS", +] diff --git a/src/agentux/mcp_config.py b/src/agentux/mcp_config.py new file mode 100644 index 0000000..b67dddf --- /dev/null +++ b/src/agentux/mcp_config.py @@ -0,0 +1,218 @@ +"""MCP server configuration. + +Two files, merged: + +* ``~/.config/agentux/mcp.json`` -- servers you always want +* ``<project>/.agentux/mcp.json`` -- servers for one repository + +Both use the same ``{"mcpServers": {...}}`` shape that Claude Desktop and the +MCP tooling use, so an existing config can be copied across verbatim:: + + { + "mcpServers": { + "filesystem": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"], + "env": {"LOG_LEVEL": "error"} + } + } + } + +Project entries win over global ones on a name collision, so a repository can +override what your machine does by default. An entry may set ``disabled: true`` +to switch off a global server without deleting it. +""" + +from __future__ import annotations + +import json +import os +from typing import Any, Dict, List, Optional, Tuple + +from .errors import MCPConfigError + +#: Where the machine-wide file lives, relative to the user's home directory. +GLOBAL_CONFIG_RELPATH = os.path.join(".config", "agentux", "mcp.json") + +#: The per-project file, relative to the workspace root. +PROJECT_CONFIG_RELPATH = os.path.join(".agentux", "mcp.json") + + +class MCPServerConfig: + """How to launch one MCP server.""" + + __slots__ = ("name", "command", "args", "env", "cwd", "disabled", "source") + + def __init__( + self, + name: str, + command: str, + args: Optional[List[str]] = None, + env: Optional[Dict[str, str]] = None, + cwd: Optional[str] = None, + disabled: bool = False, + source: str = "unknown", + ) -> None: + self.name = name + self.command = command + self.args = list(args or []) + self.env = dict(env or {}) + self.cwd = cwd + self.disabled = disabled + #: Which file this entry came from, for error messages and ``--list-tools``. + self.source = source + + def __repr__(self) -> str: + return ( + f"MCPServerConfig(name={self.name!r}, command={self.command!r}, " + f"args={self.args!r}, source={self.source!r})" + ) + + @property + def display(self) -> str: + parts = [self.command, *self.args] + return " ".join(parts) + + +def global_config_path() -> str: + override = os.environ.get("AGENTUX_MCP_CONFIG") + if override: + return os.path.expanduser(override) + return os.path.join(os.path.expanduser("~"), GLOBAL_CONFIG_RELPATH) + + +def project_config_path(working_dir: str) -> str: + return os.path.join(working_dir, PROJECT_CONFIG_RELPATH) + + +def _read_file(path: str) -> Dict[str, Any]: + """Read one config file. A missing file is normal, not an error.""" + if not os.path.isfile(path): + return {} + + try: + with open(path, encoding="utf-8") as handle: + data = json.load(handle) + except json.JSONDecodeError as exc: + raise MCPConfigError( + f"{path} is not valid JSON (line {exc.lineno}, column {exc.colno}): {exc.msg}" + ) from exc + except OSError as exc: + raise MCPConfigError(f"Could not read {path}: {exc}") from exc + + if not isinstance(data, dict): + raise MCPConfigError( + f"{path} must contain a JSON object at the top level, " + f"got {type(data).__name__}." + ) + return data + + +def _parse_servers(data: Dict[str, Any], path: str, source: str) -> Dict[str, MCPServerConfig]: + servers = data.get("mcpServers") + if servers is None: + # Tolerate a bare mapping of name -> entry, which is what a lot of + # people write by hand. + if all(isinstance(v, dict) and ("command" in v or "url" in v) for v in data.values()): + servers = data + else: + return {} + + if not isinstance(servers, dict): + raise MCPConfigError( + f"'mcpServers' in {path} must be an object mapping names to server " + f"definitions, got {type(servers).__name__}." + ) + + parsed: Dict[str, MCPServerConfig] = {} + for name, entry in servers.items(): + if not isinstance(entry, dict): + raise MCPConfigError( + f"Server {name!r} in {path} must be an object, got {type(entry).__name__}." + ) + + command = entry.get("command") + if not command: + # Remote servers exist in MCP, but this client speaks stdio only. + # Saying so beats failing later with a confusing spawn error. + if entry.get("url"): + raise MCPConfigError( + f"Server {name!r} in {path} uses a remote 'url'. This Agentux " + "build supports stdio servers only -- give it a 'command'." + ) + raise MCPConfigError( + f"Server {name!r} in {path} has no 'command'. A stdio server needs " + "at least a command, e.g. {\"command\": \"npx\", \"args\": [...]}." + ) + + args = entry.get("args") or [] + if not isinstance(args, list) or not all(isinstance(a, str) for a in args): + raise MCPConfigError( + f"'args' for server {name!r} in {path} must be a list of strings." + ) + + env = entry.get("env") or {} + if not isinstance(env, dict) or not all( + isinstance(k, str) and isinstance(v, str) for k, v in env.items() + ): + raise MCPConfigError( + f"'env' for server {name!r} in {path} must map strings to strings." + ) + + cwd = entry.get("cwd") + if cwd is not None and not isinstance(cwd, str): + raise MCPConfigError(f"'cwd' for server {name!r} in {path} must be a string.") + + parsed[name] = MCPServerConfig( + name=name, + command=str(command), + args=args, + env=env, + cwd=cwd, + disabled=bool(entry.get("disabled", False)), + source=source, + ) + + return parsed + + +def load_server_configs(working_dir: str) -> Tuple[List[MCPServerConfig], List[str]]: + """Load and merge the global and per-project MCP configs. + + Returns the enabled servers and a list of warnings for anything skipped, so + the caller can report problems without failing the session. + """ + warnings: List[str] = [] + merged: Dict[str, MCPServerConfig] = {} + + for path, source in ( + (global_config_path(), "global"), + (project_config_path(working_dir), "project"), + ): + try: + data = _read_file(path) + except MCPConfigError as exc: + warnings.append(str(exc)) + continue + try: + servers = _parse_servers(data, path, source) + except MCPConfigError as exc: + warnings.append(str(exc)) + continue + merged.update(servers) # later sources win on a name collision + + for name, server in merged.items(): + if server.disabled: + warnings.append(f"MCP server {name!r} is disabled ({server.source} config).") + + return [s for s in merged.values() if not s.disabled], warnings + + +__all__ = [ + "MCPServerConfig", + "load_server_configs", + "global_config_path", + "project_config_path", + "GLOBAL_CONFIG_RELPATH", + "PROJECT_CONFIG_RELPATH", +] diff --git a/src/agentux/memory.py b/src/agentux/memory.py new file mode 100644 index 0000000..1810300 --- /dev/null +++ b/src/agentux/memory.py @@ -0,0 +1,350 @@ +"""Persistent knowledge store for Agentux Solo. + +A small model cannot hold what it learns. This module is the place it puts +things so they survive the session: a SQLite database with a full-text index, +written by the model through the ``memory_save`` tool and read back every turn +by the agent. + +The design is deliberately dependency-free. SQLite is in the standard library +and FTS5 is compiled into it, so the store costs nothing to run and nothing to +install. Scope is a property of each memory, not of the store: a memory tagged +``project`` is only reachable from that working directory, and one tagged +``global`` is reachable from anywhere. Retrieval ranks project memories above +global ones, so a local gotcha wins over a general lesson. + +The full-text index does the heavy lifting on recall; there is no embedding +model and no vector database. The schema keeps an ``id`` column so a later +vector column can be added without a migration of the existing rows. +""" + +from __future__ import annotations + +import os +import re +import sqlite3 +import time +import uuid +from dataclasses import dataclass +from typing import List, Optional, Sequence, Tuple + +#: Scope values a memory can carry. +SCOPE_PROJECT = "project" +SCOPE_GLOBAL = "global" +VALID_SCOPES = (SCOPE_PROJECT, SCOPE_GLOBAL) + +#: Bodies are stored whole but never injected whole. +MAX_BODY_CHARS = 4_000 +MAX_INJECT_CHARS = 400 + +#: Retrieval defaults. +FTS_MAX_TERMS = 6 +DEFAULT_LIMIT = 5 + +#: Words that carry no signal for recall. Kept small on purpose: a longer list +#: risks dropping a term that was the whole point of the sentence. +_STOPWORDS = frozenset( + """ + the a an and or but if then else for to of in on at by with from as is are + was were be been being it its this that these those i you he she we they me + my your his her our their do does did can could will would should may might + must not no so than too very just about into over after before what which + who how when where why have has had having up out off + """.split() +) + +_TOKEN = re.compile(r"[a-z0-9_]+") + +_SCHEMA = """ +CREATE VIRTUAL TABLE IF NOT EXISTS memories USING fts5( + body, + scope UNINDEXED, + project UNINDEXED, + source UNINDEXED, + tags UNINDEXED, + id UNINDEXED, + created_at UNINDEXED, + updated_at UNINDEXED, + accesses UNINDEXED, + last_accessed UNINDEXED, + tokenize = 'porter unicode61' +) +""" + +# rank is FTS5's BM25 score; more negative is a better match. +_SELECT = """ +SELECT id, body, scope, project, source, tags, created_at, updated_at, + accesses, last_accessed, rank +FROM memories +WHERE memories MATCH ? + AND (scope = 'global' OR project = ? OR project IS NULL) +ORDER BY rank +LIMIT ? +""" + +_INSERT = """ +INSERT INTO memories + (body, scope, project, source, tags, id, created_at, updated_at, + accesses, last_accessed) +VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, NULL) +""" + +_UPDATE = """ +UPDATE memories +SET body = ?, scope = ?, project = ?, source = ?, tags = ?, updated_at = ? +WHERE id = ? +""" + +_FIND_BY_BODY = "SELECT id FROM memories WHERE body = ? LIMIT 1" + + +@dataclass +class Memory: + """One thing the model learned.""" + + id: str + body: str + scope: str + project: Optional[str] + source: str + tags: str + created_at: float + updated_at: float + accesses: int + last_accessed: Optional[float] + + +def default_memory_path() -> str: + """Where the store lives when no path is given.""" + return os.path.join(os.path.expanduser("~"), ".agentux", "memory.db") + + +def _normalize(body: str) -> str: + return re.sub(r"\s+", " ", str(body).strip()) + + +def build_query(text: str, max_terms: int = FTS_MAX_TERMS) -> str: + """Turn a user message into an FTS5 ``MATCH`` expression. + + Returns ``""`` when nothing usable remains. Every term is double-quoted, so + characters that FTS5 would otherwise treat as syntax are matched as + literal text; a user message containing quotes, parentheses or asterisks + cannot break the query. + """ + terms: List[str] = [] + for raw in _TOKEN.findall(str(text).lower()): + if len(raw) < 3 or raw in _STOPWORDS: + continue + if raw not in terms: + terms.append(raw) + if len(terms) >= max_terms: + break + return " OR ".join(f'"{term}"' for term in terms) + + +def render_memory_block( + memories: Sequence[Tuple[Memory, float]], + max_chars: int = MAX_INJECT_CHARS, +) -> str: + """Render recalled memories as the block injected into the system prompt. + + Empty when there is nothing to say, so the caller can append the result + unconditionally. + """ + if not memories: + return "" + lines = ["## Things you already know", ""] + for memory, _score in memories: + body = memory.body + if len(body) > max_chars: + body = body[:max_chars].rstrip() + "..." + if memory.scope == SCOPE_GLOBAL: + where = "global" + else: + where = memory.project or "this project" + lines.append(f"- {body} [{memory.id} · {where}]") + return "\n".join(lines) + + +def _row_to_memory(row: sqlite3.Row) -> Memory: + return Memory( + id=row["id"], + body=row["body"], + scope=row["scope"], + project=row["project"], + source=row["source"], + tags=row["tags"], + created_at=row["created_at"], + updated_at=row["updated_at"], + accesses=row["accesses"], + last_accessed=row["last_accessed"], + ) + + +class MemoryStore: + """A SQLite-backed memory store with a full-text index.""" + + def __init__(self, path: Optional[str] = None) -> None: + self.path = os.path.abspath( + os.path.expanduser(path) if path else default_memory_path() + ) + parent = os.path.dirname(self.path) + if parent: + os.makedirs(parent, exist_ok=True) + self._conn = sqlite3.connect(self.path, timeout=30.0) + self._conn.row_factory = sqlite3.Row + self._conn.execute("PRAGMA journal_mode=WAL") + self._conn.executescript(_SCHEMA) + self._conn.commit() + + # ------------------------------------------------------------------ + # Writing + # ------------------------------------------------------------------ + def save( + self, + body: str, + *, + scope: str = SCOPE_PROJECT, + project: Optional[str] = None, + source: str = "model", + tags: str = "", + memory_id: Optional[str] = None, + ) -> Memory: + """Store a memory, or update it if the same body is already there. + + Updating rather than duplicating is what keeps the store usable: a + model that re-learns a fact it already recorded would otherwise bury + the original under copies and flood the context with repeats. + """ + normalized = _normalize(body) + if not normalized: + raise ValueError("A memory needs a non-empty body.") + if scope not in VALID_SCOPES: + raise ValueError( + f"Scope must be one of {', '.join(VALID_SCOPES)}, got {scope!r}." + ) + if len(normalized) > MAX_BODY_CHARS: + normalized = normalized[:MAX_BODY_CHARS].rstrip() + + existing = self.get(memory_id) if memory_id else None + if existing is None: + row = self._conn.execute(_FIND_BY_BODY, (normalized,)).fetchone() + existing = self.get(row["id"]) if row is not None else None + + now = time.time() + if existing is not None: + self._conn.execute( + _UPDATE, + (normalized, scope, project, source, tags, now, existing.id), + ) + self._conn.commit() + return self.get(existing.id) # type: ignore[return-value] + + new_id = memory_id or uuid.uuid4().hex[:12] + self._conn.execute( + _INSERT, + (normalized, scope, project, source, tags, new_id, now, now), + ) + self._conn.commit() + return self.get(new_id) # type: ignore[return-value] + + # ------------------------------------------------------------------ + # Reading + # ------------------------------------------------------------------ + def search( + self, + query: str, + *, + project: Optional[str] = None, + limit: int = DEFAULT_LIMIT, + ) -> List[Tuple[Memory, float]]: + """Return the memories that best match ``query``, best first. + + ``query`` must already be an FTS5 ``MATCH`` expression; use + :func:`build_query` to make one from plain text. An empty query + returns nothing rather than raising, so a turn with no usable terms + costs no recall and no error. + """ + if not query or limit <= 0: + return [] + + rows = self._conn.execute( + _SELECT, (query, project, max(1, limit) * 3) + ).fetchall() + + now = time.time() + scored: List[Tuple[Memory, float]] = [] + for row in rows: + memory = _row_to_memory(row) + # BM25: FTS5's rank is negative, so negate it to get "higher is + # better" and add the tie-breakers on top. + score = -float(row["rank"]) + if memory.scope == SCOPE_PROJECT and memory.project == project: + score += 2.0 + if memory.last_accessed: + age_days = max(0.0, (now - memory.last_accessed) / 86_400.0) + score += max(0.0, 1.0 - age_days / 30.0) + score += min(memory.accesses, 20) * 0.05 + scored.append((memory, score)) + + scored.sort(key=lambda pair: pair[1], reverse=True) + return scored[:limit] + + def get(self, memory_id: str) -> Optional[Memory]: + row = self._conn.execute( + "SELECT id, body, scope, project, source, tags, created_at, " + "updated_at, accesses, last_accessed FROM memories WHERE id = ?", + (memory_id,), + ).fetchone() + return _row_to_memory(row) if row is not None else None + + def delete(self, memory_id: str) -> bool: + cursor = self._conn.execute("DELETE FROM memories WHERE id = ?", (memory_id,)) + self._conn.commit() + return cursor.rowcount > 0 + + def count(self, *, project: Optional[str] = None) -> int: + if project is None: + row = self._conn.execute("SELECT COUNT(*) AS n FROM memories").fetchone() + else: + row = self._conn.execute( + "SELECT COUNT(*) AS n FROM memories " + "WHERE scope = 'global' OR project = ?", + (project,), + ).fetchone() + return int(row["n"]) + + def touch(self, memory_ids: Sequence[str]) -> None: + """Record that these memories were used, so ranking learns from it.""" + now = time.time() + for memory_id in memory_ids: + self._conn.execute( + "UPDATE memories SET accesses = accesses + 1, " + "last_accessed = ? WHERE id = ?", + (now, memory_id), + ) + self._conn.commit() + + # ------------------------------------------------------------------ + # Lifecycle + # ------------------------------------------------------------------ + def close(self) -> None: + if self._conn is not None: + self._conn.close() + + def __enter__(self) -> "MemoryStore": + return self + + def __exit__(self, *exc: object) -> None: + self.close() + + +__all__ = [ + "Memory", + "MemoryStore", + "SCOPE_PROJECT", + "SCOPE_GLOBAL", + "VALID_SCOPES", + "build_query", + "render_memory_block", + "default_memory_path", +] diff --git a/src/agentux/modelpicker.py b/src/agentux/modelpicker.py new file mode 100644 index 0000000..1685601 --- /dev/null +++ b/src/agentux/modelpicker.py @@ -0,0 +1,353 @@ +"""Discovering and switching models. + +The provider's ``/models`` endpoint is the only source of truth about what is +available, so Agentux asks rather than guessing. A provider that does not +implement it is common -- gateways usually do not -- and that is not an error: +it just means switching is by name. + +Three ways to pick, in descending order of certainty: + +1. ``/model`` opens a picker when the terminal can support one, and falls back + to a numbered table otherwise. +2. ``/model <name>`` takes the name directly, with unique-prefix matching so + ``/model qwen`` works when there is exactly one qwen. +3. ``/model <number>`` takes an index into the same sorted list the table shows. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple + +from rich.console import Console +from rich.table import Table + +from .errors import AgentuxError + +if TYPE_CHECKING: # pragma: no cover + from .agent import Agent + from .config import Config + +#: Capability flags some providers report, and what we do with them. +_TOOL_CAPABILITY = "tools" + + +async def discover_models(config: "Config") -> Tuple[List[dict], Optional[BaseException]]: + """Ask the provider what models it has. + + Returns ``(models, None)`` or ``([], error)``. A provider with no model + listing returns an empty list with no error -- that is normal, not a + failure, and the caller falls back to free-text entry. + """ + from .providers.openai_compatible import OpenAICompatibleProvider + + provider = OpenAICompatibleProvider(config) + lister = getattr(provider, "list_models_detailed", None) + try: + if callable(lister): + models = await lister() + else: + models = [{"name": name} for name in await provider.list_models()] + except AgentuxError as exc: + return [], exc + except Exception as exc: # pragma: no cover - defensive + return [], exc + return list(models), None + + +def model_name(model: dict) -> str: + return model.get("name") or "?" + + +def has_tools(model: dict) -> Optional[bool]: + """Whether a model can call tools, or ``None`` if it did not say.""" + capabilities = model.get("capabilities") + if capabilities is None: + return None + return _TOOL_CAPABILITY in capabilities + + +def sort_models(models: List[dict]) -> List[dict]: + """The one order every listing uses, so a number means the same thing twice.""" + return sorted(models, key=model_name) + + +def match_model(models: List[dict], query: str) -> Optional[str]: + """Resolve a partial, exact, or numeric reference to a real model name. + + Ambiguity resolves to ``None`` rather than to a guess: picking the wrong + model silently is worse than asking. + """ + query = query.strip() + if not query: + return None + + # The same order the listing printed. A number that indexed an unsorted + # list would pick a different model than the row the user was looking at. + names = [model_name(model) for model in sort_models(models)] + + # A number picks from the sorted order the listing printed. + if query.isdigit(): + index = int(query) - 1 + return names[index] if 0 <= index < len(names) else None + + if query in names: + return query + + lowered = query.lower() + exact = [name for name in names if name.lower() == lowered] + if exact: + return exact[0] + + partial = [name for name in names if lowered in name.lower()] + return partial[0] if len(partial) == 1 else None + + +def render_model_table( + console: Console, models: List[dict], current: Optional[str] = None +) -> None: + """Print discovered models, marking tool support and the current one.""" + if not models: + console.print("[yellow]The provider returned no models.[/yellow]") + return + + models = sort_models(models) + # Capabilities are only shown when at least one model reports them; a + # column of "unknown" is worse than no column. + detail = any(model.get("capabilities") is not None for model in models) + + table = Table(box=None, pad_edge=False, show_header=True, header_style="dim") + table.add_column("", width=1, no_wrap=True) + table.add_column("#", style="dim", justify="right", no_wrap=True) + table.add_column("model", style="bold", no_wrap=True) + if detail: + table.add_column("tools", no_wrap=True) + table.add_column("", no_wrap=True) + + for index, model in enumerate(models, start=1): + name = model_name(model) + marker = "[bold green]●[/bold green]" if name == current else " " + if detail: + supported = has_tools(model) + if supported is True: + tools = "[green]yes[/green]" + elif supported is False: + tools = "[red]no[/red]" + else: + tools = "[dim]?[/dim]" + notes = [note for note in ("thinking", "vision") if note in (model.get("capabilities") or [])] + table.add_row(marker, str(index), name, tools, "[dim]" + " ".join(notes) + "[/dim]") + else: + table.add_row(marker, str(index), name) + + console.print() + console.print(table) + + if current: + console.print(f"\n[dim]{len(models)} model(s). Current: {current}[/dim]") + else: + console.print(f"\n[dim]{len(models)} model(s) available.[/dim]") + + if not detail: + console.print( + "[dim]This provider does not report capabilities, so tool support " + "is unknown.[/dim]" + ) + return + + usable = [model for model in models if has_tools(model) is True] + if usable: + console.print( + "[dim]Models marked 'no' cannot run Agentux's tools; use --no-tools " + "with those.[/dim]" + ) + else: + console.print( + "[yellow]None of these models report tool support. Agentux needs a " + "tool-capable model.[/yellow]" + ) + + +#: The picker value that means "switch to Agentux Solo". +SOLO_CHOICE = "solo" + + +def switch_to_solo(agent: "Agent", console: Console) -> None: + """Point the session at Agentux Solo. + + Rebuilds nothing: the Solo preset changes the model and base URL on the + config, and the provider reads both from there on every request. + """ + from .solo import SOLO_MODEL, apply_solo, solo_preset + + apply_solo(agent, solo_preset(agent.config.working_dir)) + console.print( + f"[green]Switched to[/green] [bold]Agentux Solo[/bold] " + f"([dim]{SOLO_MODEL} + memory[/dim])" + ) + + +def _picker_choices(models: List[dict], current: Optional[str]) -> List[Dict[str, Any]]: + from .solo import SOLO_MODEL + + choices = [ + { + "name": "Agentux Solo (qwen2.5:0.5b + memory)", + "value": SOLO_CHOICE, + "enabled": current != SOLO_MODEL, + } + ] + for model in sort_models(models): + name = model_name(model) + supported = has_tools(model) + if supported is True: + suffix = " (tools)" + elif supported is False: + suffix = " (no tools)" + else: + suffix = "" + choices.append( + { + "name": f"{name}{suffix}", + "value": name, + "enabled": name != current, # already selected: not a valid choice + } + ) + return choices + + +#: Picker outcomes. Kept distinct because "cancelled" and "unavailable" call +#: for different behaviour: a cancel should leave the user alone, while an +#: unavailable picker should fall back to the numbered table. +PICKED = "picked" +CANCELLED = "cancelled" +UNAVAILABLE = "unavailable" + + +def pick_model( + console: Console, models: List[dict], current: Optional[str] +) -> Tuple[str, Optional[str]]: + """An interactive picker. Returns ``(status, model_name)``. + + Any failure -- no InquirerPy, not a terminal, the user pressing ctrl-c -- + is reported as a status rather than raised. A picker is a convenience and + must never become the only way to do something. + """ + try: + from InquirerPy import inquirer + except Exception: + return UNAVAILABLE, None + + choices = [choice for choice in _picker_choices(models, current) if choice["enabled"]] + if not choices: + return CANCELLED, None # Only the current model exists; nothing to pick. + + try: + answer = inquirer.select( + message="Switch to which model?", + choices=choices, + default=next( + (c["value"] for c in choices if c["value"] == current), choices[0]["value"] + ), + vim_mode=True, + ) + except (KeyboardInterrupt, EOFError): + return CANCELLED, None + except Exception: + return UNAVAILABLE, None + + return (PICKED, str(answer)) if answer else (CANCELLED, None) + + +def switch_model(agent: "Agent", target: str, console: Console) -> None: + """Point the session at a different model. + + The provider is rebuilt rather than reconfigured: the HTTP client holds + the model name, so mutating the config alone would leave the old model in + place and quietly ignore the change. + """ + from .providers.openai_compatible import OpenAICompatibleProvider + + current = agent.provider.get_model_name() + if target == current: + console.print(f"[dim]Already on {target}.[/dim]") + return + + agent.config.model = target + agent.provider = OpenAICompatibleProvider(agent.config) + console.print(f"[green]Switched to[/green] [bold]{target}[/bold]") + + +async def handle_model(agent: "Agent", console: Console, argument: str = "") -> bool: + """``/model`` with no argument lists; with one, switches. + + Returns ``True`` -- the command never ends the session, including when the + provider cannot be reached. + """ + query = argument.strip() + if query.lower() == SOLO_CHOICE: + switch_to_solo(agent, console) + return True + + models, error = await discover_models(agent.config) + + if error is not None: + console.print(f"[yellow]Could not list models: {error}[/yellow]") + console.print( + f"[dim]Staying on {agent.provider.get_model_name()}. " + f"Switch with '/model <name>' or --model.[/dim]" + ) + if query: + # An explicit request still works when discovery failed. + switch_model(agent, query, console) + return True + + if not models: + if query: + switch_model(agent, query, console) + else: + console.print("[yellow]The provider returned no models.[/yellow]") + console.print("[dim]Name one directly with '/model <name>'.[/dim]") + return True + + current = agent.provider.get_model_name() + + if not query: + if console.is_terminal: + status, chosen = pick_model(console, models, current) + if status == PICKED and chosen: + if chosen == SOLO_CHOICE: + switch_to_solo(agent, console) + else: + switch_model(agent, chosen, console) + return True + # A cancel means the user said no. Dumping the table on them + # anyway is the kind of small rudeness that makes a tool feel + # unresponsive. + if status == CANCELLED: + return True + render_model_table(console, models, current=current) + console.print( + f"[dim]Switch with '/model <name>' or '/model <number>'. " + f"Current: {current}[/dim]" + ) + return True + + target = match_model(models, query) + if target is None: + console.print( + f"[yellow]No model matching {query!r}. Run '/model' to see the list.[/yellow]" + ) + return True + + switch_model(agent, target, console) + return True + + +__all__ = [ + "discover_models", + "match_model", + "render_model_table", + "handle_model", + "sort_models", + "has_tools", +] diff --git a/src/agentux/repomap.py b/src/agentux/repomap.py new file mode 100644 index 0000000..3ae7722 --- /dev/null +++ b/src/agentux/repomap.py @@ -0,0 +1,194 @@ +"""Token-efficient AST and symbol-based Repository Map generator for Agentux. + +Inspired by repomap algorithms in advanced AI pair programming tools. It scans +source files (Python via native AST, plus multi-language extractors for Go, TS/JS, +Rust), extracts definitions (classes, structs, functions, methods, interfaces), +and produces a compact outline that fits into 200-600 tokens. +""" + +from __future__ import annotations + +import ast +import os +import re +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Set, Tuple + + +@dataclass +class SymbolDef: + name: str + kind: str # "class", "function", "method", "struct", "interface" + line: int + signature: str = "" + + +@dataclass +class FileSymbols: + rel_path: str + symbols: List[SymbolDef] = field(default_factory=list) + + +# Standard ignore patterns +IGNORE_DIRS = { + ".git", ".venv", "venv", "env", "__pycache__", "node_modules", + ".idea", ".vscode", "dist", "build", ".pytest_cache", ".mypy_cache", + ".tox", "target", "vendor", "bin", "obj", ".agentux" +} + +IGNORE_EXTS = { + ".pyc", ".pyo", ".pyd", ".so", ".dll", ".dylib", ".exe", ".bin", + ".png", ".jpg", ".jpeg", ".gif", ".ico", ".svg", ".lock", ".sum", + ".log", ".tmp", ".gz", ".tar", ".zip", ".wasm", ".map" +} + +CODE_EXTS = { + ".py", ".go", ".ts", ".tsx", ".js", ".jsx", ".rs", ".c", ".cpp", + ".h", ".hpp", ".java", ".rb", ".php", ".sh" +} + + +class RepoMap: + """Extracts and formats a dense, token-aware map of the codebase.""" + + def __init__(self, root: str) -> None: + self.root = os.path.abspath(root) + + def scan_files(self, limit: int = 200) -> List[str]: + """Collect source files within the workspace respecting ignores.""" + found: List[str] = [] + for dirpath, dirnames, filenames in os.walk(self.root): + dirnames[:] = [d for d in dirnames if d not in IGNORE_DIRS and not d.startswith(".")] + for f in sorted(filenames): + if f.startswith("."): + continue + ext = os.path.splitext(f)[1].lower() + if ext in CODE_EXTS and ext not in IGNORE_EXTS: + rel = os.path.relpath(os.path.join(dirpath, f), self.root) + found.append(rel) + if len(found) >= limit: + return found + return found + + def extract_symbols(self, rel_path: str) -> FileSymbols: + """Parse definitions from a single file.""" + abs_path = os.path.join(self.root, rel_path) + symbols: List[SymbolDef] = [] + ext = os.path.splitext(rel_path)[1].lower() + + if not os.path.isfile(abs_path): + return FileSymbols(rel_path=rel_path, symbols=[]) + + try: + with open(abs_path, "r", encoding="utf-8", errors="replace") as f: + content = f.read() + except Exception: + return FileSymbols(rel_path=rel_path, symbols=[]) + + if ext == ".py": + symbols = self._extract_python(content) + else: + symbols = self._extract_generic(content, ext) + + return FileSymbols(rel_path=rel_path, symbols=symbols) + + def _extract_python(self, content: str) -> List[SymbolDef]: + """Extract classes and top-level / method functions using AST.""" + symbols: List[SymbolDef] = [] + try: + tree = ast.parse(content) + except Exception: + return self._extract_generic(content, ".py") + + for node in tree.body: + if isinstance(node, ast.ClassDef): + symbols.append(SymbolDef(name=node.name, kind="class", line=node.lineno)) + for child in node.body: + if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)): + args_list = [a.arg for a in child.args.args if a.arg != "self"] + sig = f"({', '.join(args_list)})" + symbols.append( + SymbolDef( + name=f"{node.name}.{child.name}", + kind="method", + line=child.lineno, + signature=sig, + ) + ) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + args_list = [a.arg for a in node.args.args] + sig = f"({', '.join(args_list)})" + symbols.append( + SymbolDef( + name=node.name, + kind="function", + line=node.lineno, + signature=sig, + ) + ) + return symbols + + def _extract_generic(self, content: str, ext: str) -> List[SymbolDef]: + """Regex-based symbol extractor for Go, TS/JS, Rust, etc.""" + symbols: List[SymbolDef] = [] + lines = content.split("\n") + + # Patterns for functions, classes, structs + patterns = [ + # Go: type Foo struct / func (r *R) Method / func Func + (re.compile(r"^type\s+([A-Za-z0-9_]+)\s+(?:struct|interface)"), "type"), + (re.compile(r"^func\s+(?:\([^)]+\)\s+)?([A-Za-z0-9_]+)\s*\("), "func"), + # JS/TS: class Foo / function bar / export function bar / const bar = () => + (re.compile(r"^(?:export\s+)?class\s+([A-Za-z0-9_]+)"), "class"), + (re.compile(r"^(?:export\s+)?(?:async\s+)?function\s+([A-Za-z0-9_]+)"), "function"), + (re.compile(r"^(?:export\s+)?interface\s+([A-Za-z0-9_]+)"), "interface"), + # Rust: struct Foo / fn bar / impl Foo + (re.compile(r"^(?:pub\s+)?(?:struct|enum)\s+([A-Za-z0-9_]+)"), "struct"), + (re.compile(r"^(?:pub\s+)?(?:async\s+)?fn\s+([A-Za-z0-9_]+)"), "fn"), + ] + + for idx, line in enumerate(lines, start=1): + stripped = line.strip() + for pat, kind in patterns: + m = pat.search(stripped) + if m: + symbols.append(SymbolDef(name=m.group(1), kind=kind, line=idx)) + break + return symbols + + def generate_map(self, max_tokens: int = 600, query: Optional[str] = None) -> str: + """Render a compact repository outline within token budget.""" + files = self.scan_files() + if not files: + return "(empty or non-code repository)" + + query_lower = query.lower() if query else None + lines: List[str] = [] + token_estimate = 0 + + for rel in files: + fs = self.extract_symbols(rel) + if not fs.symbols and not query_lower: + continue + + filtered = fs.symbols + if query_lower: + filtered = [s for s in fs.symbols if query_lower in s.name.lower() or query_lower in rel.lower()] + if not filtered and query_lower not in rel.lower(): + continue + + file_header = f"{rel}:" + lines.append(file_header) + token_estimate += len(file_header) // 4 + 1 + + for s in filtered: + sig = f" {s.signature}" if s.signature else "" + sym_line = f" {s.kind} {s.name}{sig} (L{s.line})" + lines.append(sym_line) + token_estimate += len(sym_line) // 4 + 1 + + if token_estimate >= max_tokens: + lines.append(" ... (truncated to fit token budget)") + return "\n".join(lines) + + return "\n".join(lines) if lines else "(no symbols matched query)" diff --git a/src/agentux/session_store.py b/src/agentux/session_store.py new file mode 100644 index 0000000..0269dba --- /dev/null +++ b/src/agentux/session_store.py @@ -0,0 +1,130 @@ +"""Session persistence and resumption engine for Agentux. + +Allows saving and restoring complete conversational and working sessions +across terminal closures, including full message histories, tool state, +working directories, and metadata. +""" + +from __future__ import annotations + +import json +import os +import time +from typing import Any, Dict, List, Optional +from .models import Message + + +def _default_session_dir(working_dir: Optional[str] = None) -> str: + """Session directory preference: project .agentux/sessions if exists, else user config.""" + if working_dir: + project_dir = os.path.join(working_dir, ".agentux", "sessions") + if os.path.isdir(os.path.join(working_dir, ".agentux")): + os.makedirs(project_dir, exist_ok=True) + return project_dir + global_dir = os.path.expanduser("~/.config/agentux/sessions") + os.makedirs(global_dir, exist_ok=True) + return global_dir + + +class SessionStore: + """Saves, lists, and restores Agentux sessions.""" + + def __init__(self, directory: Optional[str] = None) -> None: + self.directory = directory or _default_session_dir() + os.makedirs(self.directory, exist_ok=True) + + def _file_path(self, session_id: str) -> str: + safe_id = "".join(c for c in session_id if c.isalnum() or c in ("-", "_")) + return os.path.join(self.directory, f"{safe_id}.json") + + def save( + self, + session_id: str, + history: List[Message], + model: str, + working_dir: str, + title: Optional[str] = None, + extra: Optional[Dict[str, Any]] = None, + ) -> str: + """Persist a conversation session to disk.""" + path = self._file_path(session_id) + first_user_prompt = "" + for m in history: + if m.role == "user" and m.content: + first_user_prompt = m.content[:80].strip() + break + + data: Dict[str, Any] = { + "id": session_id, + "title": title or first_user_prompt or f"Session {session_id}", + "created_at": time.time(), + "updated_at": time.time(), + "model": model, + "working_dir": working_dir, + "turn_count": len([m for m in history if m.role == "user"]), + "messages": [m.to_dict() for m in history], + "extra": extra or {}, + } + + with open(path, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2) + return path + + def load(self, session_id: str) -> Optional[Dict[str, Any]]: + """Load session data by ID or filename.""" + path = self._file_path(session_id) + if not os.path.isfile(path): + # Check if session_id is a partial match + for f in os.listdir(self.directory): + if f.endswith(".json") and session_id in f: + path = os.path.join(self.directory, f) + break + if not os.path.isfile(path): + return None + + try: + with open(path, "r", encoding="utf-8") as f: + data = json.load(f) + # Reconstruct Message instances + messages = [Message.from_dict(m) for m in data.get("messages", [])] + data["messages"] = messages + return data + except Exception: + return None + + def list_sessions(self) -> List[Dict[str, Any]]: + """List all saved sessions sorted by most recently modified.""" + sessions: List[Dict[str, Any]] = [] + if not os.path.isdir(self.directory): + return sessions + + for filename in sorted(os.listdir(self.directory), reverse=True): + if not filename.endswith(".json"): + continue + path = os.path.join(self.directory, filename) + try: + with open(path, "r", encoding="utf-8") as f: + meta = json.load(f) + sessions.append({ + "id": meta.get("id", filename[:-5]), + "title": meta.get("title", "Untitled"), + "model": meta.get("model", ""), + "updated_at": meta.get("updated_at", os.path.getmtime(path)), + "turn_count": meta.get("turn_count", 0), + "working_dir": meta.get("working_dir", ""), + }) + except Exception: + continue + + sessions.sort(key=lambda s: s["updated_at"], reverse=True) + return sessions + + def delete(self, session_id: str) -> bool: + path = self._file_path(session_id) + if os.path.isfile(path): + try: + os.remove(path) + return True + except OSError: + return False + return False diff --git a/src/agentux/settings.py b/src/agentux/settings.py new file mode 100644 index 0000000..5bbcc1c --- /dev/null +++ b/src/agentux/settings.py @@ -0,0 +1,272 @@ +"""Session settings, changed from inside the running agent. + +The environment variable is the right place for a *secret* and the wrong place +for a preference. ``AGENTUX_MODEL=qwen3:14b`` typed once per terminal is +noise; retyping it every session is worse. This module lets ``/set`` change +either kind for the live session, and ``/set save`` persist everything that is +not a secret. + +Two rules hold throughout: + +* **The API key is never displayed.** It is shown as ``set`` or ``not set``, + never partially, never masked-into-shape, because a masked key still leaks + its length and its last characters. +* **A secret is never written to disk.** :func:`agentux.config.save_settings` + refuses it outright; ``/set save`` simply never offers it. +""" + +from __future__ import annotations + +import os +from typing import Any, Callable, Dict, List, Optional, Tuple + +from rich.text import Text + +from .config import Config +from .errors import ConfigurationError + +#: ``/set <name>`` -> the :class:`Config` attribute it writes. Aliases are +#: resolved in :func:`resolve_key`, so this table only holds canonical names. +SETTABLE: Dict[str, str] = { + "model": "model", + "base-url": "base_url", + "api-key": "api_key", + "max-steps": "max_steps", + "timeout": "timeout", + "temperature": "temperature", + "max-tokens": "max_tokens", + "cwd": "working_dir", +} + +#: Every spelling a user might reasonably type. +ALIASES: Dict[str, str] = { + "name": "model", + "url": "base-url", + "baseurl": "base-url", + "endpoint": "base-url", + "key": "api-key", + "apikey": "api-key", + "token": "api-key", + "steps": "max-steps", + "maxsteps": "max-steps", + "dir": "cwd", + "directory": "cwd", + "workspace": "cwd", + "temp": "temperature", + "tok": "max-tokens", + "maxtokens": "max-tokens", + "verbose": "verbose", + "stream": "stream", +} + +#: Session toggles. These are not on :class:`Config`; they are behaviour the +#: CLI owns, so they live in a plain dict the CLI reads after each command. +TOGGLES: Dict[str, str] = { + "verbose": "Show full tool arguments and results", + "stream": "Print the answer as it is generated", +} + +#: Changing any of these invalidates the HTTP client, so the provider has to be +#: rebuilt or the change silently does nothing. +REBUILDS_PROVIDER = {"model", "base_url", "api_key"} + +#: Changing this invalidates every tool's root and cwd. +REBUILDS_TOOLS = {"working_dir"} + +#: Changing these changes what the next request looks like, so the conversation +#: is no longer the same conversation. +INVALIDATES_HISTORY = {"model", "base_url", "api_key", "temperature"} + + +def resolve_key(name: str) -> Optional[str]: + """Map a user-typed name to a canonical setting, or ``None``.""" + key = name.strip().lower().replace("_", "-") + if key in SETTABLE or key in TOGGLES: + return key + key = ALIASES.get(key, key) + if key in SETTABLE or key in TOGGLES: + return key + # A unique prefix is enough to be unambiguous: "max" -> nothing (two + # matches), "base" -> "base-url". + matches = [k for k in list(SETTABLE) + list(TOGGLES) if k.startswith(key)] + return matches[0] if len(matches) == 1 else None + + +def describe_settings(config: Config) -> Text: + """Render the current settings for display.""" + text = Text() + text.append("current settings\n") + + rows: List[Tuple[str, str, bool]] = [ + ("model", config.model, False), + ("base-url", config.base_url, False), + # Presence only. Even the last four characters are a leak. + ("api-key", "set" if config.api_key else "not set", True), + ("max-steps", str(config.max_steps), False), + ("timeout", f"{config.timeout:g}s", False), + ("temperature", f"{config.temperature:g}", False), + ("max-tokens", str(config.max_tokens), False), + ("cwd", config.working_dir, False), + ] + + for label, value, muted in rows: + text.append(f" {label:<12}", style="dim") + text.append(value, style="dim" if muted else "cyan") + text.append("\n") + + return text + + +def parse_value(key: str, value: str, config: Config) -> Any: + """Convert and range-check one value, or raise with a usable message.""" + if key == "model": + if not value.strip(): + raise ConfigurationError("The model name cannot be empty.") + return value.strip() + + if key == "base-url": + candidate = value.strip().rstrip("/") + if not candidate.startswith(("http://", "https://")): + raise ConfigurationError( + f"The base URL must start with http:// or https://. Got {value!r}." + ) + return candidate + + if key == "api-key": + # An explicitly empty value is a way to clear the key, which matters + # when switching from a remote provider to a local one. + return value.strip() or None + + if key == "cwd": + path = os.path.abspath(os.path.expanduser(value.strip())) + if not os.path.isdir(path): + raise ConfigurationError(f"{path} is not a directory.") + return path + + if key in ("max-steps", "max-tokens"): + try: + number = int(value) + except ValueError: + raise ConfigurationError(f"{key.replace('-', ' ')} must be a whole number, got {value!r}.") + if number < 1: + raise ConfigurationError(f"{key.replace('-', ' ')} must be at least 1.") + return number + + if key == "timeout": + try: + number = float(value) + except ValueError: + raise ConfigurationError(f"Timeout must be a number of seconds, got {value!r}.") + if number <= 0: + raise ConfigurationError("Timeout must be greater than 0.") + return number + + if key == "temperature": + try: + number = float(value) + except ValueError: + raise ConfigurationError(f"Temperature must be a number, got {value!r}.") + if not 0.0 <= number <= 2.0: + raise ConfigurationError( + f"Temperature must be between 0 and 2. Got {number}. " + "0 is deterministic, which is what you usually want for code." + ) + return number + + raise ConfigurationError(f"{key!r} is not a setting that takes a value.") + + +def to_bool(value: str) -> bool: + lowered = value.strip().lower() + if lowered in ("on", "true", "yes", "1", "y"): + return True + if lowered in ("off", "false", "no", "0", "n"): + return False + raise ConfigurationError(f"Expected on or off, got {value!r}.") + + +async def apply_setting( + agent: Any, + key: str, + value: str, + session: Optional[Dict[str, Any]] = None, + rebuild_tools: Optional[Callable[[], Any]] = None, +) -> str: + """Apply one setting to the live session and return a human message. + + ``session`` is the CLI's bag of non-Config behaviour toggles. ``rebuild_tools`` + is a callback the CLI supplies so a working-directory change can re-root + the tools; keeping it a callback avoids importing the CLI from here, which + would be a cycle. + """ + config: Config = agent.config + session = session if session is not None else {} + + if key in TOGGLES: + enabled = to_bool(value) + session[key] = enabled + return f"{TOGGLES[key]}: {'on' if enabled else 'off'} (this session only)." + + attribute = SETTABLE.get(key) + if attribute is None: + raise ConfigurationError(f"{key!r} is not a setting.") + + parsed = parse_value(key, value, config) + + if attribute in REBUILDS_TOOLS and parsed == config.working_dir: + return f"Working directory is already {parsed}." + + previous = getattr(config, attribute) + setattr(config, attribute, parsed) + try: + config.validate() + except ConfigurationError: + setattr(config, attribute, previous) # Never leave a broken config live. + raise + + messages = [] + + if attribute in REBUILDS_PROVIDER: + from .providers.openai_compatible import OpenAICompatibleProvider + + agent.provider = OpenAICompatibleProvider(config) + messages.append(f"Now using {config.base_url} with {config.model}.") + + if attribute in REBUILDS_TOOLS and rebuild_tools is not None: + agent.registry = rebuild_tools() + messages.append(f"Tools are now rooted at {config.working_dir}.") + + if attribute in INVALIDATES_HISTORY and agent.history: + # Keeping messages that were exchanged with a different model or + # temperature is misleading: the context is not what it was. + agent.reset() + messages.append("Conversation cleared, because the model or server changed.") + + if attribute == "api_key": + messages.append( + "API key set for this session only. It is never written to disk; " + "export AGENTUX_API_KEY to make it permanent." + if parsed + else "API key cleared." + ) + else: + messages.append(f"{key} = {parsed}") + + return " ".join(messages) + + +def savable(config: Config) -> Dict[str, Any]: + """The settings that may be written to disk. Never includes the key.""" + return { + "model": config.model, + "base_url": config.base_url, + "max_steps": config.max_steps, + "timeout": config.timeout, + "temperature": config.temperature, + "max_tokens": config.max_tokens, + "working_dir": config.working_dir, + } + + +__all__ = ["SETTABLE", "TOGGLES", "ALIASES", "apply_setting", "describe_settings", + "resolve_key", "parse_value", "savable"] diff --git a/src/agentux/skills/__init__.py b/src/agentux/skills/__init__.py new file mode 100644 index 0000000..70dcf72 --- /dev/null +++ b/src/agentux/skills/__init__.py @@ -0,0 +1,2 @@ +"""Agentux skills system. +"""
\ No newline at end of file diff --git a/src/agentux/skills/base.py b/src/agentux/skills/base.py new file mode 100644 index 0000000..27b6b22 --- /dev/null +++ b/src/agentux/skills/base.py @@ -0,0 +1,79 @@ +"""Base class for Agentux skills. +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import Any, Dict, List, Optional + +from ..agent import Agent +from ..config import Config +from ..context import ContextManager + + +class BaseSkill(ABC): + """Base class for all Agentux skills.""" + + def __init__(self, agent: Agent, config: Optional[Dict[str, Any]] = None): + self.agent = agent + self.config = config or {} + self.name = self.__class__.__name__ + self.description = getattr(self.__class__, '__doc__', "").strip() or "No description" + + @abstractmethod + async def initialize(self) -> None: + """Initialize the skill. Called when the skill is loaded.""" + pass + + @abstractmethod + async def execute(self, *args, **kwargs) -> Any: + """Execute the skill's main functionality.""" + pass + + def get_info(self) -> Dict[str, Any]: + """Get information about this skill.""" + return { + "name": self.name, + "description": self.description, + "config": self.config + } + + +class SkillManager: + """Manages loading and executing skills.""" + + def __init__(self, agent: Agent): + self.agent = agent + self.skills: Dict[str, BaseSkill] = {} + self._skill_classes: Dict[str, type[BaseSkill]] = {} + + def register_skill_class(self, name: str, skill_class: type[BaseSkill]) -> None: + """Register a skill class for later instantiation.""" + self._skill_classes[name] = skill_class + + def load_skill(self, name: str, config: Optional[Dict[str, Any]] = None) -> BaseSkill: + """Load and initialize a skill by name.""" + if name in self.skills: + return self.skills[name] + + if name not in self._skill_classes: + raise ValueError(f"Skill class '{name}' not registered") + + skill_instance = self._skill_classes[name](self.agent, config or {}) + self.skills[name] = skill_instance + # Initialize the skill + import asyncio + asyncio.create_task(skill_instance.initialize()) + return skill_instance + + def get_skill(self, name: str) -> Optional[BaseSkill]: + """Get a loaded skill by name.""" + return self.skills.get(name) + + def list_skills(self) -> List[str]: + """List all loaded skill names.""" + return list(self.skills.keys()) + + def list_available_skills(self) -> List[str]: + """List all registered skill names.""" + return list(self._skill_classes.keys())
\ No newline at end of file diff --git a/src/agentux/skills/marketplace_integration.py b/src/agentux/skills/marketplace_integration.py new file mode 100644 index 0000000..c44fee5 --- /dev/null +++ b/src/agentux/skills/marketplace_integration.py @@ -0,0 +1,332 @@ +"""Marketplace integration skill for Agentux. +""" + +from __future__ import annotations + +import asyncio +from typing import Any, Dict, List, Optional + +from .base import BaseSkill +from ..marketplace import Marketplace, MarketplaceItemType + + +class MarketplaceIntegrationSkill(BaseSkill): + """Integrates with the Agentux marketplace to dynamically load skills and MCP servers. + + This skill allows Agentux to: + - Browse and search the marketplace for available skills + - Install and enable skills from the marketplace + - Load installed skills into the agent's skill system + - Manage the lifecycle of marketplace-based skills + """ + + def __init__(self, agent: Agent, config: Optional[Dict[str, Any]] = None): + super().__init__(agent, config) + self.marketplace = Marketplace() + self.loaded_marketplace_skills: Dict[str, Any] = {} # Tracks skills loaded from marketplace + + async def initialize(self) -> None: + """Initialize the marketplace integration skill.""" + # Ensure marketplace has default items + self.marketplace.populate_default_items() + + async def execute(self, operation: str, **kwargs) -> Any: + """Execute a marketplace integration operation. + + Args: + operation: The marketplace operation to perform + **kwargs: Additional arguments for the operation + + Returns: + The result of the marketplace operation + """ + operations = { + "browse_marketplace": self._browse_marketplace, + "search_marketplace": self._search_marketplace, + "install_skill": self._install_skill, + "load_installed_skills": self._load_installed_skills, + "get_marketplace_status": self._get_marketplace_status, + "use_marketplace_skill": self._use_marketplace_skill + } + + if operation not in operations: + raise ValueError(f"Unknown marketplace operation: {operation}") + + return await operations[operation](**kwargs) + + async def _browse_marketplace(self, item_type: Optional[str] = None, + limit: int = 20) -> Dict[str, Any]: + """Browse the marketplace for available items. + + Args: + item_type: Filter by item type ("skill" or "mcp_server"), or None for all + limit: Maximum number of items to return + + Returns: + Marketplace browsing results + """ + marketplace_type = None + if item_type: + try: + marketplace_type = MarketplaceItemType(item_type.lower()) + except ValueError: + pass # Ignore invalid types + + if marketplace_type: + items = self.marketplace.get_items_by_type(marketplace_type) + else: + items = self.marketplace.items + + # Apply limit + items = items[:limit] + + return { + "total_available": len(self.marketplace.items), + "filtered_count": len(items), + "items": [ + { + "id": item.id, + "name": item.name, + "description": item.description, + "type": item.type.value, + "version": item.version, + "installed": item.installed, + "enabled": item.enabled, + "tags": item.tags + } + for item in items + ] + } + + async def _search_marketplace(self, query: str, + item_type: Optional[str] = None) -> Dict[str, Any]: + """Search the marketplace for items matching a query. + + Args: + query: Search query string + item_type: Filter by item type, or None for all types + + Returns: + Marketplace search results + """ + results = self.marketplace.search_items(query) + + # Filter by type if specified + if item_type: + try: + marketplace_type = MarketplaceItemType(item_type.lower()) + results = [item for item in results if item.type == marketplace_type] + except ValueError: + pass # Ignore invalid types + + return { + "query": query, + "results_count": len(results), + "results": [ + { + "id": item.id, + "name": item.name, + "description": item.description, + "type": item.type.value, + "version": item.version, + "installed": item.installed, + "enabled": item.enabled, + "tags": item.tags + } + for item in results + ] + } + + async def _install_skill(self, skill_id: str) -> Dict[str, Any]: + """Install a skill from the marketplace. + + Args: + skill_id: ID of the skill to install + + Returns: + Installation result + """ + item = self.marketplace.get_item(skill_id) + if not item: + return {"status": "error", "message": f"Skill with ID {skill_id} not found"} + + if item.type != MarketplaceItemType.SKILL: + return {"status": "error", "message": f"Item {skill_id} is not a skill"} + + # Install in marketplace + success = self.marketplace.install_item(skill_id) + + if success: + # Try to load the skill (this would require the skill to actually exist) + try: + loaded_skill = await self._attempt_load_marketplace_skill(item) + return { + "status": "installed_and_loaded", + "skill_name": item.name, + "skill_id": skill_id, + "loaded": loaded_skill is not None + } + except Exception as e: + return { + "status": "installed_load_failed", + "skill_name": item.name, + "skill_id": skill_id, + "load_error": str(e) + } + else: + return {"status": "error", "message": f"Failed to install skill {skill_id}"} + + async def _load_installed_skills(self) -> Dict[str, Any]: + """Load all installed skills from the marketplace. + + Returns: + Result of loading installed skills + """ + installed_items = self.marketplace.get_installed_items() + skill_items = [item for item in installed_items if item.type == MarketplaceItemType.SKILL] + + loaded_skills = [] + failed_skills = [] + + for item in skill_items: + try: + loaded_skill = await self._attempt_load_marketplace_skill(item) + if loaded_skill: + loaded_skills.append({ + "skill_name": item.name, + "skill_id": item.id, + "status": "loaded" + }) + self.loaded_marketplace_skills[item.id] = loaded_skill + else: + failed_skills.append({ + "skill_name": item.name, + "skill_id": item.id, + "reason": "Skill class not found or failed to load" + }) + except Exception as e: + failed_skills.append({ + "skill_name": item.name, + "skill_id": item.id, + "reason": str(e) + }) + + return { + "total_installed_skills": len(skill_items), + "successfully_loaded": len(loaded_skills), + "failed_to_load": len(failed_skills), + "loaded_skills": loaded_skills, + "failed_skills": failed_skills + } + + async def _attempt_load_marketplace_skill(self, item: Any) -> Optional[Any]: + """Attempt to load a skill from a marketplace item. + + Args: + item: MarketplaceItem representing the skill + + Returns: + Loaded skill instance, or None if loading failed + """ + # This is a placeholder implementation + # In a real implementation, this would: + # 1. Parse the entry_point to determine how to load the skill + # 2. Dynamically import the skill module + # 3. Instantiate the skill class + # 4. Initialize and return the skill + + # For now, we'll simulate loading for known default skills + known_skills = { + "frontend-design": "FrontendDesignSkill", + "dataviz": "DataVizSkill", + "artifact-diagramming": "ArtifactDiagrammingSkill", + "update-config": "UpdateConfigSkill", + "keybindings-help": "KeybindingsHelpSkill" + } + + if item.name in known_skills: + # Simulate successful loading + return { + "name": item.name, + "type": "marketplace_skill", + "entry_point": item.entry_point, + "status": "simulated_loaded" + } + + # For unknown skills, return None to indicate they need to be created + return None + + async def _get_marketplace_status(self) -> Dict[str, Any]: + """Get the current status of the marketplace integration. + + Returns: + Marketplace status information + """ + installed_items = self.marketplace.get_installed_items() + enabled_items = self.marketplace.get_enabled_items() + + return { + "total_marketplace_items": len(self.marketplace.items), + "installed_items": len(installed_items), + "enabled_items": len(enabled_items), + "available_skills": len(self.marketplace.get_items_by_type(MarketplaceItemType.SKILL)), + "available_mcp_servers": len(self.marketplace.get_items_by_type(MarketplaceItemType.MCP_SERVER)), + "installed_skills": len([i for i in installed_items if i.type == MarketplaceItemType.SKILL]), + "enabled_skills": len([i for i in enabled_items if i.type == MarketplaceItemType.SKILL]), + "loaded_marketplace_skills": len(self.loaded_marketplace_skills), + "recently_updated": sorted( + [item for item in self.marketplace.items if item.updated_at], + key=lambda x: x.updated_at, + reverse=True + )[:3] if self.marketplace.items else [] + } + + async def _use_marketplace_skill(self, skill_id: str, operation: str = "run", + **kwargs) -> Dict[str, Any]: + """Use a skill that was loaded from the marketplace. + + Args: + skill_id: ID of the skill to use + operation: Operation to perform on the skill + **kwargs: Additional arguments for the operation + + Returns: + Result of using the skill + """ + # Check if it's a loaded marketplace skill + if skill_id in self.loaded_marketplace_skills: + skill_data = self.loaded_marketplace_skills[skill_id] + return { + "status": "used_marketplace_skill", + "skill_id": skill_id, + "skill_name": skill_data.get("name", "unknown"), + "operation": operation, + "result": f"Simulated execution of {skill_data.get('name', 'marketplace skill')}", + **kwargs + } + + # Check if it's installed and try to load it + item = self.marketplace.get_item(skill_id) + if item and item.installed: + try: + loaded_skill = await self._attempt_load_marketplace_skill(item) + if loaded_skill: + self.loaded_marketplace_skills[skill_id] = loaded_skill + return { + "status": "loaded_and_used", + "skill_id": skill_id, + "skill_name": item.name, + "operation": operation, + "result": f"Loaded and executed {item.name}", + **kwargs + } + except Exception as e: + return { + "status": "error", + "message": f"Failed to load skill {skill_id}: {str(e)}" + } + + return { + "status": "error", + "message": f"Skill {skill_id} not found or not installed" + }
\ No newline at end of file diff --git a/src/agentux/skills/reasoning.py b/src/agentux/skills/reasoning.py new file mode 100644 index 0000000..cb88933 --- /dev/null +++ b/src/agentux/skills/reasoning.py @@ -0,0 +1,293 @@ +"""Advanced reasoning and planning skill for Agentux. +""" + +from __future__ import annotations + +import json +import re +from typing import Any, Dict, List, Optional + +from .base import BaseSkill + + +class ReasoningSkill(BaseSkill): + """Enhances the agent's reasoning and planning capabilities. + + This skill provides advanced reasoning patterns, task decomposition, + and strategic thinking capabilities that enable the agent to tackle + complex, multi-step problems like Claude Code. + """ + + def __init__(self, agent: Agent, config: Optional[Dict[str, Any]] = None): + super().__init__(agent, config) + self.reasoning_patterns = { + "task_decomposition": self._decompose_task, + "step_by_step_planning": self._create_step_by_step_plan, + "hierarchical_planning": self._create_hierarchical_plan, + "reflection": self._reflect_on_progress, + "problem_solving": self._apply_problem_solving_framework + } + + async def initialize(self) -> None: + """Initialize the reasoning skill.""" + # No async initialization needed for this skill + pass + + async def execute(self, operation: str, **kwargs) -> Any: + """Execute a reasoning operation. + + Args: + operation: The reasoning operation to perform + **kwargs: Additional arguments for the operation + + Returns: + The result of the reasoning operation + """ + if operation not in self.reasoning_patterns: + raise ValueError(f"Unknown reasoning operation: {operation}") + + return await self.reasoning_patterns[operation](**kwargs) + + async def _decompose_task(self, task_description: str, + max_subtasks: int = 5) -> List[Dict[str, Any]]: + """Break down a complex task into smaller, manageable subtasks. + + Args: + task_description: Description of the task to decompose + max_subtasks: Maximum number of subtasks to create + + Returns: + List of subtask dictionaries with descriptions and estimated complexity + """ + # Use the agent's own capabilities to decompose the task + prompt = f"""Break down the following task into {max_subtasks} or fewer smaller, manageable subtasks. +For each subtask, provide: +1. A clear description +2. Estimated complexity (simple, medium, complex) +3. Any dependencies on other subtasks + +Task: {task_description} + +Format your response as a JSON array of objects, where each object has: +- "description": string describing the subtask +- "complexity": "simple", "medium", or "complex" +- "dependencies": array of integers indicating which other subtasks this depends on (by index) + +Example: [{{"description": "Set up development environment", "complexity": "simple", "dependencies": []}}] + +Only return the JSON array, nothing else.""" + + # This would normally call the agent's provider, but for now we'll return a structured approach + # In a full implementation, this would use self.agent.run() or similar + + # For demonstration, return a generic decomposition + return [ + { + "description": f"Analyze and understand: {task_description}", + "complexity": "simple", + "dependencies": [] + }, + { + "description": f"Plan approach for: {task_description}", + "complexity": "medium", + "dependencies": [0] + }, + { + "description": f"Execute solution for: {task_description}", + "complexity": "complex", + "dependencies": [1] + }, + { + "description": f"Verify and test results for: {task_description}", + "complexity": "medium", + "dependencies": [2] + }, + { + "description": f"Document and finalize: {task_description}", + "complexity": "simple", + "dependencies": [3] + } + ][:max_subtasks] + + async def _create_step_by_step_plan(self, goal: str, + constraints: Optional[List[str]] = None) -> Dict[str, Any]: + """Create a detailed step-by-step plan to achieve a goal. + + Args: + goal: The goal to achieve + constraints: Any constraints or limitations + + Returns: + A structured plan with steps, estimated time, and resources needed + """ + constraints = constraints or [] + + # In a full implementation, this would use the agent's reasoning capabilities + # For now, return a structured template + return { + "goal": goal, + "constraints": constraints, + "steps": [ + { + "step": 1, + "description": "Understand the requirements and gather information", + "estimated_time": "5-15 minutes", + "tools_needed": ["search", "filesystem"] + }, + { + "step": 2, + "description": "Design the solution approach", + "estimated_time": "10-30 minutes", + "tools_needed": ["think", "todo"] + }, + { + "step": 3, + "description": "Implement the solution", + "estimated_time": "30-120 minutes", + "tools_needed": ["filesystem", "shell", "git"] + }, + { + "step": 4, + "description": "Test and validate the solution", + "estimated_time": "15-30 minutes", + "tools_needed": ["shell", "filesystem"] + }, + { + "step": 5, + "description": "Document and cleanup", + "estimated_time": "5-15 minutes", + "tools_needed": ["filesystem"] + } + ], + "estimated_total_time": "65-210 minutes", + "success_criteria": [ + "The goal stated in the request has been achieved", + "Any tests or validation checks pass", + "The solution follows best practices and conventions" + ] + } + + async def _create_hierarchical_plan(self, objective: str) -> Dict[str, Any]: + """Create a hierarchical plan with multiple levels of detail. + + Args: + objective: The high-level objective + + Returns: + A hierarchical plan structure + """ + return { + "objective": objective, + "levels": { + "strategic": { + "timeframe": "Long-term (weeks/months)", + "goals": [ + f"Achieve {objective}", + "Establish sustainable processes", + "Create reusable components" + ] + }, + "tactical": { + "timeframe": "Medium-term (days/weeks)", + "goals": [ + "Design system architecture", + "Implement core features", + "Set up development environment" + ] + }, + "operational": { + "timeframe": "Short-term (hours/days)", + "goals": [ + "Write specific code modules", + "Fix individual bugs", + "Complete defined tasks" + ] + } + } + } + + async def _reflect_on_progress(self, completed_work: List[str], + remaining_work: List[str]) -> Dict[str, Any]: + """Reflect on progress made and suggest adjustments. + + Args: + completed_work: List of completed tasks/work items + remaining_work: List of remaining tasks/work items + + Returns: + Reflection insights and recommendations + """ + return { + "progress_assessment": { + "completed_count": len(completed_work), + "remaining_count": len(remaining_work), + "completion_percentage": len(completed_work) / max(len(completed_work) + len(remaining_work), 1) * 100 + }, + "insights": [ + f"Completed {len(completed_work)} tasks so far", + f"Have {len(remaining_work)} tasks remaining", + "Progress is on track" if len(completed_work) >= len(remaining_work) else "May need to adjust approach" + ], + "recommendations": [ + "Continue with current approach" if len(completed_work) > 0 else "Consider starting with simpler tasks", + "Break down large remaining tasks into smaller pieces", + "Verify completed work before moving on" + ], + "suggested_adjustments": [] + } + + async def _apply_problem_solving_framework(self, problem: str) -> Dict[str, Any]: + """Apply a structured problem-solving framework. + + Args: + problem: Description of the problem to solve + + Returns: + Structured analysis and solution approach + """ + return { + "problem": problem, + "framework_applied": "IDEAL (Identify, Define, Explore, Act, Look)", + "steps": { + "Identify": { + "description": "Clearly identify what the problem is", + "questions": [ + "What exactly is not working or needs to be created?", + "What are the symptoms or error messages?", + "When does the problem occur?" + ] + }, + "Define": { + "description": "Define the problem clearly and specifically", + "questions": [ + "What are the boundaries of this problem?", + "What would a successful solution look like?", + "What constraints or requirements exist?" + ] + }, + "Explore": { + "description": "Explore possible solutions and approaches", + "questions": [ + "What similar problems have been solved before?", + "What different approaches could work?", + "What resources or tools are available?" + ] + }, + "Act": { + "description": "Act on the best solution found", + "questions": [ + "What is the most promising approach?", + "What steps need to be taken to implement it?", + "What risks or challenges might arise?" + ] + }, + "Look": { + "description": "Look back and evaluate the results", + "questions": [ + "Did the solution work as expected?", + "What was learned from this process?", + "How can this approach be improved or generalized?" + ] + } + } + }
\ No newline at end of file diff --git a/src/agentux/skills/self_improvement.py b/src/agentux/skills/self_improvement.py new file mode 100644 index 0000000..24524f9 --- /dev/null +++ b/src/agentux/skills/self_improvement.py @@ -0,0 +1,307 @@ +"""Self-improvement skill for Agentux. +""" + +from __future__ import annotations + +import os +import uuid +from pathlib import Path +from typing import Any, Dict, List, Optional + +from .base import BaseSkill + + +class SelfImprovementSkill(BaseSkill): + """Enables the agent to improve and extend its own capabilities. + + This skill allows Agentux to: + - Learn from interactions and experiences + - Create new skills based on patterns observed + - Modify existing behaviors and capabilities + - Extend its own functionality safely + """ + + def __init__(self, agent: Agent, config: Optional[Dict[str, Any]] = None): + super().__init__(agent, config) + self.improvement_history: List[Dict[str, Any]] = [] + self.learned_patterns: Dict[str, Any] = {} + self.custom_skills_dir = Path.home() / ".agentux" / "custom_skills" + self.custom_skills_dir.mkdir(parents=True, exist_ok=True) + + async def initialize(self) -> None: + """Initialize the self-improvement skill.""" + # Load any previously learned patterns + await self._load_learned_patterns() + + async def execute(self, operation: str, **kwargs) -> Any: + """Execute a self-improvement operation. + + Args: + operation: The improvement operation to perform + **kwargs: Additional arguments for the operation + + Returns: + The result of the improvement operation + """ + operations = { + "learn_from_interaction": self._learn_from_interaction, + "create_skill_from_pattern": self._create_skill_from_pattern, + "suggest_improvements": self._suggest_improvements, + "apply_learned_pattern": self._apply_learned_pattern, + "get_improvement_history": self._get_improvement_history + } + + if operation not in operations: + raise ValueError(f"Unknown improvement operation: {operation}") + + return await operations[operation](**kwargs) + + async def _learn_from_interaction(self, interaction_data: Dict[str, Any]) -> Dict[str, Any]: + """Learn from an interaction or experience. + + Args: + interaction_data: Data about the interaction to learn from + + Returns: + Record of what was learned + """ + interaction_id = str(uuid.uuid4()) + + # Extract patterns from the interaction + patterns = { + "task_type": interaction_data.get("task_type", "unknown"), + "tools_used": interaction_data.get("tools_used", []), + "success_indicators": interaction_data.get("success", False), + "approach_used": interaction_data.get("approach", ""), + "lessons_learned": interaction_data.get("lessons", []) + } + + # Store the learned pattern + self.learned_patterns[interaction_id] = { + "timestamp": interaction_data.get("timestamp", ""), + "patterns": patterns, + "interaction_data": interaction_data + } + + # Record in improvement history + improvement_record = { + "id": interaction_id, + "type": "learning", + "description": f"Learned from {interaction_data.get('task_type', 'an interaction')}", + "timestamp": interaction_data.get("timestamp", ""), + "patterns_identified": list(patterns.keys()) + } + + self.improvement_history.append(improvement_record) + await self._save_improvement_history() + + return { + "status": "learned", + "interaction_id": interaction_id, + "patterns_identified": len(patterns) + } + + async def _create_skill_from_pattern(self, pattern_name: str, + skill_description: str, + example_usage: Dict[str, Any]) -> Dict[str, Any]: + """Create a new skill based on a learned pattern. + + Args: + pattern_name: Name/identifier of the pattern to base the skill on + skill_description: Description of what the skill should do + example_usage: Example of how the skill would be used + + Returns: + Information about the created skill + """ + skill_id = str(uuid.uuid4()) + skill_name = f"learned_{skill_id[:8]}" + + # Create the skill file + skill_content = f'''"""Auto-generated skill: {skill_description} + +This skill was automatically created by Agentux's self-improvement system +based on learned patterns and user interactions. +""" + +from __future__ import annotations + +from typing import Any, Dict +from .base import BaseSkill + + +class {skill_name.replace('_', '').title()}Skill(BaseSkill): + """{skill_description}""" + + def __init__(self, agent, config: Optional[Dict[str, Any]] = None): + super().__init__(agent, config or {{}}) + + async def initialize(self) -> None: + """Initialize the skill.""" + # Initialization code would go here based on the learned pattern + pass + + async def execute(self, operation: str = "run", **kwargs) -> Any: + """Execute the skill's main functionality. + + Based on learned pattern: {pattern_name} + Example usage: {example_usage} + """ + # Implementation would go here based on the learned pattern + return {{"status": "executed", "skill": "{skill_name}", "operation": operation}} + + def get_info(self) -> Dict[str, Any]: + """Get information about this skill.""" + return {{ + "name": self.__class__.__name__, + "description": "{skill_description}", + "config": self.config + }} +''' + + # Save the skill file + skill_file = self.custom_skills_dir / f"{skill_name}.py" + with open(skill_file, "w") as f: + f.write(skill_content) + + # Record the improvement + improvement_record = { + "id": str(uuid.uuid4()), + "type": "skill_creation", + "description": f"Created skill '{skill_name}' from pattern '{pattern_name}'", + "skill_name": skill_name, + "skill_file": str(skill_file), + "timestamp": str(Path().stat().st_mtime) # Simplified timestamp + } + + self.improvement_history.append(improvement_record) + await self._save_improvement_history() + + return { + "status": "skill_created", + "skill_name": skill_name, + "skill_file": str(skill_file), + "can_be_loaded": True + } + + async def _suggest_improvements(self, current_capabilities: List[str]) -> Dict[str, Any]: + """Suggest improvements based on learned patterns and usage. + + Args: + current_capabilities: List of current agent capabilities + + Returns: + Suggested improvements and potential new skills + """ + suggestions = [] + + # Analyze learned patterns for improvement opportunities + if len(self.learned_patterns) > 5: + suggestions.append({ + "type": "pattern_based_skill", + "description": "Create a skill that encapsulates frequently used patterns", + "priority": "medium", + "estimated_effort": "low" + }) + + # Suggest based on common tool usage patterns + if "filesystem" in current_capabilities and "shell" in current_capabilities: + suggestions.append({ + "type": "workflow_automation", + "description": "Create a skill for automating common file+shell workflows", + "priority": "high", + "estimated_effort": "medium" + }) + + # Suggest meta-improvements + suggestions.append({ + "type": "reasoning_enhancement", + "description": "Enhance reasoning capabilities with more sophisticated frameworks", + "priority": "medium", + "estimated_effort": "medium" + }) + + return { + "current_learned_patterns": len(self.learned_patterns), + "improvement_history_count": len(self.improvement_history), + "suggestions": suggestions, + "next_steps": [ + "Review learned patterns for skill creation opportunities", + "Identify common workflows that could be automated", + "Consider which reasoning frameworks would be most beneficial" + ] + } + + async def _apply_learned_pattern(self, pattern_id: str, + context: Dict[str, Any]) -> Dict[str, Any]: + """Apply a previously learned pattern to a new context. + + Args: + pattern_id: ID of the learned pattern to apply + context: Context in which to apply the pattern + + Returns: + Result of applying the pattern + """ + if pattern_id not in self.learned_patterns: + return {"status": "error", "message": f"Pattern {pattern_id} not found"} + + pattern_data = self.learned_patterns[pattern_id] + # In a full implementation, this would adapt the pattern to the new context + + return { + "status": "pattern_applied", + "pattern_id": pattern_id, + "adapted_to_context": bool(context), + "pattern_data": pattern_data + } + + async def _get_improvement_history(self) -> Dict[str, Any]: + """Get the history of improvements and learning. + + Returns: + Summary of improvement activities + """ + # Count by type + type_counts = {} + for record in self.improvement_history: + record_type = record.get("type", "unknown") + type_counts[record_type] = type_counts.get(record_type, 0) + 1 + + return { + "total_improvements": len(self.improvement_history), + "total_learned_patterns": len(self.learned_patterns), + "improvement_breakdown": type_counts, + "recent_improvements": self.improvement_history[-5:] if self.improvement_history else [], + "custom_skills_available": len(list(self.custom_skills_dir.glob("*.py"))) if self.custom_skills_dir.exists() else 0 + } + + async def _save_improvement_history(self) -> None: + """Save improvement history to disk.""" + try: + history_file = self.custom_skills_dir / "improvement_history.json" + import json + with open(history_file, "w") as f: + json.dump({ + "improvement_history": self.improvement_history, + "learned_patterns": {k: v for k, v in self.learned_patterns.items() if k != "_meta"}, + "last_updated": str(Path().stat().st_mtime) + }, f, indent=2) + except Exception: + # Fail silently to avoid breaking the agent + pass + + async def _load_learned_patterns(self) -> None: + """Load previously learned patterns from disk.""" + try: + history_file = self.custom_skills_dir / "improvement_history.json" + if history_file.exists(): + import json + with open(history_file) as f: + data = json.load(f) + self.improvement_history = data.get("improvement_history", []) + self.learned_patterns = data.get("learned_patterns", {}) + except Exception: + # Fail silently - start with empty history + self.improvement_history = [] + self.learned_patterns = {}
\ No newline at end of file diff --git a/src/agentux/subagents/__init__.py b/src/agentux/subagents/__init__.py new file mode 100644 index 0000000..fc9a320 --- /dev/null +++ b/src/agentux/subagents/__init__.py @@ -0,0 +1,21 @@ +"""Autonomous subagent system package for Agentux.""" + +from .manager import ( + ARCHITECT_PROMPT, + CODER_PROMPT, + DelegateTool, + RESEARCHER_PROMPT, + REVIEWER_PROMPT, + SPECIALIST_CONFIGS, + SubagentManager, +) + +__all__ = [ + "SubagentManager", + "DelegateTool", + "SPECIALIST_CONFIGS", + "RESEARCHER_PROMPT", + "CODER_PROMPT", + "REVIEWER_PROMPT", + "ARCHITECT_PROMPT", +] diff --git a/src/agentux/subagents/manager.py b/src/agentux/subagents/manager.py new file mode 100644 index 0000000..46fe7c7 --- /dev/null +++ b/src/agentux/subagents/manager.py @@ -0,0 +1,180 @@ +"""Autonomous subagents and delegation system for Agentux. + +Allows hierarchical agent execution: the primary orchestrator can delegate +subtasks to specialized agents (researcher, coder, reviewer, architect) with +scoped tools, independent context windows, and dedicated system prompts. +""" + +from __future__ import annotations + +from typing import Any, Callable, Dict, List, Optional +from ..models import ToolDefinition +from ..tools.base import BaseTool + + +RESEARCHER_PROMPT = """\ +You are an expert Codebase Researcher subagent. +Your goal is to thoroughly investigate the codebase to answer the user's inquiry or find code locations. +Rules: +- You are strictly read-only. +- Use 'search', 'filesystem', 'repomap', and 'outline_symbols' to find relevant code. +- Report exact file paths, line numbers, function/class names, and concise summaries. +- Keep your final report direct and actionable for the parent agent.\ +""" + +CODER_PROMPT = """\ +You are an expert Implementation Coder subagent. +Your goal is to implement the requested code changes with minimal, surgical edits. +Rules: +- Read files before editing. +- Use 'filesystem' operation 'edit' to replace exact target strings. +- Match existing idioms, naming conventions, and style. +- State clearly what files were modified.\ +""" + +REVIEWER_PROMPT = """\ +You are a senior Code Reviewer and Quality Assurance subagent. +Your goal is to inspect current git diffs and code modifications for bugs, regressions, security flaws, and test coverage. +Rules: +- Inspect git status and git diff. +- Run tests via 'shell' when appropriate to verify changes. +- Provide a clear, prioritized list of findings (Critical, Warning, Improvement) or verify that changes are ready to commit.\ +""" + +ARCHITECT_PROMPT = """\ +You are a Software Architect subagent. +Your goal is to inspect high-level project structure, dependencies, and design patterns to create a clear plan. +Rules: +- Use 'project' and 'repomap' to understand layout. +- Decompose the request into ordered, testable steps in 'todo'. +- Deliver an architectural recommendation with file boundaries and interfaces.\ +""" + +SPECIALIST_CONFIGS: Dict[str, Dict[str, Any]] = { + "researcher": { + "prompt": RESEARCHER_PROMPT, + "tools": ["filesystem", "search", "outline_symbols", "repomap", "project"], + "read_only": True, + }, + "coder": { + "prompt": CODER_PROMPT, + "tools": ["filesystem", "git", "shell", "search"], + "read_only": False, + }, + "reviewer": { + "prompt": REVIEWER_PROMPT, + "tools": ["git", "filesystem", "shell", "search"], + "read_only": True, + }, + "architect": { + "prompt": ARCHITECT_PROMPT, + "tools": ["project", "repomap", "search", "todo"], + "read_only": True, + }, +} + + +class SubagentManager: + """Orchestrates spawning, running, and reporting of specialist subagents.""" + + def __init__(self, parent_agent: Any) -> None: + self.parent_agent = parent_agent + self.history: List[Dict[str, Any]] = [] + + async def run_subagent(self, role: str, task: str) -> str: + """Run an isolated subagent and return its final answer.""" + from ..agent import Agent + from ..tools.registry import ToolRegistry + from ..tools.filesystem import FilesystemTool + + role_lower = role.lower().strip() + spec = SPECIALIST_CONFIGS.get(role_lower) + if not spec: + available = ", ".join(SPECIALIST_CONFIGS.keys()) + return f"Unknown subagent role '{role}'. Available specialist roles: {available}." + + # Build scoped registry for subagent + scoped_registry = ToolRegistry() + for name in spec["tools"]: + try: + tool = self.parent_agent.registry.get(name) + # If researcher or reviewer needs read-only filesystem + if spec["read_only"] and name == "filesystem": + tool = FilesystemTool( + root=self.parent_agent.config.working_dir, + read_only=True + ) + scoped_registry.register(tool) + except Exception: + pass + + # Create isolated subagent + subagent = Agent( + config=self.parent_agent.config, + provider=self.parent_agent.provider, + registry=scoped_registry, + system_prompt=spec["prompt"], + ) + + # Notify parent TUI/listeners of subagent activity + if hasattr(self.parent_agent, "_emit"): + self.parent_agent._emit("narration", f"🤖 Spawning '{role_lower}' subagent for: {task}") + + try: + result = await subagent.run(task, interactive=False) + self.history.append({ + "role": role_lower, + "task": task, + "steps": subagent.last_steps, + "tool_calls": subagent.tool_calls_made, + "result": result, + }) + return f"[{role_lower.upper()} SUBAGENT REPORT]\n{result}" + except Exception as exc: + return f"[{role_lower.upper()} SUBAGENT ERROR]: {exc}" + + +class DelegateTool(BaseTool): + """Tool allowing the agent to delegate subtasks to autonomous subagents.""" + + def __init__(self, manager: SubagentManager) -> None: + self.manager = manager + + @property + def name(self) -> str: + return "delegate" + + @property + def description(self) -> str: + return ( + "Delegate a subtask to an autonomous specialist subagent. " + "Roles: 'researcher' (read-only code investigation), " + "'coder' (targeted code changes/edits), " + "'reviewer' (diff inspection, QA, test validation), " + "'architect' (high-level system design and planning)." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "role": { + "type": "string", + "enum": ["researcher", "coder", "reviewer", "architect"], + "description": "The specialist role to delegate to.", + }, + "task": { + "type": "string", + "description": "Detailed prompt describing what the subagent should investigate or do.", + }, + }, + "required": ["role", "task"], + } + + async def execute(self, **kwargs: Any) -> str: + role = kwargs.get("role", "researcher") + task = kwargs.get("task", "") + if not task: + return "ERROR: 'task' argument is required for delegation." + return await self.manager.run_subagent(role, task) diff --git a/src/agentux/text_tools.py b/src/agentux/text_tools.py new file mode 100644 index 0000000..1a1f8ee --- /dev/null +++ b/src/agentux/text_tools.py @@ -0,0 +1,209 @@ +"""Text-based tool calling extraction and system prompt formatting. + +Allows smaller or local models (e.g. qwen2.5-coder:3b, llama-3, phi-3) whose +chat templates do not emit structured OpenAI API tool_calls to invoke tools +reliably via clear, structured markdown or XML text blocks. +""" + +from __future__ import annotations + +import json +import re +import uuid +from typing import Any, Dict, List, Optional, Set, Tuple + +from .models import ToolCall, ToolDefinition + + +TOOL_PROMPT_INSTRUCTIONS = """ +## Tool Calling Format +You can invoke workspace tools directly. If your environment does not support native API tool calling, you MUST output your tool invocation using this exact, recognizable format: + +### tool +*<tool_name> +```json +{ + "<argument_name>": "<argument_value>" +} +``` + +Or using standard tool call tags: +<tool_call> +{"name": "<tool_name>", "arguments": { ... }} +</tool_call> + +When a tool finishes running, the system will return the output in this format: +### tool_result +*<tool_name> +<result> + +You can then inspect the output and proceed to the next step or give your final answer. +""" + +# Aliases for common shorthand operations +TOOL_ALIASES: Dict[str, Tuple[str, Optional[Dict[str, Any]]]] = { + "read": ("filesystem", {"operation": "read"}), + "write": ("filesystem", {"operation": "write"}), + "edit": ("filesystem", {"operation": "edit"}), + "ls": ("filesystem", {"operation": "ls"}), + "mkdir": ("filesystem", {"operation": "mkdir"}), + "bash": ("shell", None), + "sh": ("shell", None), + "run": ("shell", None), +} + + +def extract_text_tool_calls( + content: str, + tools: Optional[List[ToolDefinition]] = None, +) -> Tuple[List[ToolCall], str]: + """Extract tool calls from text content. + + Returns: + (tool_calls, cleaned_content) + """ + if not content: + return [], "" + + known_tools: Set[str] = {t.name for t in tools} if tools else set() + tool_calls: List[ToolCall] = [] + cleaned: str = content + + # 1. User/Markdown format: + # ### tool + # *<name> + # ```json + # { ... } + # ``` + pattern_md = re.compile( + r"###\s*tool\s*\n\*\s*([a-zA-Z0-9_]+)\s*\n(?:```(?:json)?\s*)?(\{[\s\S]*?\})(?:\s*```)?", + re.DOTALL | re.IGNORECASE, + ) + for m in pattern_md.finditer(content): + raw_name = m.group(1).strip() + raw_json = m.group(2).strip() + name, default_args = _resolve_tool_name(raw_name, known_tools) + if name: + try: + args = json.loads(raw_json) + if not isinstance(args, dict): + args = {} + if default_args: + args = {**default_args, **args} + tool_calls.append( + ToolCall( + id=f"call_{uuid.uuid4().hex[:12]}", + name=name, + arguments=args, + ) + ) + cleaned = cleaned.replace(m.group(0), "") + except Exception: + pass + + # 2. XML tag format: + # <tool_call> + # {"name": "...", "arguments": { ... }} + # </tool_call> + pattern_xml = re.compile( + r"<tool_call>\s*(?:```(?:json)?\s*)?(\{[\s\S]*?\})(?:\s*```)?\s*</tool_call>", + re.DOTALL | re.IGNORECASE, + ) + for m in pattern_xml.finditer(content): + raw_json = m.group(1).strip() + try: + data = json.loads(raw_json) + if isinstance(data, dict): + raw_name = data.get("name") or data.get("function") + if isinstance(raw_name, dict): + raw_name = raw_name.get("name") + if isinstance(raw_name, str): + name, default_args = _resolve_tool_name(raw_name, known_tools) + if name: + args = data.get("arguments", {}) + if isinstance(args, str): + try: + args = json.loads(args) + except Exception: + args = {} + if not isinstance(args, dict): + args = {} + if default_args: + args = {**default_args, **args} + tool_calls.append( + ToolCall( + id=f"call_{uuid.uuid4().hex[:12]}", + name=name, + arguments=args, + ) + ) + cleaned = cleaned.replace(m.group(0), "") + except Exception: + pass + + # 3. Fenced code block or bare JSON: + # {"name": "filesystem", "arguments": { ... }} + if not tool_calls: + text_strip = content.strip() + # Check if entire content is bare JSON or fenced JSON + json_candidate = text_strip + if json_candidate.startswith("```"): + lines = json_candidate.split("\n") + if len(lines) >= 3 and lines[-1].strip().startswith("```"): + json_candidate = "\n".join(lines[1:-1]).strip() + + if json_candidate.startswith("{") and json_candidate.endswith("}"): + try: + parsed = json.loads(json_candidate) + if isinstance(parsed, dict): + candidate = parsed.get("tool_call") if isinstance(parsed.get("tool_call"), dict) else parsed + raw_name = candidate.get("name") or candidate.get("function") + if isinstance(raw_name, dict): + raw_name = raw_name.get("name") + if isinstance(raw_name, str): + name, default_args = _resolve_tool_name(raw_name, known_tools) + if name: + args = candidate.get("arguments", {}) + if isinstance(args, str): + try: + args = json.loads(args) + except Exception: + args = {} + if not isinstance(args, dict): + args = {} + if default_args: + args = {**default_args, **args} + tool_calls.append( + ToolCall( + id=f"call_{uuid.uuid4().hex[:12]}", + name=name, + arguments=args, + ) + ) + cleaned = "" + except Exception: + pass + + return tool_calls, cleaned.strip() + + +def _resolve_tool_name( + raw_name: str, + known_tools: Set[str], +) -> Tuple[Optional[str], Optional[Dict[str, Any]]]: + """Resolve tool name against known registered tools and shorthand aliases.""" + name_clean = raw_name.strip() + if name_clean in known_tools: + return name_clean, None + + # Check lowercase alias + alias_match = TOOL_ALIASES.get(name_clean.lower()) + if alias_match: + target, def_args = alias_match + if target in known_tools: + return target, def_args + + return None, None + + +__all__ = ["extract_text_tool_calls", "TOOL_PROMPT_INSTRUCTIONS", "TOOL_ALIASES"] diff --git a/src/agentux/theme.py b/src/agentux/theme.py new file mode 100644 index 0000000..64b9e12 --- /dev/null +++ b/src/agentux/theme.py @@ -0,0 +1,167 @@ +"""The Agentux palette, taken from the brand at kidux.surge.sh. + +One module owns every colour the interface uses, so the terminal and the rich +renderers cannot drift apart. Both :mod:`agentux.ui` and :mod:`agentux.tui` +read from here. + +The brand is a dark, retro-hardware palette: near-black grounds, emerald and +cyan carrying the interface, yellow for warnings, purple and pink for accents +and failures. The values below are the brand's own, except the borders, which +the brand defines as translucent white. A terminal has no alpha channel, so +those are composited over ``--bg-pure`` here -- 14% white over ``#030508`` is +``#26282b``, and 8% is ``#17191c``. Deriving them beats guessing a grey: the +ratio between border and ground is the brand's, not ours. +""" + +from __future__ import annotations + +from enum import Enum +from typing import Dict, Tuple + +# -- grounds --------------------------------------------------------------- +#: The darkest ground - full black for Opencode-like appearance +BG_PURE = "#000000" +#: The raised panel ground, one step up from the page. +BG_SURFACE = "#000000" + +# -- accents --------------------------------------------------------------- +#: The primary. The prompt, the brand mark, anything that means "you". +EMERALD = "#00ff88" +#: The secondary. Tool activity and other machine-side events. +CYAN = "#00f0ff" +#: Warnings: recoverable, but the user should look. +YELLOW = "#ffd60a" +#: Secondary accent, for values that need to stand out without alarming. +PURPLE = "#bf5af2" +#: Failures. Named for the brand token even though it is a red. +PINK = "#ff3b30" + +# -- text ------------------------------------------------------------------ +#: Body copy. +TEXT_LIGHT = "#f4f7fc" +#: Supporting copy: labels, footers, secondary lines. +TEXT_MUTED = "#94a0b3" +#: The quietest text that should still be legible. +TEXT_DIM = "#546073" + +# -- borders --------------------------------------------------------------- +#: ``rgba(255, 255, 255, 0.14)`` over :data:`BG_PURE`. Panel and frame edges. +BORDER = "#26282b" +#: ``rgba(255, 255, 255, 0.08)`` over :data:`BG_PURE`. Rules and dividers +#: that should be felt rather than read. +BORDER_SUBTLE = "#17191c" + +# -- gradients ------------------------------------------------------------- +#: The wordmark ramps emerald -> cyan down the rows. +#: +#: Vertical, not horizontal. The glyphs are solid block characters, so ramping +#: across each row colours neighbouring columns of the same letter differently +#: and the letter reads as vertical stripes instead of one shape. +WORDMARK_START: Tuple[int, int, int] = (0, 255, 136) +WORDMARK_END: Tuple[int, int, int] = (0, 240, 255) +#: The extruded side of each letter. A deep green, so the depth belongs to the +#: same object as the face rather than reading as a separate grey slab. +WORDMARK_DEPTH: Tuple[int, int, int] = (12, 74, 56) +#: What the extrusion fades toward at the bottom: the page ground. +WORDMARK_SHADOW: Tuple[int, int, int] = (3, 5, 8) + + +#: Operation modes for Agentux. +class Mode(Enum): + """Operation modes for Agentux.""" + CHAT = "chat" # Normal conversational mode + BUILD = "build" # Focused on building/creating + PLAN = "plan" # Focused on planning/designing + + +def _mix(first: Tuple[int, int, int], second: Tuple[int, int, int], t: float) -> str: + """A hex colour between two RGB points.""" + t = max(0.0, min(1.0, t)) + return "#{:02x}{:02x}{:02x}".format( + round(first[0] + (second[0] - first[0]) * t), + round(first[1] + (second[1] - first[1]) * t), + round(first[2] + (second[2] - first[2]) * t), + ) + + +#: A dimmed emerald, for chrome that must recede. Interpolating between the +#: accent and the ground keeps the hue, so dimmed text still reads as *ours*. +ACCENT_DIM = _mix(WORDMARK_START, (3, 5, 8), 0.45) + +#: Accent gradient start for interactive elements (used in commands.py) +ACCENT_START_HEX = "#{:02x}{:02x}{:02x}".format(*WORDMARK_START) +#: Accent gradient end for interactive elements (used in commands.py) +ACCENT_END_HEX = "#{:02x}{:02x}{:02x}".format(*WORDMARK_END) + +#: The prompt_toolkit class names the TUI styles fragments against, and the +#: hex each one resolves to. Kept beside the palette so adding an accent means +#: editing one list. +STYLE_CLASSES: Dict[str, str] = { + "frame": BORDER, + "frame-focus": EMERALD, + "accent": EMERALD, + "accent-dim": ACCENT_DIM, + "brand": EMERALD, + "label": TEXT_MUTED, + "value": TEXT_LIGHT, + "tool": CYAN, + "tool-arg": TEXT_MUTED, + "error": PINK, + "warn": YELLOW, + "ok": EMERALD, + "prompt": EMERALD, + "body": TEXT_LIGHT, + "footer": TEXT_DIM, + "rule": BORDER_SUBTLE, + "scrollbar": BORDER_SUBTLE, +} + + +__all__ = [ + "BG_PURE", + "BG_SURFACE", + "EMERALD", + "CYAN", + "YELLOW", + "PURPLE", + "PINK", + "TEXT_LIGHT", + "TEXT_MUTED", + "TEXT_DIM", + "BORDER", + "BORDER_SUBTLE", + "ACCENT_DIM", + "ACCENT_START_HEX", + "ACCENT_END_HEX", + "WORDMARK_START", + "WORDMARK_END", + "WORDMARK_DEPTH", + "WORDMARK_SHADOW", + "STYLE_CLASSES", + "Mode" +] + + +__all__ = [ + "BG_PURE", + "BG_SURFACE", + "EMERALD", + "CYAN", + "YELLOW", + "PURPLE", + "PINK", + "TEXT_LIGHT", + "TEXT_MUTED", + "TEXT_DIM", + "BORDER", + "BORDER_SUBTLE", + "ACCENT_DIM", + "ACCENT_START_HEX", + "ACCENT_END_HEX", + "WORDMARK_START", + "WORDMARK_END", + "WORDMARK_DEPTH", + "WORDMARK_SHADOW", + "STYLE_CLASSES", + "Mode" +]
\ No newline at end of file diff --git a/src/agentux/tools/checkpoint_tool.py b/src/agentux/tools/checkpoint_tool.py new file mode 100644 index 0000000..2302bbb --- /dev/null +++ b/src/agentux/tools/checkpoint_tool.py @@ -0,0 +1,61 @@ +"""Checkpoint tool for Agentux.""" + +from __future__ import annotations + +from typing import Any, Dict +from ..checkpoint import CheckpointManager +from ..models import ToolDefinition +from .base import BaseTool + + +class CheckpointTool(BaseTool): + """Tool allowing the agent to create checkpoints, view diffs, and inspect state.""" + + def __init__(self, manager: CheckpointManager) -> None: + self.manager = manager + + @property + def name(self) -> str: + return "checkpoint" + + @property + def description(self) -> str: + return ( + "Manage project checkpoints and inspect session diffs. " + "Actions: 'create' (create new snapshot), 'diff' (view current unified diff), " + "'list' (list recent checkpoints)." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "action": { + "type": "string", + "enum": ["create", "diff", "list"], + "description": "The action to perform.", + }, + "description": { + "type": "string", + "description": "Description for action='create'.", + }, + }, + "required": ["action"], + } + + async def execute(self, **kwargs: Any) -> str: + action = kwargs.get("action", "diff") + if action == "create": + desc = kwargs.get("description", "Manual agent snapshot") + cp = self.manager.create_checkpoint(desc) + return f"Created checkpoint '{cp.id}' at {cp.formatted_time}: {desc}" + elif action == "diff": + return self.manager.get_diff() + elif action == "list": + cps = self.manager.list_checkpoints() + if not cps: + return "No checkpoints recorded in this session." + lines = [f"- [{c.id}] ({c.formatted_time}) {c.description} ({len(c.files)} files)" for c in cps] + return "Session Checkpoints:\n" + "\n".join(lines) + return f"Unknown action: {action}" diff --git a/src/agentux/tools/git.py b/src/agentux/tools/git.py new file mode 100644 index 0000000..ccc3db1 --- /dev/null +++ b/src/agentux/tools/git.py @@ -0,0 +1,192 @@ +"""Git inspection. + +Read-only by construction. Knowing what changed and what is dirty is how an +agent avoids overwriting work in progress -- both the user's and its own. + +Every subcommand here is a query. Anything that rewrites history or moves +commits is the shell tool's job, where it passes through the safety prompt. +""" + +from __future__ import annotations + +import os +import subprocess + +from ..errors import ToolError +from .base import BaseTool + +#: Subcommands this tool will run. +ACTIONS = {"status", "diff", "log", "show", "branch", "blame", "stash_list", "commit"} +READ_ONLY = ACTIONS + +DEFAULT_TIMEOUT = 20 +MAX_OUTPUT = 40_000 + + +class GitTool(BaseTool): + """Inspect the repository's state without changing anything.""" + + def __init__(self, root: Optional[str] = None, timeout: int = DEFAULT_TIMEOUT) -> None: + self.root = os.path.realpath(root or os.getcwd()) + self.timeout = timeout + + @property + def name(self) -> str: + return "git" + + @property + def description(self) -> str: + return ( + "Inspect the git repository: current status and uncommitted " + "changes, diffs (staged or working tree), recent commit history, " + "the contents of a commit, branches, or line authorship. Read-only " + "-- it cannot stage, commit, or rewrite anything. Check status " + "before editing so you do not overwrite work already in progress." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "action": { + "type": "string", + "enum": ["status", "diff", "log", "show", "branch", "blame", "stash_list", "commit"], + "description": ( + "status: branch and modified/untracked files. " + "diff: changes (add file= for staged). " + "log: recent commits. show: one commit's changes. " + "branch: list branches. blame: who wrote each line. " + "stash_list: saved stashes. " + "commit: stage changes and create a git commit with 'message'." + ), + }, + "message": { + "type": "string", + "description": "For 'commit', the commit message to record.", + }, + "stage_all": { + "type": "boolean", + "description": "For 'commit', whether to run git add -A first. Defaults to true.", + }, + "path": { + "type": "string", + "description": "Limit the diff or blame to this path.", + }, + "staged": { + "type": "boolean", + "description": "For 'diff', show staged changes only. Defaults to false.", + }, + "revision": { + "type": "string", + "description": "For 'show' and 'log', a revision (HEAD, HEAD~2, a sha).", + }, + "lines": { + "type": "integer", + "description": "Number of context lines in a diff. Defaults to 3.", + }, + "limit": { + "type": "integer", + "description": "Number of commits for 'log'. Defaults to 15.", + }, + }, + "required": ["action"], + } + + def _cwd(self) -> str: + if not os.path.isdir(os.path.join(self.root, ".git")): + # Worktrees and submodules keep the real git dir elsewhere. + probe = subprocess.run( + ["git", "rev-parse", "--is-inside-work-tree"], + cwd=self.root, capture_output=True, text=True, timeout=self.timeout, + ) + if probe.returncode != 0 or probe.stdout.strip() != "true": + raise ToolError( + f"{self.root} is not a git repository. The git tool only " + "works inside one; use the shell tool for raw git commands." + ) + return self.root + + def _run(self, args: List[str]) -> str: + try: + result = subprocess.run( + ["git", "-C", self._cwd()] + args, + capture_output=True, + text=True, + timeout=self.timeout, + ) + except FileNotFoundError: + raise ToolError("git is not available on this system.") from None + except subprocess.TimeoutExpired: + raise ToolError(f"git {' '.join(args[:2])} timed out after {self.timeout}s.") from None + + if result.returncode != 0: + message = (result.stderr or result.stdout).strip() + raise ToolError(f"git {' '.join(args[:2])} failed: {message or 'no output'}") + + output = result.stdout.strip() + if not output: + return "(no output)" + if len(output) > MAX_OUTPUT: + head = output[: MAX_OUTPUT // 2] + tail = output[-MAX_OUTPUT // 2 :] + dropped = len(output) - MAX_OUTPUT + return f"{head}\n\n... [{dropped} characters omitted] ...\n\n{tail}" + return output + + def _build(self, action: str, **kwargs: Any) -> List[str]: + if action not in READ_ONLY: + raise ToolError( + f"Unsupported git action {action!r}. This tool is read-only and " + f"supports: {', '.join(sorted(READ_ONLY))}." + ) + + path = kwargs.get("path") + staged = bool(kwargs.get("staged")) + revision = kwargs.get("revision") + context = max(0, min(int(kwargs.get("lines") or 3), 20)) + limit = max(1, min(int(kwargs.get("limit") or 15), 100)) + + if action == "status": + return ["status", "--short", "--branch"] + if action == "diff": + args = ["diff", f"-U{context}"] + if staged: + args.append("--cached") + if revision: + args.append(revision) + if path: + args += ["--", path] + return args + if action == "log": + args = ["log", f"-{limit}", "--no-color"] + if path: + args += ["--", path] + return args + if action == "show": + return ["show", "--no-color", f"-U{context}", revision or "HEAD"] + if action == "branch": + return ["branch", "-vv", "--all"] + if action == "blame": + if not path: + raise ToolError("'blame' needs a 'path' to inspect.") + return ["blame", "-w", "--", path] + return ["stash", "list"] + + async def execute(self, action: str, **kwargs: Any) -> str: + if not action: + raise ToolError("The git tool needs an 'action'.") + + if action == "commit": + message = kwargs.get("message") + if not message or not str(message).strip(): + raise ToolError("'commit' action requires a non-empty 'message'.") + stage_all = kwargs.get("stage_all", True) + if stage_all: + self._run(["add", "-A"]) + return self._run(["commit", "-m", str(message).strip()]) + + return self._run(self._build(action, **kwargs)) + + +__all__ = ["GitTool"] diff --git a/src/agentux/tools/image.py b/src/agentux/tools/image.py new file mode 100644 index 0000000..9515ff1 --- /dev/null +++ b/src/agentux/tools/image.py @@ -0,0 +1,172 @@ +"""Terminal image graphics rendering tool powered by Chafa. + +Allows the AI model and user to view images directly inside the terminal. +""" + +from __future__ import annotations + +import os +import shutil +import struct +import subprocess +import urllib.parse +import urllib.request +from typing import Any, Dict, Optional, Tuple + +from ..errors import ToolError +from .base import BaseTool + +CHAFA_CANDIDATES = [ + "chafa", + "/opt/local/bin/chafa", + "/usr/local/bin/chafa", + "/usr/bin/chafa", + "/home/linuxbrew/.linuxbrew/bin/chafa", +] + + +def find_chafa() -> Optional[str]: + """Locate the chafa executable on the host system.""" + for candidate in CHAFA_CANDIDATES: + found = shutil.which(candidate) + if found: + return found + if os.path.isfile(candidate) and os.access(candidate, os.X_OK): + return candidate + return None + + +def get_image_info(path: str) -> Optional[Tuple[str, int, int]]: + """Extract format, width, and height for common image types without external libraries.""" + try: + with open(path, "rb") as f: + data = f.read(32) + if len(data) < 16: + return None + + # PNG + if data.startswith(b"\x89PNG\r\n\x1a\n"): + w, h = struct.unpack(">II", data[16:24]) + return ("PNG", w, h) + + # GIF + if data.startswith((b"GIF87a", b"GIF89a")): + w, h = struct.unpack("<HH", data[6:10]) + return ("GIF", w, h) + + # JPEG + if data.startswith(b"\xff\xd8"): + f.seek(0) + b = f.read() + i = 2 + while i < len(b) - 8: + marker, length = struct.unpack(">HH", b[i:i+4]) + if marker in (0xFFC0, 0xFFC2): + h, w = struct.unpack(">HH", b[i+5:i+9]) + return ("JPEG", w, h) + i += length + 2 + return ("JPEG", 0, 0) + except Exception: + pass + return None + + +class ViewImageTool(BaseTool): + """Render and inspect local or remote images in terminal graphics format.""" + + def __init__(self, root: Optional[str] = None) -> None: + self.root = os.path.realpath(root or os.getcwd()) + + @property + def name(self) -> str: + return "view_image" + + @property + def description(self) -> str: + return ( + "View and render images (PNG, JPG, SVG, WebP, GIF) directly in the " + "terminal using Chafa terminal graphics. Accepts local file paths or URLs." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Path to local image file (relative to workspace) or remote HTTP/HTTPS URL.", + }, + "max_width": { + "type": "integer", + "description": "Maximum width in terminal character columns (default: 60).", + }, + "max_height": { + "type": "integer", + "description": "Maximum height in terminal character rows (default: 25).", + }, + }, + "required": ["path"], + } + + async def execute(self, path: str, max_width: int = 60, max_height: int = 25) -> str: + path = path.strip() + if not path: + raise ToolError("Image path cannot be empty.") + + local_path = path + is_temp = False + + if path.startswith(("http://", "https://")): + # Download remote image to temporary file + try: + import tempfile + parsed = urllib.parse.urlparse(path) + suffix = os.path.splitext(parsed.path)[1] or ".png" + with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp: + local_path = tmp.name + is_temp = True + urllib.request.urlretrieve(path, local_path) + except Exception as exc: + return f"Failed to download remote image from {path}: {exc}" + else: + # Resolve and verify local path + if not os.path.isabs(local_path): + local_path = os.path.join(self.root, local_path) + local_path = os.path.realpath(local_path) + if not local_path.startswith(self.root): + raise ToolError(f"Path escapes workspace directory: {path}") + if not os.path.isfile(local_path): + raise ToolError(f"Image file not found: {path}") + + try: + chafa_bin = find_chafa() + if chafa_bin: + size_arg = f"--size={max_width}x{max_height}" + proc = subprocess.run( + [chafa_bin, size_arg, "--format=symbols", local_path], + capture_output=True, + text=True, + timeout=15, + ) + if proc.returncode == 0 and proc.stdout.strip(): + return f"[Terminal Graphics: {os.path.basename(path)}]\n\n" + proc.stdout + + # Fallback metadata representation if chafa is not installed + info = get_image_info(local_path) + if info: + fmt, w, h = info + dim_str = f"{w}x{h} px" if w and h else "unknown dimensions" + size_kb = os.path.getsize(local_path) / 1024 + return f"[📷 Image: {os.path.basename(path)} · {fmt} · {dim_str} · {size_kb:.1f} KB (chafa not installed for ASCII render)]" + + return f"[📷 Image: {os.path.basename(path)} (chafa not installed for inline rendering)]" + finally: + if is_temp and os.path.exists(local_path): + try: + os.unlink(local_path) + except Exception: + pass + + +__all__ = ["ViewImageTool", "find_chafa"] diff --git a/src/agentux/tools/knowledge_tool.py b/src/agentux/tools/knowledge_tool.py new file mode 100644 index 0000000..4b0e452 --- /dev/null +++ b/src/agentux/tools/knowledge_tool.py @@ -0,0 +1,612 @@ +"""Knowledge database tools for Agentux Solo. + +The model's read/write access to its persistent knowledge store. These tools +exist so a small model does not have to remember everything: it can look up +what it learned before, save what it just discovered, and inspect the store. +""" + +from __future__ import annotations + +from typing import Any, Dict, List + +from ..errors import ToolError +from ..knowledge import ( + KnowledgeStore, + VERIFICATION_CONFLICTING, + VERIFICATION_VERIFIED, + VERIFICATION_UNVERIFIED, +) +from .base import BaseTool + +_VALID_VERIFICATION = (VERIFICATION_UNVERIFIED, VERIFICATION_VERIFIED, VERIFICATION_CONFLICTING) + + +def _format_entry(k) -> str: + lines = [ + f"[{k.id}] {k.title}", + f" Category: {k.category or '(none)'}", + f" Confidence: {k.confidence:.0%} Verification: {k.verification}", + f" Tags: {k.tags or '(none)'}", + f" Content: {k.content}", + ] + if k.sources: + lines.append(" Sources:") + for s in k.sources: + lines.append(f" - {s.get('url', '')}") + return "\n".join(lines) + + +class SearchKnowledgeTool(BaseTool): + """Search the persistent knowledge database.""" + + def __init__(self, store: KnowledgeStore) -> None: + self.store = store + + @property + def name(self) -> str: + return "search_knowledge" + + @property + def description(self) -> str: + return ( + "Search what you learned before and stored in your knowledge " + "database. Use this BEFORE answering a factual question you might " + "already know the answer to. Returns matching entries with their " + "sources, confidence, and verification status." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Keywords describing what you are looking for.", + }, + "category": { + "type": "string", + "description": "Optional category to restrict the search to.", + }, + "limit": { + "type": "integer", + "description": "Maximum entries to return (default 10).", + }, + }, + "required": ["query"], + } + + async def execute(self, query: str, category: str = "", limit: int = 10, **kwargs: Any) -> str: + if not query or not str(query).strip(): + return "No query provided." + try: + count = max(1, min(int(limit or 10), 50)) + except (TypeError, ValueError): + count = 10 + hits = self.store.search(str(query), category=category or None, limit=count) + if not hits: + return "No matching knowledge entries found." + header = f"Found {len(hits)} matching knowledge entr(ies):" + return header + "\n\n" + "\n\n".join(_format_entry(k) for k in hits) + + +class SaveKnowledgeTool(BaseTool): + """Store newly discovered information in the knowledge database.""" + + def __init__(self, store: KnowledgeStore) -> None: + self.store = store + + @property + def name(self) -> str: + return "save_knowledge" + + @property + def description(self) -> str: + return ( + "Save something you discovered to your persistent knowledge " + "database. Use this after researching a topic so you do not have " + "to look it up again next time. Store one fact per call. Include " + "the source URLs so you can verify the information later." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "title": { + "type": "string", + "description": "Short title for this fact.", + }, + "content": { + "type": "string", + "description": "The fact itself, in one or two sentences.", + }, + "category": { + "type": "string", + "description": "Optional category, e.g. 'history', 'science', 'programming'.", + }, + "tags": { + "type": "string", + "description": "Optional comma-separated keywords.", + }, + "confidence": { + "type": "number", + "description": "How confident you are (0.0 to 1.0). Default 0.5.", + }, + "verification": { + "type": "string", + "enum": list(_VALID_VERIFICATION), + "description": "'unverified' (default), 'verified', or 'conflicting'.", + }, + "sources": { + "type": "array", + "items": {"type": "object"}, + "description": "Optional list of source URLs this fact came from.", + }, + }, + "required": ["title", "content"], + } + + async def execute( + self, + title: str, + content: str, + category: str = "", + tags: str = "", + confidence: float = 0.5, + verification: str = VERIFICATION_UNVERIFIED, + sources: List[Dict[str, Any]] = None, + **kwargs: Any, + ) -> str: + if not title or not str(title).strip(): + raise ToolError("'title' is required.") + if not content or not str(content).strip(): + raise ToolError("'content' is required.") + if verification not in _VALID_VERIFICATION: + raise ToolError( + f"verification must be one of {', '.join(_VALID_VERIFICATION)}" + ) + entry = self.store.save( + str(title).strip(), + str(content).strip(), + category=str(category).strip(), + tags=str(tags).strip(), + confidence=float(confidence), + verification=verification, + sources=sources or None, + ) + return ( + f"Saved knowledge entry {entry.id} ({entry.verification}, " + f"{entry.confidence:.0%} confidence): {entry.title}" + ) + + +class GetKnowledgeTool(BaseTool): + """Retrieve a specific knowledge entry by ID.""" + + def __init__(self, store: KnowledgeStore) -> None: + self.store = store + + @property + def name(self) -> str: + return "get_knowledge" + + @property + def description(self) -> str: + return ( + "Retrieve a specific knowledge entry by its ID. Use this to look " + "up something you stored earlier when you only have its ID." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The knowledge entry ID.", + }, + }, + "required": ["id"], + } + + async def execute(self, id: str, **kwargs: Any) -> str: + entry = self.store.get(str(id).strip()) + if entry is None: + return f"No knowledge entry found with ID {id}." + return _format_entry(entry) + + +class ListKnowledgeTool(BaseTool): + """List stored knowledge entries, optionally filtered by category.""" + + def __init__(self, store: KnowledgeStore) -> None: + self.store = store + + @property + def name(self) -> str: + return "list_knowledge" + + @property + def description(self) -> str: + return ( + "List the knowledge entries you have stored, optionally filtered " + "by category. Use this to see what you already know." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "category": { + "type": "string", + "description": "Optional category to filter by.", + }, + "limit": { + "type": "integer", + "description": "Maximum entries to list (default 20).", + }, + }, + } + + async def execute(self, category: str = "", limit: int = 20, **kwargs: Any) -> str: + try: + count = max(1, min(int(limit or 20), 100)) + except (TypeError, ValueError): + count = 20 + entries = self.store.list_all(category=category or None, limit=count) + if not entries: + return "No knowledge entries stored yet." + lines = [f"{len(entries)} knowledge entr(ies):", ""] + for entry in entries: + lines.append(f"- [{entry.id}] {entry.title} ({entry.category or 'uncategorized'}, {entry.verification})") + return "\n".join(lines) + + +class DeleteKnowledgeTool(BaseTool): + """Remove an incorrect or obsolete knowledge entry.""" + + def __init__(self, store: KnowledgeStore) -> None: + self.store = store + + @property + def name(self) -> str: + return "delete_knowledge" + + @property + def description(self) -> str: + return ( + "Delete a knowledge entry you stored when it turns out to be " + "wrong or obsolete. Use with care -- deletion is permanent." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The knowledge entry ID to delete.", + }, + "reason": { + "type": "string", + "description": "Why this entry is being deleted.", + }, + }, + "required": ["id"], + } + + async def execute(self, id: str, reason: str = "", **kwargs: Any) -> str: + entry = self.store.get(str(id).strip()) + if entry is None: + return f"No knowledge entry found with ID {id}." + self.store.delete(entry.id) + note = f" (reason: {reason})" if reason else "" + return f"Deleted knowledge entry {entry.id}: {entry.title}{note}" + + +class UpdateKnowledgeTool(BaseTool): + """Update an existing knowledge entry with newer or more accurate info.""" + + def __init__(self, store: KnowledgeStore) -> None: + self.store = store + + @property + def name(self) -> str: + return "update_knowledge" + + @property + def description(self) -> str: + return ( + "Update an existing knowledge entry when you discover newer or " + "more accurate information. Use this instead of saving a duplicate." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The knowledge entry ID to update.", + }, + "title": {"type": "string", "description": "New title (optional)."}, + "content": {"type": "string", "description": "New content (optional)."}, + "category": {"type": "string", "description": "New category (optional)."}, + "tags": {"type": "string", "description": "New tags (optional)."}, + "confidence": {"type": "number", "description": "New confidence 0.0-1.0 (optional)."}, + "verification": { + "type": "string", + "enum": list(_VALID_VERIFICATION), + "description": "New verification status (optional).", + }, + }, + "required": ["id"], + } + + async def execute(self, id: str, **kwargs: Any) -> str: + entry = self.store.get(str(id).strip()) + if entry is None: + return f"No knowledge entry found with ID {id}." + title = kwargs.get("title") or entry.title + content = kwargs.get("content") or entry.content + category = kwargs.get("category") or entry.category + tags = kwargs.get("tags") or entry.tags + confidence = float(kwargs.get("confidence", entry.confidence)) + verification = kwargs.get("verification") or entry.verification + if verification not in _VALID_VERIFICATION: + raise ToolError( + f"verification must be one of {', '.join(_VALID_VERIFICATION)}" + ) + updated = self.store.save( + title, content, category=category, tags=tags, + confidence=confidence, verification=verification, + knowledge_id=entry.id, + ) + return f"Updated knowledge entry {updated.id}: {updated.title}" + + +class ExtractInformationTool(BaseTool): + """Extract factual information from research material.""" + + def __init__(self, store: Optional[KnowledgeStore] = None) -> None: + self.store = store + + @property + def name(self) -> str: + return "extract_information" + + @property + def description(self) -> str: + return ( + "Extract the factual information from research material you have " + "gathered. Returns a structured list of facts with their sources, " + "ready to be saved to your knowledge database." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "material": { + "type": "string", + "description": "The research material to extract facts from.", + }, + "sources": { + "type": "array", + "items": {"type": "object"}, + "description": "Optional source URLs the material came from.", + }, + "question": { + "type": "string", + "description": "Optional question to focus extraction on.", + }, + }, + "required": ["material"], + } + + async def execute( + self, + material: str, + sources: List[Dict[str, Any]] = None, + question: str = "", + **kwargs: Any, + ) -> str: + material = (material or "").strip() + if not material: + raise ToolError("'material' is required.") + if len(material) > 50_000: + material = material[:50_000] + "\n... [truncated]" + + # Deterministic extraction: split into sentences and keep the ones + # that look like factual statements. A small model benefits from a + # structured output it can act on directly. + import re + + sentences = re.split(r"(?<=[.!?])\s+", material) + facts: List[Dict[str, Any]] = [] + for sentence in sentences: + sentence = sentence.strip() + if not sentence or len(sentence) < 15: + continue + if sentence.startswith(("#", "|", "*", "-", ">", "`")): + continue + facts.append({ + "fact": sentence, + "sources": [s.get("url", "") for s in (sources or []) if s.get("url")], + }) + + if not facts: + return "No factual statements could be extracted from the material." + + lines = [f"Extracted {len(facts)} fact(s):", ""] + for i, fact in enumerate(facts, 1): + srcs = ", ".join(fact["sources"]) or "(no source)" + lines.append(f"{i}. {fact['fact']}") + lines.append(f" Source: {srcs}") + return "\n".join(lines) + + +class SearchMultipleTool(BaseTool): + """Search for a topic from multiple angles.""" + + def __init__(self, web_search=None) -> None: + self._web_search = web_search + + @property + def name(self) -> str: + return "search_multiple" + + @property + def description(self) -> str: + return ( + "Search for a topic from multiple angles at once. Use this when " + "one query is not enough to understand a subject -- it runs " + "several related searches and returns all results together." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "queries": { + "type": "array", + "items": {"type": "string"}, + "description": "List of search queries to run.", + }, + "max_results": { + "type": "integer", + "description": "Maximum results per query (default 3).", + }, + }, + "required": ["queries"], + } + + async def execute(self, queries: List[str], max_results: int = 3, **kwargs: Any) -> str: + if not queries: + raise ToolError("'queries' is required and must be non-empty.") + if self._web_search is None: + raise ToolError("No web search backend is configured.") + try: + count = max(1, min(int(max_results or 3), 10)) + except (TypeError, ValueError): + count = 3 + blocks: List[str] = [] + for query in queries: + try: + result = self._web_search(str(query).strip(), count) + except Exception as exc: + result = f"Search failed for '{query}': {exc}" + blocks.append(f"### {query}\n{result}") + return "\n\n".join(blocks) + + +class GetDateTimeTool(BaseTool): + """Return the current date and time.""" + + @property + def name(self) -> str: + return "get_current_datetime" + + @property + def description(self) -> str: + return ( + "Get the current date and time. Use this when the user asks about " + "the current date, time, or 'today'." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return {"type": "object", "properties": {}} + + async def execute(self, **kwargs: Any) -> str: + import datetime + + now = datetime.datetime.now(datetime.timezone.utc) + return ( + f"Current date and time (UTC): {now.strftime('%Y-%m-%d %H:%M:%S')}\n" + f"ISO 8601: {now.isoformat()}" + ) + + +class CalculateTool(BaseTool): + """Perform deterministic mathematical calculations.""" + + @property + def name(self) -> str: + return "calculate" + + @property + def description(self) -> str: + return ( + "Perform a mathematical calculation and return the result. Use " + "this for arithmetic instead of trying to compute it yourself." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "expression": { + "type": "string", + "description": "A mathematical expression, e.g. '2 + 3 * 4'.", + }, + }, + "required": ["expression"], + } + + async def execute(self, expression: str, **kwargs: Any) -> str: + import ast + import operator as op + + expression = str(expression).strip() + if not expression: + raise ToolError("'expression' is required.") + + _SAFE_OPS = { + ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, + ast.Div: op.truediv, ast.Mod: op.mod, ast.Pow: op.pow, + ast.USub: op.neg, ast.UAdd: op.pos, ast.FloorDiv: op.floordiv, + } + + def _eval(node): + if isinstance(node, ast.Expression): + return _eval(node.body) + if isinstance(node, ast.Constant): + return node.value + if isinstance(node, ast.BinOp): + return _SAFE_OPS[type(node.op)](_eval(node.left), _eval(node.right)) + if isinstance(node, ast.UnaryOp): + return _SAFE_OPS[type(node.op)](_eval(node.operand)) + raise ValueError(f"Unsupported operation: {type(node).__name__}") + + try: + tree = ast.parse(expression, mode="eval") + result = _eval(tree) + if isinstance(result, float) and result.is_integer(): + result = int(result) + return f"{expression} = {result}" + except Exception as exc: + raise ToolError(f"Could not evaluate '{expression}': {exc}") + + +__all__ = [ + "SearchKnowledgeTool", + "SaveKnowledgeTool", + "GetKnowledgeTool", + "ListKnowledgeTool", + "DeleteKnowledgeTool", + "UpdateKnowledgeTool", + "ExtractInformationTool", + "SearchMultipleTool", + "GetDateTimeTool", + "CalculateTool", +]
\ No newline at end of file diff --git a/src/agentux/tools/lsp.py b/src/agentux/tools/lsp.py new file mode 100644 index 0000000..66416ac --- /dev/null +++ b/src/agentux/tools/lsp.py @@ -0,0 +1,699 @@ +"""Language Server Protocol (LSP) integration. + +Provides semantic code navigation tools (go to definition, find references, +and get symbol info) by talking to a language server over stdio. + +The agent uses this instead of `grep` when it needs to know what a symbol +*means* rather than where its name appears. A grep match can be a comment, +a string, or a shadowed variable; an LSP response is the compiler's own +understanding of the code. +""" + +from __future__ import annotations + +import asyncio +import json +import os +import re +import shutil +import subprocess +import threading +from typing import Any, Dict, List, Optional + +from ..errors import ToolError +from .base import BaseTool + + +# --------------------------------------------------------------------------- +# JSON-RPC 2.0 over stdio (LSP framing: Content-Length headers) +# --------------------------------------------------------------------------- + +class _LSPClient: + """A minimal synchronous JSON-RPC 2.0 client for an LSP server process. + + The reader runs in a dedicated daemon thread doing blocking ``os.read`` + on the server's stdout pipe; the writer is the caller's thread. Responses + are delivered back through ``threading.Event`` objects so ``request()`` + can block synchronously. This is the same pattern as the proven sync test + and avoids the fragility of ``loop.connect_read_pipe`` on CPython 3.14, + where the pipe transport can silently stop delivering data. + + The async tools wrap calls to this client with ``asyncio.to_thread``. + """ + + def __init__(self, command: List[str], root: str) -> None: + self.command = command + self.root = root + self._proc: Optional[subprocess.Popen] = None + self._req_id = 0 + self._buf = b"" + self._responses: Dict[int, Tuple[threading.Event, Dict[str, Any]]] = {} + self._reader_thread: Optional[threading.Thread] = None + self._closed = False + + def start(self) -> None: + if self._proc is not None: + return + env = { + k: v + for k, v in os.environ.items() + if not k.startswith("AGENTUX_") + } + self._proc = subprocess.Popen( + self.command, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + bufsize=0, + env=env, + ) + self._reader_thread = threading.Thread( + target=self._read_loop, daemon=True + ) + self._reader_thread.start() + + def _read_loop(self) -> None: + assert self._proc is not None and self._proc.stdout is not None + fd = self._proc.stdout.fileno() + try: + while True: + chunk = os.read(fd, 65536) + if not chunk: + break + self._buf += chunk + # Parse as many complete LSP messages as are available. + while True: + msg, self._buf = self._extract_message(self._buf) + if msg is None: + break + try: + resp = json.loads(msg) + except Exception: + continue + if "id" in resp and resp["id"] is not None: + entry = self._responses.get(resp["id"]) + if entry is not None: + entry[1]["resp"] = resp + entry[0].set() + except OSError: + pass + + @staticmethod + def _extract_message(buf: bytes) -> tuple: + """Return (message_bytes, remaining_buf) or (None, buf).""" + header_end = buf.find(b"\r\n\r\n") + if header_end < 0: + return None, buf + header = buf[:header_end].decode("utf-8", "replace") + length = None + for line in header.split("\r\n"): + if line.lower().startswith("content-length:"): + try: + length = int(line.split(":", 1)[1].strip()) + except ValueError: + return None, buf + if length is None: + return None, buf[header_end + 4:] + body_start = header_end + 4 + if len(buf) < body_start + length: + return None, buf + return buf[body_start:body_start + length], buf[body_start + length:] + + def _write(self, body: bytes) -> None: + assert self._proc is not None and self._proc.stdin is not None + header = f"Content-Length: {len(body)}\r\n\r\n".encode("utf-8") + self._proc.stdin.write(header + body) + self._proc.stdin.flush() + + def _send(self, method: str, params: Any, expect_response: bool = True) -> Any: + self.start() + request_id = None + if expect_response: + self._req_id += 1 + request_id = self._req_id + # Notifications must OMIT the id field entirely. Sending + # ``"id": null`` is rejected by pyright ("Received message which is + # neither a response nor a notification"), which silently drops the + # handshake and leaves later requests hanging. + if expect_response: + body = json.dumps({ + "jsonrpc": "2.0", + "id": request_id, + "method": method, + "params": params or {}, + }).encode("utf-8") + else: + body = json.dumps({ + "jsonrpc": "2.0", + "method": method, + "params": params or {}, + }).encode("utf-8") + self._write(body) + + if not expect_response: + return None + + event = threading.Event() + holder: Dict[str, Any] = {} + self._responses[request_id] = (event, holder) + event.wait(timeout=30.0) + self._responses.pop(request_id, None) + if not event.is_set(): + raise ToolError(f"LSP request '{method}' timed out") + resp = holder.get("resp", {}) + if resp.get("error"): + raise ToolError(f"LSP error ({resp['error'].get('code')}): {resp['error'].get('message')}") + return resp.get("result") + + def notify(self, method: str, params: Any) -> None: + self._send(method, params, expect_response=False) + + def request(self, method: str, params: Any) -> Any: + return self._send(method, params, expect_response=True) + + def did_open(self, path: str) -> None: + """Notify the server that a document is open. + + Several servers (pyright, rust-analyzer) will not answer + ``textDocument/documentSymbol`` or ``textDocument/definition`` for a + file they have not been told is open. We send ``didOpen`` once per + path and ignore failures -- a server that does not care simply + ignores the notification. + """ + if not os.path.isfile(path): + return + try: + with open(path, "r", encoding="utf-8", errors="replace") as f: + text = f.read() + except Exception: + return + try: + self._write(json.dumps({ + "jsonrpc": "2.0", + "method": "textDocument/didOpen", + "params": { + "textDocument": { + "uri": "file://" + path, + "languageId": _language_id_for(path), + "version": 1, + "text": text, + }, + }, + }).encode("utf-8")) + except Exception: + pass + + def close(self) -> None: + if self._closed: + return + self._closed = True + if self._proc is not None: + try: + self._send("shutdown", None) + except Exception: + pass + try: + self.notify("exit", {}) + except Exception: + pass + try: + self._proc.wait(timeout=2) + except Exception: + try: + self._proc.kill() + except Exception: + pass + try: + self._proc.wait(timeout=2) + except Exception: + try: + self._proc.kill() + except Exception: + pass + if self._reader_thread is not None and self._reader_thread.is_alive(): + self._reader_thread.join(timeout=1) + + +# --------------------------------------------------------------------------- +# Server registry +# --------------------------------------------------------------------------- + +#: Map of file extension -> (language id, command, root marker files) +LSP_SERVERS: Dict[str, Dict[str, Any]] = { + ".py": { + "language": "python", + "command": ["pyright-langserver", "--stdio"], + "fallback": [["pyls"], ["pylsp"]], + "root_markers": ["pyproject.toml", "setup.py", "requirements.txt", "setup.cfg"], + }, + ".go": { + "language": "go", + "command": ["gopls", "serve"], + "fallback": [], + "root_markers": ["go.mod", "go.sum"], + }, + ".ts": { + "language": "typescript", + "command": ["typescript-language-server", "--stdio"], + "fallback": [], + "root_markers": ["tsconfig.json", "package.json"], + }, + ".tsx": { + "language": "typescript", + "command": ["typescript-language-server", "--stdio"], + "fallback": [], + "root_markers": ["tsconfig.json", "package.json"], + }, + ".js": { + "language": "javascript", + "command": ["typescript-language-server", "--stdio"], + "fallback": [], + "root_markers": ["package.json"], + }, + ".jsx": { + "language": "javascript", + "command": ["typescript-language-server", "--stdio"], + "fallback": [], + "root_markers": ["package.json"], + }, + ".rs": { + "language": "rust", + "command": ["rust-analyzer"], + "fallback": [], + "root_markers": ["Cargo.toml"], + }, + ".java": { + "language": "java", + "command": ["jdtls"], + "fallback": [], + "root_markers": ["pom.xml", "build.gradle"], + }, + ".c": { + "language": "c", + "command": ["clangd"], + "fallback": [], + "root_markers": ["compile_commands.json", "Makefile", "CMakeLists.txt"], + }, + ".cpp": { + "language": "cpp", + "command": ["clangd"], + "fallback": [], + "root_markers": ["compile_commands.json", "Makefile", "CMakeLists.txt"], + }, +} + + +def _language_id_for(path: str) -> str: + """Return the LSP ``languageId`` for a file based on its extension.""" + ext = os.path.splitext(path)[1].lower() + spec = LSP_SERVERS.get(ext) + if spec is None: + return "text" + return spec.get("language", "text") + + +def _find_server_root(root: str, markers: List[str]) -> str: + """Walk up from `root` looking for one of the marker files.""" + current = root + for _ in range(10): + for marker in markers: + if os.path.exists(os.path.join(current, marker)): + return current + parent = os.path.dirname(current) + if parent == current: + break + current = parent + return root + + +def _resolve_binary(command: List[str]) -> Optional[List[str]]: + """Return the command if the binary is available, else None.""" + if not command: + return None + if shutil.which(command[0]) is None: + return None + return command + + +def _try_resolve(spec: Dict[str, Any]) -> Optional[List[str]]: + """Try the primary command, then each fallback, returning the first that exists.""" + primary = _resolve_binary(spec.get("command") or []) + if primary is not None: + return primary + for fallback in spec.get("fallback", []) or []: + if isinstance(fallback, list): + resolved = _resolve_binary(fallback) + else: + resolved = _resolve_binary([fallback, "--stdio"]) + if resolved is not None: + return resolved + return None + + +class LSPManager: + """Manages LSP server processes and routes requests to them.""" + + def __init__(self, root: str) -> None: + self.root = os.path.realpath(root) + self._clients: Dict[str, _LSPClient] = {} + + def _language_for(self, path: str) -> Optional[str]: + ext = os.path.splitext(path)[1].lower() + spec = LSP_SERVERS.get(ext) + if spec is None: + return None + return spec["language"] + + def _spec_for(self, path: str) -> Optional[Dict[str, Any]]: + ext = os.path.splitext(path)[1].lower() + return LSP_SERVERS.get(ext) + + async def _get_or_start(self, path: str) -> _LSPClient: + ext = os.path.splitext(path)[1].lower() + spec = LSP_SERVERS.get(ext) + if spec is None: + raise ToolError(f"No LSP server configured for extension '{ext}'") + + lang = spec["language"] + if lang in self._clients: + return self._clients[lang] + + command = _try_resolve(spec) + if command is None: + raise ToolError( + f"No LSP server binary found for {ext} ({lang}). " + f"Install one of: {', '.join(spec['command'] + spec.get('fallback', []))}" + ) + + server_root = _find_server_root(self.root, spec.get("root_markers", [])) + client = _LSPClient(command, server_root) + await asyncio.to_thread(client.start) + + # Initialize + await asyncio.to_thread(client.request, "initialize", { + "processId": os.getpid(), + "rootUri": "file://" + server_root, + "capabilities": { + "textDocument": { + "completion": {"completionItem": {"snippetSupport": True}}, + }, + }, + }) + await asyncio.to_thread(client.notify, "initialized", {}) + + self._clients[lang] = client + return client + + async def request(self, path: str, method: str, params: Any) -> Any: + client = await self._get_or_start(path) + return await asyncio.to_thread(client.request, method, params) + + async def close_all(self) -> None: + for client in list(self._clients.values()): + await asyncio.to_thread(client.close) + self._clients.clear() + + +# --------------------------------------------------------------------------- +# Tools +# --------------------------------------------------------------------------- + +def _location_to_str(loc: Dict[str, Any], root: str) -> str: + """Convert an LSP Location to a human-readable path:line:col.""" + uri = loc.get("uri", "") + path = uri.replace("file://", "") + if path.startswith(root): + path = path[len(root):].lstrip("/") + rng = loc.get("range", {}) + start = rng.get("start", {}) + line = start.get("line", 0) + 1 + char = start.get("character", 0) + 1 + return f"{path}:{line}:{char}" + + +class GoToDefinitionTool(BaseTool): + """Jump to the definition of a symbol using a language server.""" + + def __init__(self, root: Optional[str] = None) -> None: + self.root = os.path.realpath(root or os.getcwd()) + self._manager: Optional[LSPManager] = None + + @property + def name(self) -> str: + return "go_to_definition" + + @property + def description(self) -> str: + return ( + "Find the definition of a symbol at a given position using a " + "language server. Returns the file, line, and column where the " + "symbol is defined. Much more accurate than searching for the name." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Path to the source file containing the symbol.", + }, + "line": { + "type": "integer", + "description": "1-indexed line number of the symbol.", + }, + "character": { + "type": "integer", + "description": "1-indexed character offset of the symbol.", + }, + }, + "required": ["path", "line", "character"], + } + + def _get_manager(self) -> LSPManager: + if self._manager is None: + self._manager = LSPManager(self.root) + return self._manager + + async def execute(self, path: str, line: int, character: int) -> str: + full_path = path if os.path.isabs(path) else os.path.join(self.root, path) + full_path = os.path.realpath(full_path) + if not full_path.startswith(self.root): + raise ToolError(f"Path escapes workspace directory: {path}") + if not os.path.isfile(full_path): + raise ToolError(f"File not found: {path}") + + manager = self._get_manager() + client = await manager._get_or_start(full_path) + await asyncio.to_thread(client.did_open, full_path) + try: + result = await asyncio.to_thread( + client.request, + "textDocument/definition", + { + "textDocument": {"uri": "file://" + full_path}, + "position": {"line": line - 1, "character": character - 1}, + }, + ) + except ToolError: + raise + except Exception as exc: + raise ToolError(f"LSP definition failed: {exc}") + + if not result: + return f"No definition found for symbol at {path}:{line}:{character}." + + if isinstance(result, list): + if not result: + return f"No definition found for symbol at {path}:{line}:{character}." + locations = [_location_to_str(loc, self.root) for loc in result] + return "Definitions:\n" + "\n".join(locations) + + if isinstance(result, dict) and "uri" in result: + return "Definition: " + _location_to_str(result, self.root) + + return f"Definition (raw): {json.dumps(result)}" + + +class FindReferencesTool(BaseTool): + """Find all references to a symbol using a language server.""" + + def __init__(self, root: Optional[str] = None) -> None: + self.root = os.path.realpath(root or os.getcwd()) + self._manager: Optional[LSPManager] = None + + @property + def name(self) -> str: + return "find_references" + + @property + def description(self) -> str: + return ( + "Find all references to a symbol at a given position using a " + "language server. Returns a list of locations where the symbol " + "is used. Useful before renaming or refactoring." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Path to the source file containing the symbol.", + }, + "line": { + "type": "integer", + "description": "1-indexed line number of the symbol.", + }, + "character": { + "type": "integer", + "description": "1-indexed character offset of the symbol.", + }, + }, + "required": ["path", "line", "character"], + } + + def _get_manager(self) -> LSPManager: + if self._manager is None: + self._manager = LSPManager(self.root) + return self._manager + + async def execute(self, path: str, line: int, character: int) -> str: + full_path = path if os.path.isabs(path) else os.path.join(self.root, path) + full_path = os.path.realpath(full_path) + if not full_path.startswith(self.root): + raise ToolError(f"Path escapes workspace directory: {path}") + if not os.path.isfile(full_path): + raise ToolError(f"File not found: {path}") + + manager = self._get_manager() + client = await manager._get_or_start(full_path) + await asyncio.to_thread(client.did_open, full_path) + try: + result = await asyncio.to_thread( + client.request, + "textDocument/references", + { + "textDocument": {"uri": "file://" + full_path}, + "position": {"line": line - 1, "character": character - 1}, + "context": {"includeDeclaration": True}, + }, + ) + except ToolError: + raise + except Exception as exc: + raise ToolError(f"LSP references failed: {exc}") + + if not result: + return f"No references found for symbol at {path}:{line}:{character}." + + locations = [_location_to_str(loc, self.root) for loc in result] + header = f"Found {len(locations)} reference(s) for symbol at {path}:{line}:{character}:" + return header + "\n" + "\n".join(locations) + + +class GetSymbolInfoTool(BaseTool): + """Get the document symbols (outline) of a file using a language server.""" + + def __init__(self, root: Optional[str] = None) -> None: + self.root = os.path.realpath(root or os.getcwd()) + self._manager: Optional[LSPManager] = None + + @property + def name(self) -> str: + return "get_symbol_info" + + @property + def description(self) -> str: + return ( + "Get the list of symbols (functions, classes, variables, etc.) " + "in a file using a language server. Returns a structured outline " + "with names, kinds, and line numbers." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Path to the source file to inspect.", + }, + }, + "required": ["path"], + } + + def _get_manager(self) -> LSPManager: + if self._manager is None: + self._manager = LSPManager(self.root) + return self._manager + + async def execute(self, path: str) -> str: + full_path = path if os.path.isabs(path) else os.path.join(self.root, path) + full_path = os.path.realpath(full_path) + if not full_path.startswith(self.root): + raise ToolError(f"Path escapes workspace directory: {path}") + if not os.path.isfile(full_path): + raise ToolError(f"File not found: {path}") + + manager = self._get_manager() + client = await manager._get_or_start(full_path) + await asyncio.to_thread(client.did_open, full_path) + try: + result = await asyncio.to_thread( + client.request, + "textDocument/documentSymbol", + {"textDocument": {"uri": "file://" + full_path}}, + ) + except ToolError: + raise + except Exception as exc: + raise ToolError(f"LSP documentSymbol failed: {exc}") + + if not result: + return f"No symbols found in {path}." + + # Handle both flat DocumentSymbol[] and flat SymbolInformation[] + kind_names = { + 1: "File", 2: "Module", 3: "Namespace", 4: "Package", 5: "Class", + 6: "Method", 7: "Property", 8: "Field", 9: "Constructor", 10: "Enum", + 11: "Interface", 12: "Function", 13: "Variable", 14: "Constant", + 15: "String", 16: "Number", 17: "Boolean", 18: "Array", 19: "Object", + 20: "Key", 21: "Null", 22: "EnumMember", 23: "Struct", 24: "Event", + 25: "Operator", 26: "TypeParameter", + } + + lines = [f"Symbols in {path}:"] + if isinstance(result, list): + for sym in result: + if "location" in sym: + # DocumentSymbol (has children) + name = sym.get("name", "?") + kind = kind_names.get(sym.get("kind", 0), "Unknown") + loc = sym["location"]["range"]["start"] + lines.append(f" L{loc['line'] + 1:<5} [{kind:<12}] {name}") + for child in sym.get("children", []) or []: + cname = child.get("name", "?") + ckind = kind_names.get(child.get("kind", 0), "Unknown") + cloc = child["location"]["range"]["start"] + lines.append(f" L{cloc['line'] + 1:<5} [{ckind:<12}] {cname}") + else: + # SymbolInformation (flat) + name = sym.get("name", "?") + kind = kind_names.get(sym.get("kind", 0), "Unknown") + loc = sym.get("location", {}).get("range", {}).get("start", {}) + lines.append(f" L{loc.get('line', 0) + 1:<5} [{kind:<12}] {name}") + + return "\n".join(lines) + + +__all__ = [ + "GoToDefinitionTool", + "FindReferencesTool", + "GetSymbolInfoTool", + "LSPManager", +]
\ No newline at end of file diff --git a/src/agentux/tools/mcp_tool.py b/src/agentux/tools/mcp_tool.py new file mode 100644 index 0000000..03f8951 --- /dev/null +++ b/src/agentux/tools/mcp_tool.py @@ -0,0 +1,196 @@ +"""Exposing MCP server tools to the agent. + +Each remote tool becomes an ordinary :class:`~agentux.tools.base.BaseTool`, so +the agent loop cannot tell the difference between a tool Agentux implements and +one that lives in another process. That is the point: adding MCP changes what +the model can call without changing how the loop calls it. + +Remote tools are namespaced ``mcp__<server>__<tool>``. Namespacing is not +cosmetic -- a server is free to publish a tool called ``shell`` or ``write``, +and without a prefix it would silently shadow a built-in one. +""" + +from __future__ import annotations + +import asyncio +from typing import Any, Dict, List, Optional, Tuple + +from ..errors import MCPError +from ..mcp import DEFAULT_TIMEOUT, MCPServer, render_tool_result +from ..mcp_config import MCPServerConfig, load_server_configs +from ..models import ToolDefinition +from .base import BaseTool + +#: Separator between the server name and the tool name. +SEPARATOR = "__" + + +def qualify(server: str, tool: str) -> str: + """The name the model uses to call a remote tool.""" + return f"mcp{SEPARATOR}{server}{SEPARATOR}{tool}" + + +def split(name: str) -> Optional[Tuple[str, str]]: + """Inverse of :func:`qualify`, or ``None`` if the name is not a remote tool.""" + if not name.startswith(f"mcp{SEPARATOR}"): + return None + remainder = name[len(f"mcp{SEPARATOR}"):] + server, separator, tool = remainder.partition(SEPARATOR) + if not separator or not server or not tool: + return None + return server, tool + + +class MCPTool(BaseTool): + """One tool provided by an MCP server.""" + + def __init__( + self, + server: MCPServer, + remote_name: str, + description: str, + schema: Dict[str, Any], + ) -> None: + self.server = server + self.remote_name = remote_name + self._description = description or "No description provided by the server." + self._schema = schema or {"type": "object", "properties": {}} + + @property + def name(self) -> str: + return qualify(self.server.name, self.remote_name) + + @property + def description(self) -> str: + return f"[MCP server {self.server.name!r}] {self._description}" + + @property + def parameters(self) -> Dict[str, Any]: + # Servers send JSON Schema; providers want the same shape. Only the + # fields that vary are rewritten. + schema = dict(self._schema) + schema.setdefault("type", "object") + schema.setdefault("properties", {}) + return schema + + def to_definition(self) -> ToolDefinition: + return ToolDefinition( + name=self.name, description=self.description, parameters=self.parameters + ) + + async def execute(self, **kwargs: Any) -> str: + result = await self.server.call_tool(self.remote_name, kwargs) + + text = render_tool_result(result) + if result.get("isError"): + # Surfaced as text, not raised: the spec is explicit that these are + # the errors a model can act on, and aborting the run would deny it + # the chance to retry with better arguments. + return f"ERROR (from MCP server {self.server.name!r}): {text}" + return text + + +class MCPToolManager: + """Owns the running MCP servers and the tools they provide.""" + + def __init__( + self, + working_dir: str, + timeout: float = DEFAULT_TIMEOUT, + on_log: Optional[Any] = None, + ) -> None: + self.working_dir = working_dir + self.timeout = timeout + self.on_log = on_log + self.servers: Dict[str, MCPServer] = {} + self.tools: List[MCPTool] = [] + self.warnings: List[str] = [] + self.configs: List[MCPServerConfig] = [] + #: (server name, tool name, reason) for each server that failed to load. + self.failed: List[Tuple[str, str]] = [] + + def _log(self, message: str) -> None: + if self.on_log: + try: + self.on_log(message) + except Exception: + pass + + async def load(self, start: bool = True) -> List[MCPTool]: + """Load configured servers and their tools. + + A server that fails to start is recorded and skipped. One broken server + must not take down the session -- Agentux's own tools still work. + + Returns a snapshot, not the live list: :meth:`close` clears the + internal one, and a caller that kept the result should not find it + emptied out from under it. + """ + self.configs, self.warnings = load_server_configs(self.working_dir) + + for config in self.configs: + server = MCPServer(config, timeout=self.timeout, on_log=self._log) + self.servers[config.name] = server + + if not start: + continue + + try: + await server.start() + remote_tools = await server.list_tools() + except (MCPError, asyncio.TimeoutError, OSError) as exc: + self.failed.append((config.name, str(exc))) + self._log(f"skipping MCP server {config.name!r}: {exc}") + await server.close() + continue + + for entry in remote_tools: + remote_name = entry.get("name") + if not remote_name: + continue + self.tools.append( + MCPTool( + server=server, + remote_name=str(remote_name), + description=str(entry.get("description") or ""), + schema=entry.get("inputSchema") or {}, + ) + ) + + self._log( + f"MCP server {config.name!r} ready: {len(remote_tools)} tool(s)" + ) + + return list(self.tools) + + def describe(self) -> List[str]: + """One line per configured server, for ``--list-tools`` and ``/mcp``.""" + lines: List[str] = [] + for name, server in self.servers.items(): + info = server.server_info or {} + label = info.get("name") or config_name(server.config) + version = info.get("version") + detail = f"{label}" + (f" {version}" if version else "") + if name in {f for f, _ in self.failed}: + reason = next(r for f, r in self.failed if f == name) + lines.append(f"{name}: unavailable — {reason}") + else: + count = sum(1 for t in self.tools if t.server.name == name) + lines.append(f"{name}: {detail} — {count} tool(s)") + return lines + + async def close(self) -> None: + for server in self.servers.values(): + try: + await server.close() + except Exception: + pass + self.servers.clear() + self.tools.clear() + + +def config_name(config: MCPServerConfig) -> str: + return f"{config.command} {' '.join(config.args)}".strip() + + +__all__ = ["MCPTool", "MCPToolManager", "qualify", "split", "SEPARATOR"] diff --git a/src/agentux/tools/memory_tool.py b/src/agentux/tools/memory_tool.py new file mode 100644 index 0000000..68baf96 --- /dev/null +++ b/src/agentux/tools/memory_tool.py @@ -0,0 +1,153 @@ +"""Memory tools: the model's own read and write access to the store. + +``memory_save`` is how the model records something it learned. ``memory_search`` +is how it looks for something it might already know. Both are deliberately +plain: the model hands over text, the store does the ranking, and the result +comes back as text the model can read and act on. +""" + +from __future__ import annotations + +from typing import Any, Dict + +from ..errors import ToolError +from ..memory import ( + SCOPE_GLOBAL, + SCOPE_PROJECT, + VALID_SCOPES, + MemoryStore, +) +from .base import BaseTool + + +class MemorySaveTool(BaseTool): + """Write one thing the model learned into the store.""" + + def __init__(self, store: MemoryStore, project: str = "") -> None: + self.store = store + self.project = project + + @property + def name(self) -> str: + return "memory_save" + + @property + def description(self) -> str: + return ( + "Save something you learned so you can recall it later. Use it for " + "anything non-obvious: a gotcha, a fact about this project, a " + "convention, a command that works, a URL, a correction the user " + "gave you. One fact per call. Be specific enough that the fact is " + "useful months from now." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "body": { + "type": "string", + "description": "The fact to remember, in one or two sentences.", + }, + "scope": { + "type": "string", + "enum": list(VALID_SCOPES), + "description": ( + "'project' (default) keeps it visible only in this " + "workspace. 'global' makes it visible everywhere — use " + "that only for lessons that are genuinely general." + ), + }, + "tags": { + "type": "string", + "description": "Optional comma-separated keywords, e.g. 'go,channels'.", + }, + }, + "required": ["body"], + } + + async def execute( + self, + body: str, + scope: str = SCOPE_PROJECT, + tags: str = "", + **kwargs: Any, + ) -> str: + if body is None or not str(body).strip(): + raise ToolError("'body' is required and must be non-empty.") + if scope not in VALID_SCOPES: + raise ToolError( + f"Scope must be one of {', '.join(VALID_SCOPES)}, got {scope!r}." + ) + if scope == SCOPE_GLOBAL: + project = None + else: + project = self.project or None + + memory = self.store.save( + str(body), scope=scope, project=project, source="model", tags=str(tags) + ) + preview = memory.body if len(memory.body) <= 80 else memory.body[:80] + "..." + return f"Saved memory {memory.id} ({memory.scope}): {preview}" + + +class MemorySearchTool(BaseTool): + """Look for something the model might already know.""" + + def __init__(self, store: MemoryStore, project: str = "") -> None: + self.store = store + self.project = project + + @property + def name(self) -> str: + return "memory_search" + + @property + def description(self) -> str: + return ( + "Search what you have learned before. Use this before answering " + "something you might already know, and whenever a question mentions " + "a project, a command, or a technology you have seen before." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": ( + "Keywords describing what you are looking for. A few " + "specific words work better than a whole sentence." + ), + }, + "limit": { + "type": "integer", + "description": "Maximum memories to return. Defaults to 5.", + }, + }, + "required": ["query"], + } + + async def execute(self, query: str, limit: int = 5, **kwargs: Any) -> str: + if not query or not str(query).strip(): + return "No memories matched." + try: + count = max(1, min(int(limit or 5), 20)) + except (TypeError, ValueError): + count = 5 + + hits = self.store.search(str(query), project=self.project or None, limit=count) + if not hits: + return "No memories matched." + + lines = [f"{len(hits)} remembered:"] + for index, (memory, _score) in enumerate(hits, 1): + scope = memory.scope if memory.scope == SCOPE_GLOBAL else "project" + lines.append(f"{index}. [{scope}] {memory.body}") + return "\n".join(lines) + + +__all__ = ["MemorySaveTool", "MemorySearchTool"] diff --git a/src/agentux/tools/repomap_tool.py b/src/agentux/tools/repomap_tool.py new file mode 100644 index 0000000..c265c51 --- /dev/null +++ b/src/agentux/tools/repomap_tool.py @@ -0,0 +1,49 @@ +"""Repomap tool for Agentux.""" + +from __future__ import annotations + +from typing import Any, Dict +from ..models import ToolDefinition +from ..repomap import RepoMap +from .base import BaseTool + + +class RepomapTool(BaseTool): + """Tool allowing the agent to inspect the codebase symbol outline.""" + + def __init__(self, root: str) -> None: + self.repomap = RepoMap(root) + + @property + def name(self) -> str: + return "repomap" + + @property + def description(self) -> str: + return ( + "Generate a compact, token-efficient repository symbol map. " + "Shows all classes, structs, functions, methods, and line numbers " + "across the codebase without reading entire files. " + "Optionally filter by symbol query or path keyword." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Optional symbol name, keyword, or path to filter the map.", + }, + "max_tokens": { + "type": "integer", + "description": "Maximum token budget for the map (default 600).", + }, + }, + } + + async def execute(self, **kwargs: Any) -> str: + query = kwargs.get("query") + max_tokens = int(kwargs.get("max_tokens", 600)) + return self.repomap.generate_map(max_tokens=max_tokens, query=query) diff --git a/src/agentux/tools/search.py b/src/agentux/tools/search.py new file mode 100644 index 0000000..9344ac3 --- /dev/null +++ b/src/agentux/tools/search.py @@ -0,0 +1,283 @@ +"""Content search across the workspace. + +Regex-based, the way an agent actually needs to find things: a symbol's +definition and its call sites, a string literal, an error message. Every result +carries enough context to act on without a second read. + +Results are capped and files are skipped by extension and directory, because an +unbounded search is how an agent fills its own context window with noise. +""" + +from __future__ import annotations + +import os +import re + +from ..errors import ToolError +from .base import BaseTool + +#: Directories that are never worth grepping. +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", + ".eggs", "*.egg-info", +} + +#: Binary and generated formats with nothing useful in them as text. +SKIP_SUFFIXES = { + ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".webp", ".svgz", + ".pdf", ".zip", ".gz", ".bz2", ".xz", ".tar", ".7z", ".rar", + ".so", ".dylib", ".dll", ".exe", ".bin", ".o", ".a", ".class", ".jar", + ".pyc", ".pyo", ".wasm", ".woff", ".woff2", ".ttf", ".eot", ".otf", + ".mp3", ".mp4", ".mov", ".avi", ".wav", ".flac", ".ogg", + ".db", ".sqlite", ".sqlite3", ".lock", +} + +#: Files larger than this are reported but not searched: a 4 MB minified bundle +#: matches everything and tells the model nothing. +MAX_FILE_BYTES = 1_000_000 + +#: Caps that keep a search result readable and the context window survivable. +MAX_MATCHES = 200 +MAX_FILES = 2_000 +MAX_LINE_CHARS = 400 +MAX_FILE_LIST = 100 + + +class SearchTool(BaseTool): + """Find text in files across the workspace.""" + + def __init__(self, root: Optional[str] = None) -> None: + self.root = os.path.realpath(root or os.getcwd()) + + @property + def name(self) -> str: + return "search" + + @property + def description(self) -> str: + return ( + "Search file contents with a regular expression. Returns matching " + "lines with file:line references and surrounding context. Use this " + "to find where something is defined or used before reading whole " + "files. Also supports listing file paths by glob pattern when " + "'content_pattern' is omitted." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "content_pattern": { + "type": "string", + "description": ( + "Regular expression to search for. Omit to list files " + "whose paths match 'file_pattern' instead." + ), + }, + "path": { + "type": "string", + "description": "File or directory to search under. Defaults to the project root.", + }, + "file_pattern": { + "type": "string", + "description": ( + "Glob restricting which files are searched, e.g. '*.py' " + "or 'src/**/*.ts'. Omit to search all text files." + ), + }, + "context_lines": { + "type": "integer", + "description": "Lines of context to show around each match. Defaults to 1.", + }, + "ignore_case": { + "type": "boolean", + "description": "Case-insensitive match. Defaults to false.", + }, + "max_matches": { + "type": "integer", + "description": "Maximum matches to return. Defaults to 200.", + }, + }, + "required": [], + } + + # ------------------------------------------------------------------ + # Path handling + # ------------------------------------------------------------------ + 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 resolved.startswith(self.root + os.sep) and resolved != self.root: + raise ToolError(f"Path {path!r} is outside the workspace root {self.root}.") + return resolved + + def _walk(self, base: str) -> Iterator[str]: + """Yield searchable files under ``base``, pruning noise directories.""" + if os.path.isfile(base): + yield base + return + + checked = 0 + for dirpath, dirnames, filenames in os.walk(base): + dirnames[:] = sorted( + d for d in dirnames + if d not in SKIP_DIRS and not d.endswith(".egg-info") + ) + for filename in sorted(filenames): + if os.path.splitext(filename)[1].lower() in SKIP_SUFFIXES: + continue + full = os.path.join(dirpath, filename) + try: + if os.path.getsize(full) > MAX_FILE_BYTES: + continue + except OSError: + continue + yield full + checked += 1 + if checked >= MAX_FILES: + return + + def _matches_glob(self, path: str, pattern: Optional[str]) -> bool: + if not pattern: + return True + try: + from fnmatch import fnmatch + + if fnmatch(path, pattern): + return True + # A bare '*.py' should also match nested paths. + return fnmatch(os.path.basename(path), pattern) + except Exception: + return True + + # ------------------------------------------------------------------ + # Actions + # ------------------------------------------------------------------ + def _list_files(self, base: str, file_pattern: Optional[str]) -> str: + matches = [ + os.path.relpath(p, self.root) + for p in self._walk(base) + if self._matches_glob(p, file_pattern) + ] + if not matches: + scope = os.path.relpath(base, self.root) or "." + return f"No files matching {file_pattern!r} under {scope}." + + shown = matches[:MAX_FILE_LIST] + lines = "\n".join(shown) + footer = "" + if len(matches) > MAX_FILE_LIST: + footer = f"\n... {len(matches) - MAX_FILE_LIST} more (narrow 'file_pattern')" + return f"{len(matches)} file(s):\n{lines}{footer}" + + def _grep( + self, + base: str, + pattern: str, + file_pattern: Optional[str], + context_lines: int, + ignore_case: bool, + max_matches: int, + ) -> str: + flags = re.IGNORECASE if ignore_case else 0 + try: + regex = re.compile(pattern, flags) + except re.error as exc: + raise ToolError( + f"Invalid regular expression {pattern!r}: {exc}" + ) from exc + + span = max(0, min(int(context_lines or 0), 5)) + results: List[str] = [] + matched_files: List[str] = [] + truncated_at: Optional[str] = None + total = 0 + + for full in self._walk(base): + if not self._matches_glob(full, file_pattern): + continue + try: + with open(full, encoding="utf-8", errors="replace") as handle: + lines = handle.readlines() + except (OSError, PermissionError): + continue + + rel = os.path.relpath(full, self.root) + hits = [i for i, line in enumerate(lines) if regex.search(line)] + if not hits: + continue + matched_files.append(rel) + total += len(hits) + + # Collapse a run of nearby hits into one block instead of repeating + # the same context lines for every match. + shown_lines: set = set() + for index in hits: + if len(results) >= max_matches: + truncated_at = rel + break + start, end = max(0, index - span), min(len(lines), index + span + 1) + if any(j in shown_lines for j in range(start, end)): + continue + shown_lines.update(range(start, end)) + if start > 0: + results.append(" ...") + for j in range(start, end): + marker = ">" if j == index else " " + text = lines[j].rstrip("\n") + if len(text) > MAX_LINE_CHARS: + text = text[:MAX_LINE_CHARS] + "..." + results.append(f"{marker} {rel}:{j + 1}: {text}") + if end < len(lines): + results.append(" ...") + if truncated_at: + break + + if not results: + scope = os.path.relpath(base, self.root) or "." + where = f" under {scope}" if scope != "." else "" + suffix = f" matching {file_pattern!r}" if file_pattern else "" + return f"No matches for {pattern!r}{where}{suffix}." + + header = f"{total} match(es) for {pattern!r} in {len(matched_files)} file(s)" + footer = "" + if truncated_at: + footer = ( + f"\n\n... stopped at {max_matches} matches (in {truncated_at}). " + "Narrow the pattern or the file_pattern to see the rest." + ) + elif total > max_matches: + footer = "\n\n... output capped." + return f"{header}\n\n" + "\n".join(results) + footer + + async def execute( + self, + content_pattern: Optional[str] = None, + path: Optional[str] = None, + file_pattern: Optional[str] = None, + context_lines: int = 1, + ignore_case: bool = False, + max_matches: int = MAX_MATCHES, + **kwargs: Any, + ) -> str: + base = self._base(path) + + if not content_pattern: + return self._list_files(base, file_pattern) + + return self._grep( + base=base, + pattern=content_pattern, + file_pattern=file_pattern, + context_lines=context_lines, + ignore_case=bool(ignore_case), + max_matches=max(1, min(int(max_matches or MAX_MATCHES), 500)), + ) + + +__all__ = ["SearchTool"] diff --git a/src/agentux/tools/symbols.py b/src/agentux/tools/symbols.py new file mode 100644 index 0000000..19c269a --- /dev/null +++ b/src/agentux/tools/symbols.py @@ -0,0 +1,130 @@ +"""High-speed symbol outline and code skeleton extraction tool. + +Allows the AI model to locate classes, functions, and types in large files +with precise line numbers, minimizing token consumption. +""" + +from __future__ import annotations + +import os +import re +from typing import Any, Dict, List, Optional, Tuple + +from ..errors import ToolError +from .base import BaseTool + + +class OutlineSymbolsTool(BaseTool): + """Extract symbol outlines (classes, functions, types) from workspace source code.""" + + def __init__(self, root: Optional[str] = None) -> None: + self.root = os.path.realpath(root or os.getcwd()) + + @property + def name(self) -> str: + return "outline_symbols" + + @property + def description(self) -> str: + return ( + "Extracts a high-level symbol outline (classes, functions, methods, types, " + "interfaces) with line numbers from source files (Python, Go, JS/TS, Rust). " + "Far faster and more token-efficient than reading full files." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "Path to the source code file (relative to workspace).", + }, + }, + "required": ["path"], + } + + async def execute(self, path: str) -> str: + path = path.strip() + if not path: + raise ToolError("File path cannot be empty.") + + full_path = path if os.path.isabs(path) else os.path.join(self.root, path) + full_path = os.path.realpath(full_path) + + if not full_path.startswith(self.root): + raise ToolError(f"Path escapes workspace directory: {path}") + if not os.path.isfile(full_path): + raise ToolError(f"File not found: {path}") + + ext = os.path.splitext(full_path)[1].lower() + patterns = self._get_patterns_for_ext(ext) + + symbols: List[Tuple[int, str, str]] = [] + total_lines = 0 + + try: + with open(full_path, "r", encoding="utf-8", errors="replace") as f: + for idx, line in enumerate(f, 1): + total_lines = idx + stripped = line.strip() + if not stripped or stripped.startswith(("//", "#", "/*", "*")): + continue + + for kind, regex in patterns: + if regex.search(stripped): + symbols.append((idx, kind, stripped)) + break + except Exception as exc: + raise ToolError(f"Failed to read file {path}: {exc}") + + rel_path = os.path.relpath(full_path, self.root) + header = f"Outline of {rel_path} ({total_lines} lines, {len(symbols)} symbols found):\n" + + if not symbols: + return header + "\n(no top-level classes or functions detected)" + + out_lines = [header] + for line_num, kind, raw in symbols: + out_lines.append(f"L{line_num:<4} [{kind:<7}] {raw}") + + return "\n".join(out_lines) + + def _get_patterns_for_ext(self, ext: str) -> List[Tuple[str, re.Pattern]]: + if ext == ".py": + return [ + ("class", re.compile(r"^class\s+[A-Za-z0-9_]+")), + ("async", re.compile(r"^async\s+def\s+[A-Za-z0-9_]+\s*\(")), + ("def", re.compile(r"^def\s+[A-Za-z0-9_]+\s*\(")), + ] + elif ext == ".go": + return [ + ("method", re.compile(r"^func\s+\([^)]+\)\s+[A-Za-z0-9_]+\s*\(")), + ("func", re.compile(r"^func\s+[A-Za-z0-9_]+\s*\(")), + ("struct", re.compile(r"^type\s+[A-Za-z0-9_]+\s+struct\b")), + ("interface", re.compile(r"^type\s+[A-Za-z0-9_]+\s+interface\b")), + ("type", re.compile(r"^type\s+[A-Za-z0-9_]+\s+")), + ] + elif ext in (".ts", ".tsx", ".js", ".jsx"): + return [ + ("class", re.compile(r"^(?:export\s+)?(?:default\s+)?class\s+[A-Za-z0-9_]+")), + ("func", re.compile(r"^(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+[A-Za-z0-9_]+")), + ("type", re.compile(r"^(?:export\s+)?(?:interface|type)\s+[A-Za-z0-9_]+")), + ("const", re.compile(r"^(?:export\s+)?(?:const|let|var)\s+[A-Za-z0-9_]+\s*=\s*(?:async\s*)?\(")), + ] + elif ext == ".rs": + return [ + ("fn", re.compile(r"^(?:pub\s+)?(?:async\s+)?fn\s+[A-Za-z0-9_]+")), + ("struct", re.compile(r"^(?:pub\s+)?struct\s+[A-Za-z0-9_]+")), + ("enum", re.compile(r"^(?:pub\s+)?enum\s+[A-Za-z0-9_]+")), + ("impl", re.compile(r"^impl(?:\s*<[^>]+>)?\s+[A-Za-z0-9_]+")), + ("trait", re.compile(r"^(?:pub\s+)?trait\s+[A-Za-z0-9_]+")), + ] + else: + return [ + ("symbol", re.compile(r"^(?:class|struct|function|def|func)\s+[A-Za-z0-9_]+")), + ] + + +__all__ = ["OutlineSymbolsTool"] diff --git a/src/agentux/tools/todo.py b/src/agentux/tools/todo.py new file mode 100644 index 0000000..43d5d02 --- /dev/null +++ b/src/agentux/tools/todo.py @@ -0,0 +1,196 @@ +"""Task tracking for multi-step work. + +An agent given a five-part task will quietly do three of them and report +success. Writing the plan down first, and updating it as it goes, is the +cheapest thing that keeps the whole task in view. + +The list lives in memory and is rendered back to the model on every update, so +the current state is always in the conversation rather than something the model +has to remember. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional + +from ..errors import ToolError +from .base import BaseTool + +#: The states a task moves through. Kept small on purpose. +STATUSES = ("pending", "in_progress", "completed", "cancelled") + +#: The columns a rendered board uses, in order. +ORDER = ("in_progress", "pending", "completed", "cancelled") + +MAX_TASKS = 50 + + +class TodoTool(BaseTool): + """Maintain a checklist of what the current task requires.""" + + def __init__(self) -> None: + self._items: List[Dict[str, str]] = [] + self._next_id = 1 + + @property + def name(self) -> str: + return "todo" + + @property + def description(self) -> str: + return ( + "Track a checklist of steps for the current task. Create the full " + "list before starting a multi-step job, keep exactly one item " + "'in_progress' at a time, and mark items completed as you finish " + "them. The rendered list comes back on every update, so you do not " + "need to track it yourself. Use it for anything with more than " + "about three steps; skip it for single actions." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "action": { + "type": "string", + "enum": ["add", "update", "list", "clear"], + "description": ( + "add: append tasks. update: change one task's status. " + "list: render the current checklist. clear: remove all." + ), + }, + "tasks": { + "type": "array", + "items": {"type": "string"}, + "description": "Task descriptions. Required for 'add'.", + }, + "id": { + "type": "integer", + "description": "Task id to update. Required for 'update'.", + }, + "status": { + "type": "string", + "enum": list(STATUSES), + "description": "New status for a task. Required for 'update'.", + }, + }, + "required": ["action"], + } + + # ------------------------------------------------------------------ + def _find(self, task_id: Any) -> Dict[str, str]: + try: + wanted = int(task_id) + except (TypeError, ValueError): + raise ToolError(f"Task id must be an integer, got {task_id!r}.") from None + + for item in self._items: + if int(item["id"]) == wanted: + return item + valid = ", ".join(str(i["id"]) for i in self._items) or "(none)" + raise ToolError(f"No task with id {wanted}. Existing ids: {valid}") + + def _render(self) -> str: + if not self._items: + return "The checklist is empty." + + done = sum(1 for i in self._items if i["status"] == "completed") + cancelled = sum(1 for i in self._items if i["status"] == "cancelled") + total = len(self._items) + + summary = f"{done}/{total} complete" + if cancelled: + summary += f", {cancelled} cancelled" + lines = [f"Checklist ({summary}):"] + + for status in ORDER: + group = [i for i in self._items if i["status"] == status] + if not group: + continue + label = {"in_progress": "IN PROGRESS", "pending": "TODO", + "completed": "DONE", "cancelled": "SKIPPED"}[status] + lines.append(f"\n{label}") + for item in group: + text = item["task"] + if len(text) > 120: + text = text[:120] + "..." + lines.append(f" [{str(item['id']):>2}] {text}") + + remaining = total - done - cancelled + if remaining: + lines.append(f"\n{remaining} item(s) still open.") + else: + lines.append("\nEverything on the list is finished.") + return "\n".join(lines) + + def _add(self, tasks: Optional[List[str]]) -> str: + if not tasks: + raise ToolError("'add' needs a 'tasks' list of descriptions.") + room = MAX_TASKS - len(self._items) + if room <= 0: + raise ToolError( + f"The checklist is full ({MAX_TASKS} items). Update or clear " + "existing tasks before adding more." + ) + for text in tasks[:room]: + self._items.append({ + "id": str(self._next_id), + "task": str(text), + "status": "pending", + }) + self._next_id += 1 + if len(tasks) > room: + return self._render() + f"\n\n... {len(tasks) - room} task(s) dropped: the list is full." + return self._render() + + def _update(self, task_id: Any, status: Optional[str]) -> str: + if task_id is None: + raise ToolError("'update' needs a task 'id'.") + if status not in STATUSES: + raise ToolError( + f"Invalid status {status!r}. Use one of: {', '.join(STATUSES)}." + ) + + item = self._find(task_id) + previous = item["status"] + item["status"] = status + + # Keep at most one task in progress so "what am I doing now" stays + # unambiguous as the list gets long. + cleared = "" + if status == "in_progress": + for other in self._items: + if other is not item and other["status"] == "in_progress": + other["status"] = "pending" + cleared = f"\nMoved task [{other['id']}] back to pending." + + return ( + f"Task [{item['id']}]: {previous} -> {status}.{cleared}\n\n" + self._render() + ) + + async def execute( + self, + action: str, + tasks: Optional[List[str]] = None, + id: Optional[int] = None, # noqa: A002 - matches the JSON Schema name + status: Optional[str] = None, + **kwargs: Any, + ) -> str: + if action == "list": + return self._render() + if action == "add": + return self._add(tasks) + if action == "update": + return self._update(id, status) + if action == "clear": + count = len(self._items) + self._items.clear() + return f"Cleared {count} task(s)." + + raise ToolError( + f"Unsupported action {action!r}. Use 'add', 'update', 'list', or 'clear'." + ) + + +__all__ = ["TodoTool"] diff --git a/src/agentux/tools/web.py b/src/agentux/tools/web.py new file mode 100644 index 0000000..eae5eab --- /dev/null +++ b/src/agentux/tools/web.py @@ -0,0 +1,454 @@ +"""Live technical web search and page content extraction tools. + +Enables the agent to search online documentation, code references, +and error solutions without third-party python dependencies. +""" + +from __future__ import annotations + +import asyncio +import html +import json +import os +import re +import urllib.parse +import urllib.request +from typing import Any, Dict, List, Optional + +from ..errors import ToolError +from .base import BaseTool + +USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Agentux/0.2.0" + +#: Words that carry no subject, so they must not drive a Wikipedia lookup. +_WIKI_STOPWORDS = frozenset( + { + "what", "who", "whom", "whose", "when", "where", "why", "how", "which", + "is", "are", "was", "were", "do", "does", "did", "can", "could", + "should", "would", "will", "the", "and", "for", "with", "that", + "this", "from", "tell", "explain", "please", "about", "your", "you", + } +) + + +class WebSearchTool(BaseTool): + """Search technical documentation and code solutions on the live web.""" + + def __init__(self) -> None: + pass + + @property + def name(self) -> str: + return "web_search" + + @property + def description(self) -> str: + return ( + "Search technical documentation, error messages, and API references " + "on the live web. Uses DuckDuckGo HTML search by default, or Tavily/Brave " + "if API keys are configured." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Technical search query (e.g. 'pydantic v2 field_validator example').", + }, + "max_results": { + "type": "integer", + "description": "Maximum number of search results to return (default: 5).", + }, + }, + "required": ["query"], + } + + def search(self, query: str, max_results: int = 5) -> str: + """Run a search synchronously. + + Exists so callers outside the async tool path -- Agentux Solo grounds a + question before the model answers it -- can use it without an event + loop. ``execute`` is the tool-facing wrapper. + """ + query = query.strip() + if not query: + raise ToolError("Query cannot be empty.") + + # Check for Tavily API key + tavily_key = os.environ.get("TAVILY_API_KEY") + if tavily_key: + return self._search_tavily(query, tavily_key, max_results) + + # Check for Brave API key + brave_key = os.environ.get("BRAVE_API_KEY") + if brave_key: + return self._search_brave(query, brave_key, max_results) + + # Default: Zero-dependency DuckDuckGo HTML scraper + return self._search_duckduckgo(query, max_results) + + async def execute(self, query: str, max_results: int = 5, **kwargs: Any) -> str: + if "num_results" in kwargs: + max_results = int(kwargs["num_results"]) + return await asyncio.to_thread(self.search, query, max_results) + + def _fetch(self, url: str) -> str: + """GET a URL and return the decoded body.""" + req = urllib.request.Request( + url, + headers={"User-Agent": USER_AGENT, "Accept": "application/json, text/html"}, + ) + with urllib.request.urlopen(req, timeout=20) as resp: + return resp.read().decode("utf-8", errors="replace") + + def search_wikipedia(self, query: str, max_chars: int = 1200) -> str: + """Look a topic up on Wikipedia and return its lead sentence. + + Keyless and reliable, which makes it the best grounding source for a + small model: it returns a sentence containing the fact rather than a + headline the model can misread. + + Each candidate phrase is searched on its own and the best-matching + article wins. Opensearch matches whole phrases, so a question finds + nothing while its content words find the article; a single word often + lands on a disambiguation page ("Mojo" is one), so the phrase is tried + first. A title that merely contains the word is not enough either -- + the extract has to mention it, and a short title beats a long one when + the mentions tie. + """ + words = self._subject_words(query) + if not words: + return "" + terms = set(words) + + candidates: List[str] = [] + phrase = " ".join(words) + if phrase: + candidates.append(phrase) + candidates.extend(word for word in words if word != phrase) + + best_score = None + best_title = "" + best_extract = "" + try: + for candidate in candidates[:4]: + for title in self._wikipedia_titles(candidate)[:2]: + extract = self._wikipedia_summary(title) + if not extract: + continue + haystack = (title + " " + extract).lower() + hits = sum(1 for term in terms if term in haystack) + score = (hits, -len(title.split())) + if best_score is None or score > best_score: + best_score = score + best_title = title + best_extract = extract + if not best_extract: + return "" + # The lead paragraph may not answer the question -- "who invented + # the transistor" is not answered by a definition. Pick the + # paragraph that mentions the subject words most. + paragraph = self._wikipedia_best_paragraph(best_title, list(terms)) + return (paragraph or best_extract)[:max_chars] + except Exception: + return "" + + def _wikipedia_best_paragraph(self, title: str, terms: List[str]) -> str: + """The paragraph of an article that mentions the subject words most.""" + text = self._wikipedia_full_extract(title) + if not text: + return "" + best = "" + best_hits = 0 + for paragraph in text.split("\n"): + clean = " ".join(paragraph.split()) + if len(clean) < 40: + continue + lowered = clean.lower() + hits = sum(1 for term in terms if term in lowered) + if hits > best_hits: + best, best_hits = clean, hits + return best + + def _wikipedia_full_extract(self, title: str) -> str: + url = "https://en.wikipedia.org/w/api.php?" + urllib.parse.urlencode( + { + "action": "query", + "prop": "extracts", + "explaintext": 1, + "format": "json", + "redirects": 1, + "titles": title, + } + ) + data = json.loads(self._fetch(url)) + for page in data.get("query", {}).get("pages", {}).values(): + extract = page.get("extract") + if extract: + return str(extract) + return "" + + @staticmethod + def _subject_words(query: str) -> List[str]: + """The words in a question that could name its subject, in order.""" + return [ + word + for word in re.findall(r"[a-z0-9]+", str(query).lower()) + if len(word) >= 4 and word not in _WIKI_STOPWORDS + ] + + def _wikipedia_titles(self, query: str) -> List[str]: + url = "https://en.wikipedia.org/w/api.php?" + urllib.parse.urlencode( + { + "action": "opensearch", + "search": query, + "limit": 5, + "format": "json", + "profile": "fuzzy", + } + ) + data = json.loads(self._fetch(url)) + if len(data) > 1 and isinstance(data[1], list): + return [str(title) for title in data[1]] + return [] + + def _wikipedia_summary(self, title: str) -> str: + path = urllib.parse.quote(title.replace(" ", "_"), safe="()_") + data = json.loads( + self._fetch(f"https://en.wikipedia.org/api/rest_v1/page/summary/{path}") + ) + extract = data.get("extract") + if not extract or data.get("type") == "disambiguation": + return "" + return f"{data.get('title', title)}: {extract}" + + def _search_duckduckgo(self, query: str, max_results: int) -> str: + encoded_query = urllib.parse.urlencode({"q": query, "b": ""}) + url = f"https://html.duckduckgo.com/html/?{encoded_query}" + + req = urllib.request.Request( + url, + headers={ + "User-Agent": USER_AGENT, + "Accept": "text/html,application/xhtml+xml", + "Accept-Language": "en-US,en;q=0.9", + }, + ) + + try: + with urllib.request.urlopen(req, timeout=15) as resp: + content = resp.read().decode("utf-8", errors="replace") + except Exception as exc: + return f"Web search failed: {exc}" + + # Parse results with regex + results: List[Dict[str, str]] = [] + pattern = re.compile( + r'<a[^>]+class="result__snippet"[^>]*href="(?P<link>[^"]+)"[^>]*>(?P<snippet>.*?)</a>', + re.DOTALL | re.IGNORECASE, + ) + title_pattern = re.compile( + r'<a[^>]+class="result__url"[^>]*>(?P<title>.*?)</a>', + re.DOTALL | re.IGNORECASE, + ) + + # Alternative generic extraction for DuckDuckGo HTML layout + block_pattern = re.compile( + r'<div[^>]+class="[^"]*result__body[^"]*"[^>]*>(.*?)</div>\s*</div>', + re.DOTALL | re.IGNORECASE, + ) + + for block in block_pattern.findall(content): + if len(results) >= max_results: + break + + title_m = re.search(r'<a[^>]+class="result__a"[^>]*href="([^"]+)"[^>]*>(.*?)</a>', block, re.DOTALL) + snippet_m = re.search(r'<a[^>]+class="result__snippet"[^>]*>(.*?)</a>', block, re.DOTALL) + + if title_m: + raw_url = title_m.group(1) + # Unpack DuckDuckGo redirect uddg= if present + if "uddg=" in raw_url: + parsed = urllib.parse.parse_qs(urllib.parse.urlparse(raw_url).query) + raw_url = parsed.get("uddg", [raw_url])[0] + + title = re.sub(r"<[^>]+>", "", title_m.group(2)).strip() + title = html.unescape(title) + + snippet = "" + if snippet_m: + snippet = re.sub(r"<[^>]+>", "", snippet_m.group(1)).strip() + snippet = html.unescape(snippet) + + results.append({ + "title": title or "Untitled", + "url": raw_url, + "snippet": snippet, + }) + + if not results: + return f"No results found for query: {query!r}" + + lines = [f"Web Search Results for '{query}' ({len(results)} matches):\n"] + for idx, item in enumerate(results, 1): + lines.append(f"{idx}. **{item['title']}**") + lines.append(f" URL: {item['url']}") + if item["snippet"]: + lines.append(f" {item['snippet']}") + lines.append("") + + return "\n".join(lines).strip() + + def _search_tavily(self, query: str, api_key: str, max_results: int) -> str: + req_data = json.dumps({"api_key": api_key, "query": query, "max_results": max_results}).encode("utf-8") + req = urllib.request.Request( + "https://api.tavily.com/search", + data=req_data, + headers={"Content-Type": "application/json", "User-Agent": USER_AGENT}, + ) + try: + with urllib.request.urlopen(req, timeout=15) as resp: + data = json.loads(resp.read().decode("utf-8")) + except Exception as exc: + return f"Tavily search error: {exc}" + + results = data.get("results", []) + if not results: + return f"No results found for query: {query!r}" + + lines = [f"Tavily Search Results for '{query}':\n"] + for idx, r in enumerate(results[:max_results], 1): + lines.append(f"{idx}. **{r.get('title', 'Untitled')}**") + lines.append(f" URL: {r.get('url', '')}") + lines.append(f" {r.get('content', '')}\n") + return "\n".join(lines).strip() + + def _search_brave(self, query: str, api_key: str, max_results: int) -> str: + encoded = urllib.parse.urlencode({"q": query, "count": max_results}) + url = f"https://api.search.brave.com/res/v1/web/search?{encoded}" + req = urllib.request.Request( + url, + headers={"X-Subscription-Token": api_key, "Accept": "application/json", "User-Agent": USER_AGENT}, + ) + try: + with urllib.request.urlopen(req, timeout=15) as resp: + data = json.loads(resp.read().decode("utf-8")) + except Exception as exc: + return f"Brave search error: {exc}" + + results = data.get("web", {}).get("results", []) + if not results: + return f"No results found for query: {query!r}" + + lines = [f"Brave Search Results for '{query}':\n"] + for idx, r in enumerate(results[:max_results], 1): + lines.append(f"{idx}. **{r.get('title', 'Untitled')}**") + lines.append(f" URL: {r.get('url', '')}") + lines.append(f" {r.get('description', '')}\n") + return "\n".join(lines).strip() + + +class FetchWebPageTool(BaseTool): + """Scrape and convert online web pages and documentation to clean readable text.""" + + @property + def name(self) -> str: + return "fetch_web_page" + + @property + def description(self) -> str: + return ( + "Fetch an online URL and extract its text content, converting HTML " + "into clean readable plain text / markdown. Useful for reading documentation." + ) + + @property + def parameters(self) -> Dict[str, Any]: + return { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "Full HTTP or HTTPS URL to fetch.", + }, + "max_chars": { + "type": "integer", + "description": "Maximum characters to return (default: 8000).", + }, + }, + "required": ["url"], + } + + async def execute(self, url: str, max_chars: int = 8000) -> str: + url = url.strip() + if not url.startswith(("http://", "https://")): + raise ToolError(f"URL must start with http:// or https://: {url!r}") + + req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) + try: + with urllib.request.urlopen(req, timeout=20) as resp: + headers = getattr(resp, "headers", None) + charset = (headers.get_content_charset() if headers and hasattr(headers, "get_content_charset") else None) or "utf-8" + raw_html = resp.read().decode(charset, errors="replace") + except Exception as exc: + return f"Failed to fetch {url}: {exc}" + + text = self._html_to_markdown(raw_html) + if len(text) > max_chars: + text = text[:max_chars] + f"\n\n[... truncated at {max_chars} characters ...]" + + return f"Content of {url}:\n\n{text}" + + def _html_to_markdown(self, raw_html: str) -> str: + # Strip script, style, head, nav, footer + content = re.sub(r"<(script|style|head|nav|footer)[^>]*>.*?</\1>", " ", raw_html, flags=re.DOTALL | re.IGNORECASE) + content = re.sub(r"<!--.*?-->", " ", content, flags=re.DOTALL) + + # Convert links <a href="url">text</a> -> [text](url) + content = re.sub( + r'<a[^>]+href="([^"]+)"[^>]*>(.*?)</a>', + lambda m: f"[{re.sub(r'<[^>]+>', '', m.group(2)).strip()}]({m.group(1)})", + content, + flags=re.DOTALL | re.IGNORECASE, + ) + + # Convert headings + for h in range(6, 0, -1): + content = re.sub( + rf"<h{h}[^>]*>(.*?)</h{h}>", + rf"\n\n{'#' * h} \1\n\n", + content, + flags=re.DOTALL | re.IGNORECASE, + ) + + # Convert paragraphs, list items, breaks + content = re.sub(r"<li[^>]*>(.*?)</li>", r"\n• \1", content, flags=re.DOTALL | re.IGNORECASE) + content = re.sub(r"<p[^>]*>(.*?)</p>", r"\n\n\1\n\n", content, flags=re.DOTALL | re.IGNORECASE) + content = re.sub(r"<br\s*/?>", "\n", content, flags=re.IGNORECASE) + + # Strip remaining tags + content = re.sub(r"<[^>]+>", " ", content) + + # Decode HTML entities + content = html.unescape(content) + + # Collapse whitespace + lines = [re.sub(r"[ \t]+", " ", line).strip() for line in content.split("\n")] + collapsed = [] + prev_blank = False + for line in lines: + if not line: + if not prev_blank: + collapsed.append("") + prev_blank = True + else: + collapsed.append(line) + prev_blank = False + + return "\n".join(collapsed).strip() + + +__all__ = ["WebSearchTool", "FetchWebPageTool"] diff --git a/src/agentux/ui.py b/src/agentux/ui.py new file mode 100644 index 0000000..0f6c5ff --- /dev/null +++ b/src/agentux/ui.py @@ -0,0 +1,660 @@ +"""Terminal presentation. + +Everything that decides how Agentux *looks* lives here rather than in the CLI, +so the same rendering can be reused by a test or another front end. + +Three ideas carry the interface: + +* **Gradients, sparingly.** A gradient on the wordmark and on nothing else. + Colour used as decoration everywhere is noise, and it disappears entirely + when the output is not a terminal. The wordmark's gradient runs down the + rows and its extruded side is a second, darker colour -- the two together + are what make the letters read as solid rather than as flat blocks. +* **One live region.** Tool activity scrolls permanently; the answer streams + into a single live region that re-renders markdown as it arrives. Two + competing live regions fight each other and flicker. +* **Numbers are labelled.** Tokens come from the provider when it reports them + and from an estimate when it does not, and the display says which. +""" + +from __future__ import annotations + +import time +from typing import Any, List, Optional, Tuple, Union + +from rich.console import Console, Group, RenderableType +from rich.live import Live +from rich.markdown import Markdown +from rich.panel import Panel +from rich.text import Text + +from .theme import ( + ACCENT_DIM, + BORDER, + BORDER_SUBTLE, + CYAN, + EMERALD, + PINK, + PURPLE, + TEXT_LIGHT, + TEXT_MUTED, + WORDMARK_DEPTH, + WORDMARK_END, + WORDMARK_SHADOW, + WORDMARK_START, + YELLOW, +) +from .usage import ( + DEFAULT_CONTEXT_WINDOW, + Usage, + context_bar, + conversation_tokens, + format_duration, + format_tokens, +) + +#: The accent ramp. Emerald -> cyan, from the brand palette. +ACCENT_START = WORDMARK_START +ACCENT_END = WORDMARK_END + +#: The colour of the extruded side of each letter. Dim enough to read as depth +#: rather than as a second letter, bright enough to be visible at all. +ACCENT_DEPTH = WORDMARK_DEPTH + +#: Letterforms, sharp-cornered, each exactly ``LETTER_WIDTH`` columns by +#: ``LETTER_HEIGHT`` rows. Declared as a grid rather than written out as one +#: banner because a hand-typed banner silently goes ragged -- and ragged rows +#: shear, which is what once made this read as "AOSNTUK" instead of AGENTUX. +#: +#: ``G`` carries a crossbar on its fourth row. Without it ``G`` is a closed +#: ring and reads as ``O``. ``U`` closes across both legs on its last row, so +#: the bowl is actually connected. +LETTER_HEIGHT = 6 +LETTER_WIDTH = 8 + +_LETTERS: Dict[str, List[str]] = { + "A": [ + " ████ ", + " ██ ██ ", + "████████", + "██ ██", + "██ ██", + "██ ██", + ], + "G": [ + " ██████ ", + "██ ██", + "██ ", + "██ ████ ", + "██ ██", + " ██████ ", + ], + "E": [ + "████████", + "██ ", + "███████ ", + "██ ", + "██ ", + "████████", + ], + "N": [ + "██ ██", + "███ ██", + "████ ██", + "██ ██ ██", + "██ ████", + "██ ███", + ], + "T": [ + "████████", + " ████ ", + " ████ ", + " ████ ", + " ████ ", + " ████ ", + ], + "U": [ + "██ ██", + "██ ██", + "██ ██", + "██ ██", + "██ ██", + " ██████ ", + ], + "X": [ + "██ ██", + "██ ██", + " ██ ██ ", + " ████ ", + " ██ ██ ", + "██ ██", + ], +} + +#: How far the extruded side is offset from the face, in (columns, rows). +#: One column and one row. Anything wider reaches across the gap between +#: neighbouring strokes and fills it in, which fuses the letters together -- +#: the depth then reads as fill rather than as an edge. +DEPTH_X = 1 +DEPTH_Y = 1 + + +def _wordmark_layers() -> Tuple[List[str], List[str]]: + """The wordmark as two aligned layers: the face and the extruded side. + + Returned separately rather than composited, because the two want different + colours. Compositing first would mean re-deriving which cells are shadow, + and the depth colour is most of what makes the letters read as solid. + """ + face = [ + [" "] * (len(_LETTERS) * LETTER_WIDTH + (len(_LETTERS) - 1)) + for _ in range(LETTER_HEIGHT) + ] + for index, char in enumerate(_WORDMARK_TEXT): + glyph = _LETTERS[char] + offset = index * (LETTER_WIDTH + 1) + for row in range(LETTER_HEIGHT): + for col, pixel in enumerate(glyph[row]): + face[row][offset + col] = pixel + + height, width = LETTER_HEIGHT, len(face[0]) + rows, cols = height + DEPTH_Y, width + DEPTH_X + + # The silhouette shifted down-right by (DEPTH_Y, DEPTH_X). Anything drawn + # from this is "what the letters look like one step further back". + shifted = [[" "] * cols for _ in range(rows)] + for row in range(height): + for col in range(width): + shifted[row + DEPTH_Y][col + DEPTH_X] = face[row][col] + + def ink(grid: List[List[str]], row: int, col: int) -> bool: + return 0 <= row < len(grid) and 0 <= col < len(grid[row]) and grid[row][col] != " " + + # Only the *rim* of the shifted silhouette is drawn. Two things are + # subtracted, and both are load-bearing: + # + # 1. The face itself. Painting depth over the face smears the letters. + # 2. The interior of the shifted silhouette -- the cells a letter's + # counter encloses, such as the triangle inside "A". Those are inside + # the solid, not on its edge, so filling them turns the counter into + # a filled wedge and the letter stops reading. + # + # What survives is the one-cell edge along the lower-right of each stroke, + # which is the only part of an extruded face you would actually see. + depth = [[" "] * cols for _ in range(rows)] + for row in range(rows): + for col in range(cols): + if not ink(shifted, row, col) or ink(face, row, col): + continue + enclosed = all( + ink(shifted, row + dy, col + dx) + for dy, dx in ((-1, 0), (1, 0), (0, -1), (0, 1)) + ) + if not enclosed: + depth[row][col] = shifted[row][col] + + return ( + ["".join(row) for row in face], + ["".join(row) for row in depth], + ) + + +#: The word, spelled once. `_LETTERS` is the only place the shapes live. +_WORDMARK_TEXT = "AGENTUX" + + +def interpolate(start: Tuple[int, int, int], end: Tuple[int, int, int], t: float) -> str: + """A colour between two RGB points, as a rich hex string.""" + t = max(0.0, min(1.0, t)) + return "#{:02x}{:02x}{:02x}".format( + round(start[0] + (end[0] - start[0]) * t), + round(start[1] + (end[1] - start[1]) * t), + round(start[2] + (end[2] - start[2]) * t), + ) + + +def gradient_text(text: str, start=ACCENT_START, end=ACCENT_END) -> Text: + """Paint a string with a horizontal colour ramp. + + The ramp runs across the whole string, not per line, so a multi-line + wordmark reads as one gradient rather than several restarting ones. + """ + total = len(text) + if total == 0: + return Text("") + + lines = text.split("\n") + styled = Text() + seen = 0 + for line_index, line in enumerate(lines): + if line_index: + styled.append("\n") + for char in line: + styled.append(char, style=interpolate(start, end, seen / max(1, total - 1))) + seen += 1 + seen += 1 # the newline counts toward the ramp + return styled + + +def gradient_text_vertical( + text: str, start=ACCENT_START, end=ACCENT_END +) -> Text: + """Paint a string with a vertical colour ramp, one colour per line. + + The wordmark needs this rather than a horizontal ramp. Its glyphs are solid + block characters, so ramping across each line colours adjacent columns of + the same letter differently -- the letter reads as vertical stripes instead + of one shape. Ramping down the lines instead gives each row a single colour, + which keeps every letter solid and still reads as one gradient overall. + """ + lines = text.split("\n") + if not lines: + return Text("") + + styled = Text() + last = max(1, len(lines) - 1) + for index, line in enumerate(lines): + if index: + styled.append("\n") + if not line: + continue + # Half a step in: the first row fully at `start` and the last fully at + # `end` both look washed out next to their neighbours. + styled.append(line, style=interpolate(start, end, (index + 0.5) / (last + 1))) + return styled + + +def wordmark() -> Text: + """The Agentux wordmark: a gradient face with an extruded dark side. + + The two layers are composited onto one grid before any colour is applied, + because a cell can hold only one glyph. Drawing the depth row and then the + face row as separate strings would interleave them wrongly -- the rows are + different lengths, so the face would land in the wrong columns and smear + sideways across the banner. + + Each row is padded to the full grid width and never stripped: the trailing + blanks are what keep the letters from shearing against each other. + """ + face, depth = _wordmark_layers() + width = max(len(row) for row in depth) + + # Composite: start from the depth, then stamp the face over it. + grid = [list(row.ljust(width)) for row in depth] + for index, row in enumerate(face): + target = grid[index] + for col, char in enumerate(row): + if char != " ": + target[col] = char + # Which cells are face and which are depth, after compositing. The depth + # layer is taller than the face (that is the extrusion), so the extra rows + # have no face to mark and are depth throughout. + face_mask = [ + [ + index < len(face) and col < len(face[index]) and face[index][col] != " " + for col in range(width) + ] + for index in range(len(grid)) + ] + + last = max(1, len(grid) - 1) + styled = Text() + for index in range(len(grid)): + if index: + styled.append("\n") + shade = interpolate(ACCENT_START, ACCENT_END, (index + 0.5) / (last + 1)) + side = interpolate(ACCENT_DEPTH, WORDMARK_SHADOW, index / last) + for col in range(width): + char = grid[index][col] + if char == " ": + styled.append(" ") + elif face_mask[index][col]: + styled.append(char, style=shade) + else: + styled.append(char, style=side) + + return styled + + +#: The face layer only, for tests and for anything that wants plain text. +WORDMARK = "\n".join(_wordmark_layers()[0]) + + +def context_bar_text(fraction: float, width: int = 16) -> Text: + """The context bar as a styled ``Text``. + + ``usage.context_bar`` returns markup, which is only safe to print with + markup parsing on. Callers here build a ``Text`` with ``append``, and + ``Text.append`` treats its argument literally -- so the tags would appear + on screen as ``[green]...[/green]``. Converting here keeps the style. + """ + return Text.from_markup(context_bar(fraction, width)) + + +# ---------------------------------------------------------------------- +# Rendering into a buffer instead of onto the terminal +# ---------------------------------------------------------------------- +# The full-screen TUI owns the terminal, so rich must not print to stdout. +# These render to an in-memory console and return the ANSI text, which the TUI +# hands to prompt_toolkit as styled text. Rich stays the only renderer; it just +# writes somewhere that is not the screen. + +def render_markdown_ansi(text: str, width: int = 80) -> str: + """Render markdown to ANSI text without touching stdout.""" + return _render_ansi(Markdown(text) if text.strip() else Text(""), width) + + +def render_text_ansi(text: str, width: int = 80) -> str: + """Render plain text to ANSI, with no markup interpretation.""" + return _render_ansi(Text(text), width) + + +def render_tool_ansi(text: str, width: int = 100) -> str: + """Render a verbose tool result as an indented, dimmed block.""" + body = Text() + for index, line in enumerate(text.rstrip("\n").split("\n")): + if index: + body.append("\n") + body.append(" " + line, style="dim") + return _render_ansi(body, width) + + +def _render_ansi(renderable: RenderableType, width: int) -> str: + from io import StringIO + + console = Console( + file=StringIO(), + width=max(20, width), + force_terminal=True, + color_system="truecolor", + legacy_windows=False, + highlight=False, + soft_wrap=False, + ) + console.print(renderable) + # `print` terminates its last line. Callers embed this in a larger + # document, so the extra newline shows up as a stray blank row there. + raw = console.file.getvalue().rstrip("\n") # type: ignore[union-attr] + return "\n".join(line.rstrip() for line in raw.split("\n")) + + +def wordmark_to_ansi(rows: Optional[int] = None) -> str: + """The wordmark as ANSI text, optionally only its first N rows. + + Truncating has to keep the spans. The gradient lives in them, so slicing + the plain string and re-rendering would give a flat grey block instead of + the ramp. + """ + # Split the Text itself, not its plain form: the spans carry the gradient, + # and re-joining plain strings would flatten every row to one colour. + lines = wordmark().split("\n", allow_blank=True) + # The rendered Text keeps its trailing newline, which would show up as a + # stray blank line inside the transcript. + while lines and not lines[-1].plain.strip(): + lines.pop() + if rows is not None: + lines = lines[:rows] + + trimmed = Text() + for index, line in enumerate(lines): + if index: + trimmed.append("\n") + trimmed.append_text(line) + return _render_ansi(trimmed, 200) + + +# ---------------------------------------------------------------------- +# Streaming +# ---------------------------------------------------------------------- +class StreamRenderer: + """Renders an answer into one live region, markdown and all. + + Markdown cannot be appended to incrementally -- a half-typed code fence is + not the same document as a closed one -- so the accumulated text is + re-rendered on each delta. For answer-sized text that is cheap, and it buys + correctly formatted output the instant it is complete. + """ + + def __init__(self, console: Console, markdown: bool = True, transient: bool = False) -> None: + self.console = console + self.markdown = markdown + self.buffer: List[str] = [] + self._live: Optional[Live] = None + self.started = time.monotonic() + self.elapsed: float = 0.0 + + def _renderable(self) -> RenderableType: + text = "".join(self.buffer) + if not text: + return Text("") + if self.markdown: + return Markdown(text) + return Text(text) + + def start(self) -> None: + if self._live is not None: + return + self.started = time.monotonic() + self._live = Live( + self._renderable(), + console=self.console, + refresh_per_second=12, + transient=False, + vertical_overflow="visible", + ) + self._live.start() + + def feed(self, piece: str) -> None: + """Append a delta and repaint.""" + self.buffer.append(piece) + if self._live is not None: + self._live.update(self._renderable()) + + def stop(self) -> str: + """Finish the region, leaving the rendered answer on screen.""" + self.elapsed = time.monotonic() - self.started + if self._live is not None: + self._live.update(self._renderable()) + self._live.stop() + self._live = None + return "".join(self.buffer) + + +# ---------------------------------------------------------------------- +# Session chrome +# ---------------------------------------------------------------------- +class SessionView: + """Renders the header, tool activity, status, and footer for one session.""" + + def __init__(self, console: Console, agent: Any, mcp_manager: Any = None) -> None: + self.console = console + self.agent = agent + self.mcp_manager = mcp_manager + self.started = time.monotonic() + self.usage = Usage() + self._spinner_cycle = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏" + + # -- header --------------------------------------------------------- + def banner(self) -> None: + agent = self.agent + mcp_tools = len(self.mcp_manager.tools) if self.mcp_manager else 0 + built_in = len(agent.registry) - mcp_tools + servers = len(self.mcp_manager.servers) if self.mcp_manager else 0 + + tools_line = f"{built_in} built-in" + if servers: + tools_line += f" · {mcp_tools} from {servers} MCP server{'s' if servers != 1 else ''}" + + stats = self.stats_line() + + body = Group( + wordmark(), + Text(""), + Text.from_markup(f"[dim]v{agentux_version()}[/dim]"), + Text(""), + _rule(), + _field("model", agent.provider.get_model_name()), + _field("workspace", agent.config.working_dir), + _field("tools", tools_line), + _field("context", stats), + Text(""), + _rule(), + Text.from_markup( + "[dim]/help[/dim] [dim]/model[/dim] [dim]/set[/dim] " + "[dim]/tools[/dim] [dim]/mcp[/dim] [dim]/context[/dim] " + "[dim]/reset[/dim] [dim]/exit[/dim]" + ), + ) + + self.console.print() + self.console.print( + Panel(body, border_style=ACCENT_START_HEX, padding=(1, 2), title=None) + ) + self.console.print() + + # -- activity ------------------------------------------------------- + def narration(self, text: str) -> None: + self.console.print(f" [dim italic]{_shorten(text, 160)}[/dim italic]") + + def tool_call(self, text: str) -> None: + name = text.split("(", 1)[0] + arguments = text[len(name):] + self.console.print( + Text(" ⏺ ", style=ACCENT_START_HEX) + + Text(name, style=f"bold {ACCENT_START_HEX}") + + Text(_shorten(arguments, 100), style="dim") + ) + + def tool_error(self, text: str) -> None: + self.console.print(f" [red]✗[/red] [red]{_shorten(text, 300)}[/red]") + + def tool_output(self, text: str, verbose: bool) -> None: + if not verbose: + return + self.console.print( + Panel(_shorten(text, 6000), title="result", border_style="dim", padding=(0, 1)) + ) + + def reflection(self, text: str) -> None: + self.console.print(f" [yellow]⟳[/yellow] [dim yellow]{_shorten(text, 120)}[/dim yellow]") + + # -- status --------------------------------------------------------- + def status(self) -> str: + """The line shown while the agent is working. + + Deliberately one line: a status that reflows the terminal is a status + the user has to wait for. Everything here is short enough to stay put. + """ + frame = self._spinner_cycle[int(time.monotonic() * 10) % len(self._spinner_cycle)] + elapsed = time.monotonic() - self.started + tools = len(self.agent.step_log) + parts = [ + f"[{ACCENT_START_HEX}]{frame}[/{ACCENT_START_HEX}] [bold]working[/bold]", + f"[dim]{_format(elapsed)}[/dim]", + f"[dim]{tools} tool{'s' if tools != 1 else ''}[/dim]", + ] + tokens = self.usage.total_tokens + if tokens: + # A leading ~ marks a figure the provider did not report. + source = "" if self.usage.reported else "~" + parts.append(f"[dim]{source}{format_tokens(tokens)} tok[/dim]") + return " " + " [dim]·[/dim] ".join(parts) + + def stats_line(self) -> Text: + """Context occupancy, for the banner and ``/context``.""" + return self.context_stats() + + def context_stats(self) -> Text: + """The occupancy bar and its numbers, as a ``Text``. + + A ``Text`` and not a markup string: every caller appends this into an + existing ``Text``, and ``Text.append`` does not parse markup, so a + returned ``"[green]...[/green]"`` would be shown to the user verbatim. + """ + history = getattr(self.agent, "history", []) + system = history[0].content if history and history[0].role == "system" else "" + tools = self.agent.registry.definitions() + used = conversation_tokens(history, system or "", tools) + window = DEFAULT_CONTEXT_WINDOW + fraction = min(1.0, used / window) if window else 0.0 + + text = Text() + text.append_text(context_bar_text(fraction, 16)) + text.append(f" {fraction * 100:.0f}%", style="dim") + text.append(f" {format_tokens(used)} / {format_tokens(window)}", style="dim") + return text + + # -- footer --------------------------------------------------------- + def summary(self, steps: int) -> None: + elapsed = time.monotonic() - self.started + pieces = [ + f"{len(self.agent.step_log)} tool call{'s' if len(self.agent.step_log) != 1 else ''}", + f"{steps} step{'s' if steps != 1 else ''}", + _format(elapsed), + ] + if self.usage.total_tokens: + pieces.append(f"{'~' if not self.usage.reported else ''}" + f"{format_tokens(self.usage.total_tokens)} tokens") + failures = sum(1 for entry in self.agent.step_log if entry[2]) + if failures: + pieces.append(f"{failures} failed") + + self.console.print() + self.console.print( + Text(" " + " · ".join(pieces), style="dim") + ) + self.console.print(_rule()) + self.started = time.monotonic() + + +# ---------------------------------------------------------------------- +ACCENT_START_HEX = interpolate(ACCENT_START, ACCENT_END, 0.15) +ACCENT_END_HEX = interpolate(ACCENT_START, ACCENT_END, 0.85) + + +def _rule() -> Text: + return Text("─" * 60, style="dim") + + +def _field(label: str, value: Union[str, Text]) -> Text: + """One ``label value`` row of the banner. + + A ``Text`` value keeps its own styles. The context row passes one so the + bar can stay green/yellow/red instead of being flattened to cyan, and so + its markup tags are never shown literally. + """ + text = Text() + text.append(f"{label:<11}", style="dim") + if isinstance(value, Text): + text.append_text(value.copy()) + else: + text.append(value, style="cyan") + return text + + +def _shorten(text: str, limit: int) -> str: + text = text.strip() + if len(text) <= limit: + return text + return text[:limit] + "…" + + +def _format(seconds: float) -> str: + return format_duration(seconds) + + +def agentux_version() -> str: + from . import __version__ + + return __version__ + + +__all__ = [ + "StreamRenderer", + "SessionView", + "gradient_text", + "wordmark", + "interpolate", + "ACCENT_START", + "ACCENT_END", +] diff --git a/src/agentux/usage.py b/src/agentux/usage.py new file mode 100644 index 0000000..53323ef --- /dev/null +++ b/src/agentux/usage.py @@ -0,0 +1,195 @@ +"""Token and context accounting. + +Two different numbers matter and they are not the same: + +* **Usage** is what the provider reports it was billed for: prompt tokens plus + completion tokens, summed across every request in a run. +* **Context** is how full the next request will be -- system prompt, tool + schemas, and the whole conversation. + +Providers report usage inconsistently, and local servers often report nothing, +so every figure here is labelled with where it came from. A number presented as +exact when it was guessed is worse than no number. +""" + +from __future__ import annotations + +import json +from typing import Any, Dict, List, Optional + +from .models import Message, ToolDefinition + +#: Rough characters-per-token ratio for English text and code. Used only when +#: the provider gives us nothing; good to within ~10% for prose, worse for +#: code, which is why estimates are never labelled as reported. +CHARS_PER_TOKEN = 4 + +#: Assumed context window when the provider does not advertise one. Deliberately +#: conservative so the percentage is not reassuring by default. +DEFAULT_CONTEXT_WINDOW = 128_000 + +#: Above this fraction of the window, the conversation is genuinely at risk. +CONTEXT_WARN_FRACTION = 0.75 + + +def estimate_tokens(text: Optional[str]) -> int: + """Approximate the token count of a string.""" + if not text: + return 0 + return max(1, len(text) // CHARS_PER_TOKEN) + + +def usage_from_payload(raw: Any) -> Optional[Dict[str, int]]: + """Read a usage object out of a provider response, if there is one. + + Handles both shapes in the wild: OpenAI's ``usage`` object, and Ollama's + native ``prompt_eval_count`` / ``eval_count`` fields. + """ + if not isinstance(raw, dict): + return None + + usage = raw.get("usage") + if isinstance(usage, dict): + prompt = usage.get("prompt_tokens") + completion = usage.get("completion_tokens") + if isinstance(prompt, int) or isinstance(completion, int): + total = usage.get("total_tokens") + return { + "prompt_tokens": prompt if isinstance(prompt, int) else 0, + "completion_tokens": completion if isinstance(completion, int) else 0, + "total_tokens": total if isinstance(total, int) else 0, + } + + prompt = raw.get("prompt_eval_count") + completion = raw.get("eval_count") + if isinstance(prompt, int) or isinstance(completion, int): + return { + "prompt_tokens": prompt if isinstance(prompt, int) else 0, + "completion_tokens": completion if isinstance(completion, int) else 0, + "total_tokens": (prompt if isinstance(prompt, int) else 0) + + (completion if isinstance(completion, int) else 0), + } + + return None + + +class Usage: + """Running token totals for a session or a single run.""" + + def __init__(self) -> None: + self.prompt_tokens = 0 + self.completion_tokens = 0 + self.requests = 0 + #: True when at least one provider response carried real numbers. + self.reported = False + + @property + def total_tokens(self) -> int: + return self.prompt_tokens + self.completion_tokens + + def record(self, usage: Optional[Dict[str, int]], fallback_prompt: int = 0, + fallback_completion: int = 0) -> None: + """Add one request's usage, falling back to estimates when absent.""" + self.requests += 1 + if usage: + self.prompt_tokens += usage.get("prompt_tokens", 0) + self.completion_tokens += usage.get("completion_tokens", 0) + self.reported = True + else: + self.prompt_tokens += fallback_prompt + self.completion_tokens += fallback_completion + + def reset(self) -> None: + self.__init__() # type: ignore[misc] + + def summary(self) -> str: + """A one-line, honest description of where these numbers came from.""" + source = "reported" if self.reported else "estimated" + return ( + f"{self.total_tokens:,} tokens " + f"({self.prompt_tokens:,} in / {self.completion_tokens:,} out, {source})" + ) + + def __repr__(self) -> str: + return f"Usage(prompt={self.prompt_tokens}, completion={self.completion_tokens})" + + +def conversation_tokens( + history: List[Message], + system_prompt: str = "", + tools: Optional[List[ToolDefinition]] = None, +) -> int: + """Estimate the tokens the next request will carry. + + Covers the three things that actually get sent: the system prompt, the tool + schemas, and every message. The tool schemas are easy to forget and are + often a large fraction of the total. + """ + total = estimate_tokens(system_prompt) + + for tool in tools or []: + total += estimate_tokens(tool.name) + total += estimate_tokens(tool.description) + total += estimate_tokens(json.dumps(tool.parameters, default=str)) + + for message in history: + total += estimate_tokens(message.content) + for call in message.tool_calls or []: + total += estimate_tokens(call.name) + total += estimate_tokens(json.dumps(call.arguments, default=str)) + + return total + + +def format_tokens(count: int) -> str: + """Compact token counts: 812, 12.4k, 1.2M.""" + if count < 1000: + return str(count) + if count < 1_000_000: + return f"{count / 1000:.1f}k" + return f"{count / 1_000_000:.1f}M" + + +def format_duration(seconds: float) -> str: + """Short, human durations: 240ms, 3.1s, 2m04s.""" + if seconds < 1: + return f"{seconds * 1000:.0f}ms" + if seconds < 60: + return f"{seconds:.1f}s" + minutes, remainder = divmod(seconds, 60) + if minutes < 60: + return f"{int(minutes)}m{remainder:04.1f}s".replace("m0", "m") + hours, minutes = divmod(int(minutes), 60) + return f"{hours}h{minutes:02d}m" + + +def context_bar(fraction: float, width: int = 20) -> str: + """A fixed-width bar for context usage, coloured by how close it is. + + Returns a *markup string*. It must reach the screen through something that + parses markup -- ``console.print(...)`` or ``Text.from_markup(...)`` -- never + through ``Text.append``, which takes its argument as literal text and would + show the ``[green]`` tags verbatim. :func:`agentux.ui.context_bar_text` is + the safe way to get this into an existing ``Text``. + """ + fraction = max(0.0, min(1.0, fraction)) + filled = int(round(fraction * width)) + bar = "█" * filled + "░" * (width - filled) + if fraction >= CONTEXT_WARN_FRACTION: + return f"[red]{bar}[/red]" + if fraction >= 0.5: + return f"[yellow]{bar}[/yellow]" + return f"[green]{bar}[/green]" + + +__all__ = [ + "Usage", + "usage_from_payload", + "estimate_tokens", + "conversation_tokens", + "format_tokens", + "format_duration", + "context_bar", + "CHARS_PER_TOKEN", + "DEFAULT_CONTEXT_WINDOW", +] diff --git a/src/agentux/web/static/app.js b/src/agentux/web/static/app.js new file mode 100644 index 0000000..0534348 --- /dev/null +++ b/src/agentux/web/static/app.js @@ -0,0 +1,592 @@ +/* ────────────────────────────────────────────────────────────── + Agentux Web Console — client script + Vanilla JS, SSE streaming, zero dependencies. + ────────────────────────────────────────────────────────────── */ + +"use strict"; + +const $ = (sel, root = document) => root.querySelector(sel); +const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel)); + +const state = { + busy: false, + view: "chat", + files: [], + tools: [], + checkpoints: [], + sessions: [], + currentFile: null, +}; + +/* ── Bootstrap ─────────────────────────────────────────────── */ +async function boot() { + try { + const status = await api("/api/status"); + const modelLine = $("#model-line"); + modelLine.textContent = status.model || "—"; + modelLine.classList.remove("muted"); + const wsLine = $("#workspace-line"); + wsLine.textContent = shortPath(status.workspace); + wsLine.title = status.workspace; + } catch (e) { + console.warn("status fetch failed", e); + } + loadTools(); + loadCheckpoints(); + loadSessions(); + switchView("chat"); +} + +/* ── API helper ────────────────────────────────────────────── */ +async function api(path, opts = {}) { + const res = await fetch(path, { + method: opts.method || "GET", + headers: { "Content-Type": "application/json" }, + body: opts.body ? JSON.stringify(opts.body) : undefined, + }); + if (!res.ok) { + const t = await res.text().catch(() => ""); + throw new Error(`${res.status} ${t}`); + } + return res.json(); +} + +function shortPath(p) { + if (!p) return "—"; + const parts = p.split("/").filter(Boolean); + return parts.length <= 3 ? p : "…" + parts.slice(-3).join("/"); +} + +/* ── Views ─────────────────────────────────────────────────── */ +function switchView(name) { + state.view = name; + $$(".nav-item").forEach(b => b.classList.toggle("active", b.dataset.view === name)); + $$(".view").forEach(v => v.classList.remove("active")); + const el = $("#view-" + name); + if (el) el.classList.add("active"); + + const titles = { + chat: ["Chat", "Ask anything. Tools run inline."], + files: ["Workspace", "Browse and edit project files."], + tools: ["Tools", "Available tools and their descriptions."], + checkpoints: ["Checkpoints", "Snapshots of the working tree."], + sessions: ["Sessions", "Saved conversation sessions."], + }; + const [h, sub] = titles[name] || ["", ""]; + $("#view-title").textContent = h; + $("#view-subtitle").textContent = sub; + + if (name === "files") renderFileTree(); + if (name === "checkpoints") loadCheckpoints(); + if (name === "sessions") loadSessions(); +} + +/* ── Chat ──────────────────────────────────────────────────── */ +function addMessage(role, content = "") { + const wrap = document.createElement("div"); + wrap.className = "msg " + role; + const who = document.createElement("div"); + who.className = "who"; + who.textContent = role === "user" ? "You" : role === "assistant" ? "Agentux" : "system"; + const body = document.createElement("div"); + body.className = "body"; + if (content) renderMarkdown(body, content); + wrap.append(who, body); + $("#messages").append(wrap); + scrollBottom(); + return { wrap, body }; +} + +function renderMarkdown(el, text) { + // Very small markdown: code fences, inline code, tables, lists, bold/italic. + const lines = text.split("\n"); + let i = 0; + let block = null; + + function closeBlock() { + if (block) { el.append(block); block = null; } + } + + function ensureP() { + closeBlock(); + block = document.createElement("p"); + } + + while (i < lines.length) { + const line = lines[i]; + + // Code fence + const fence = line.match(/^```(\w*)$/); + if (fence) { + ensureP(); + closeBlock(); + const pre = document.createElement("pre"); + const code = document.createElement("code"); + let j = i + 1; + while (j < lines.length && !lines[j].match(/^```$/)) j++; + code.textContent = lines.slice(i + 1, j).join("\n"); + pre.append(code); + el.append(pre); + i = j + 1; + continue; + } + + // Table + if (line.includes("|") && i + 1 < lines.length && lines[i + 1].match(/^\|[\s:|-]+\|$/)) { + ensureP(); + closeBlock(); + const table = document.createElement("table"); + const head = document.createElement("tr"); + line.split("|").slice(1, -1).forEach(c => { + const th = document.createElement("th"); + th.textContent = c.trim(); + head.append(th); + }); + table.append(head); + i += 2; + while (i < lines.length && lines[i].includes("|")) { + const tr = document.createElement("tr"); + lines[i].split("|").slice(1, -1).forEach(c => { + const td = document.createElement("td"); + td.innerHTML = inline(c.trim()); + tr.append(td); + }); + table.append(tr); + i++; + } + el.append(table); + continue; + } + + // Unordered list + if (/^\s*[-*]\s/.test(line)) { + ensureP(); + closeBlock(); + const ul = document.createElement("ul"); + while (i < lines.length && /^\s*[-*]\s/.test(lines[i])) { + const li = document.createElement("li"); + li.innerHTML = inline(lines[i].replace(/^\s*[-*]\s/, "")); + ul.append(li); + i++; + } + el.append(ul); + continue; + } + + // Ordered list + if (/^\s*\d+\.\s/.test(line)) { + ensureP(); + closeBlock(); + const ol = document.createElement("ol"); + while (i < lines.length && /^\s*\d+\.\s/.test(lines[i])) { + const li = document.createElement("li"); + li.innerHTML = inline(lines[i].replace(/^\s*\d+\.\s/, "")); + ol.append(li); + i++; + } + el.append(ol); + continue; + } + + // Blank line -> paragraph break + if (line.trim() === "") { + ensureP(); + closeBlock(); + i++; + continue; + } + + ensureP(); + block.append(document.createElement("span")); + block.lastChild.innerHTML = inline(line); + i++; + } + closeBlock(); +} + +function inline(s) { + return s + .replace(/&/g, "&") + .replace(/</g, "<") + .replace(/>/g, ">") + .replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>") + .replace(/\*([^*]+)\*/g, "<em>$1</em>") + .replace(/`([^`]+)`/g, '<code>$1</code>'); +} + +function scrollBottom() { + const m = $("#messages"); + m.scrollTop = m.scrollHeight; +} + +function addToolCard(name, args, result, error) { + const card = document.createElement("div"); + card.className = "tool-card" + (error ? " error" : ""); + const tag = error ? "error" : result ? "result" : "running"; + const argsStr = args ? JSON.stringify(args) : ""; + card.innerHTML = ` + <div class="tool-head"> + <span class="tool-tag">${tag}</span> + <span class="tool-name">${escapeHtml(name)}</span> + </div> + ${argsStr ? `<div class="tool-args">${escapeHtml(argsStr)}</div>` : ""} + ${result !== undefined ? `<div class="tool-result">${escapeHtml(result)}</div>` : ""} + `; + $("#messages").append(card); + scrollBottom(); + return card; +} + +function escapeHtml(s) { + return String(s).replace(/[&<>"']/g, c => ({ + "&": "&", "<": "<", ">": ">", '"': """, "'": "'" + }[c])); +} + +async function sendPrompt() { + const input = $("#input"); + const prompt = input.value.trim(); + if (!prompt || state.busy) return; + + state.busy = true; + $("#send-btn").disabled = true; + input.value = ""; + autoGrow(input); + + addMessage("user", prompt); + const assistant = addMessage("assistant"); + let buffer = ""; + + const resp = await fetch("/api/chat", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ prompt }), + }); + + const reader = resp.body.getReader(); + const decoder = new TextDecoder(); + let done = false; + + while (!done) { + const { value, done: d } = await reader.read(); + done = d; + if (value) { + const chunk = decoder.decode(value, { stream: true }); + const events = parseSSE(chunk); + for (const ev of events) { + handleSSE(ev, assistant, buffer); + } + } + } + + state.busy = false; + $("#send-btn").disabled = false; + input.focus(); +} + +function parseSSE(chunk) { + const events = []; + const blocks = chunk.split(/\n\n/); + for (const block of blocks) { + if (!block.trim()) continue; + let data = ""; + let event = "message"; + for (const line of block.split("\n")) { + if (line.startsWith("event:")) event = line.slice(6).trim(); + else if (line.startsWith("data:")) data += line.slice(5).trim(); + } + if (data) { + try { events.push({ event, data: JSON.parse(data) }); } + catch { events.push({ event, data: { raw: data } }); } + } + } + return events; +} + +function handleSSE(ev, assistant, buffer) { + const d = ev.data; + switch (ev.event) { + case "chunk": + buffer += d.delta || ""; + renderMarkdown(assistant.body, buffer); + scrollBottom(); + break; + case "tool_call": + addToolCard(d.name, d.arguments); + break; + case "tool_result": + const cards = $("#messages .tool-card.running"); + if (cards.length) { + const last = cards[cards.length - 1]; + last.classList.remove("running"); + const res = document.createElement("div"); + res.className = "tool-result"; + res.textContent = d.result; + last.append(res); + } else { + addToolCard(d.name, null, d.result); + } + scrollBottom(); + break; + case "narration": + case "reflection": { + // Agent narration / reflection nudge. Show as a system line. + const sys = addMessage("system"); + renderMarkdown(sys.body, d.message || ""); + scrollBottom(); + break; + } + case "assistant": + // Final answer. The streaming already populated the assistant bubble. + break; + case "done": + addMessage("system", "✓ Completed"); + break; + case "error": + const err = document.createElement("div"); + err.className = "tool-card error"; + err.innerHTML = `<div class="tool-head"><span class="tool-tag">error</span></div><div class="tool-result">${escapeHtml(d.error)}</div>`; + $("#messages").append(err); + scrollBottom(); + break; + case "nudge": + const n = document.createElement("div"); + n.className = "tool-card"; + n.style.borderColor = "var(--purple)"; + n.innerHTML = `<div class="tool-head" style="color:var(--purple)"><span class="tool-tag">enforced</span></div><div class="tool-args">${escapeHtml(d.message)}</div>`; + $("#messages").append(n); + scrollBottom(); + break; + } +} + +/* ── Files ─────────────────────────────────────────────────── */ +async function loadFiles() { + try { + const data = await api("/api/files"); + state.files = data.files || []; + } catch (e) { + console.warn(e); + } +} + +function renderFileTree() { + loadFiles().then(() => { + const tree = $("#file-tree"); + tree.innerHTML = ""; + if (!state.files.length) { + tree.innerHTML = '<div class="empty">No files found</div>'; + return; + } + const root = { name: "", children: {} }; + for (const f of state.files) { + const parts = f.split("/"); + let node = root; + for (let i = 0; i < parts.length; i++) { + const part = parts[i]; + if (i === parts.length - 1) { + node.files = node.files || []; + node.files.push({ name: part, path: f }); + } else { + node.children = node.children || {}; + node.children[part] = node.children[part] || { name: part, children: {}, files: [] }; + node = node.children[part]; + } + } + } + renderNode(tree, root, 0); + }); +} + +function renderNode(parent, node, depth) { + const keys = Object.keys(node.children || {}).sort(); + for (const name of keys) { + const child = node.children[name]; + const div = document.createElement("div"); + div.className = "tree-item"; + div.style.paddingLeft = (8 + depth * 14) + "px"; + div.innerHTML = `<span class="f-icon">📁</span><span class="indent"></span>${escapeHtml(name)}`; + div.onclick = () => { + $$(".tree-item").forEach(t => t.classList.remove("active")); + div.classList.add("active"); + }; + parent.append(div); + renderNode(div, child, depth + 1); + } + for (const f of node.files || []) { + const div = document.createElement("div"); + div.className = "tree-item"; + div.style.paddingLeft = (8 + depth * 14) + "px"; + const icon = fileIcon(f.name); + div.innerHTML = `<span class="f-icon">${icon}</span>${escapeHtml(f.name)}`; + div.onclick = () => openFile(f.path, div); + parent.append(div); + } +} + +function fileIcon(name) { + const ext = name.split(".").pop().toLowerCase(); + const map = { + js: "📄", mjs: "📄", cjs: "📄", ts: "📘", tsx: "📘", jsx: "📘", + py: "🐍", rb: "💎", go: "🔵", rs: "🟠", java: "☕", kt: "🟣", + c: "🧩", h: "🧩", cpp: "🧩", hpp: "🧩", + md: "📝", txt: "📝", json: "🧾", yaml: "⚙️", yml: "⚙️", toml: "⚙️", + html: "🌐", css: "🎨", scss: "🎨", sass: "🎨", + sh: "⌨️", bash: "⌨️", zsh: "⌨️", + sql: "🗄️", db: "🗄️", sqlite: "🗄️", + png: "🖼️", jpg: "🖼️", svg: "🖼️", gif: "🖼️", + pdf: "📕", + }; + return map[ext] || "📄"; +} + +async function openFile(path, el) { + if (el) { + $$(".tree-item").forEach(t => t.classList.remove("active")); + el.classList.add("active"); + } + state.currentFile = path; + $("#file-path").textContent = path; + $("#file-content").textContent = "Loading…"; + $("#view-files").classList.add("active"); + try { + const data = await api("/api/file?path=" + encodeURIComponent(path)); + $("#file-content").textContent = data.content || "(empty)"; + } catch (e) { + $("#file-content").textContent = "Error: " + e.message; + } +} + +/* ── Tools ─────────────────────────────────────────────────── */ +async function loadTools() { + try { + const data = await api("/api/tools"); + state.tools = data.tools || []; + renderTools(); + } catch (e) { + console.warn(e); + } +} + +function renderTools() { + const grid = $("#tools-grid"); + grid.innerHTML = ""; + if (!state.tools.length) { + grid.innerHTML = '<div class="empty">No tools registered</div>'; + return; + } + for (const t of state.tools) { + const card = document.createElement("div"); + card.className = "tool-chip"; + card.innerHTML = ` + <div class="tool-chip-name">${escapeHtml(t.name)}</div> + <div class="tool-chip-desc">${escapeHtml(t.description || "")}</div> + `; + grid.append(card); + } +} + +/* ── Checkpoints ───────────────────────────────────────────── */ +async function loadCheckpoints() { + try { + const data = await api("/api/checkpoints"); + state.checkpoints = data.checkpoints || []; + renderCheckpoints(); + } catch (e) { + console.warn(e); + } +} + +function renderCheckpoints() { + const box = $("#checkpoints"); + box.innerHTML = ""; + if (!state.checkpoints.length) { + box.innerHTML = '<div class="empty">No checkpoints yet</div>'; + return; + } + for (const cp of state.checkpoints) { + const card = document.createElement("div"); + card.className = "cp-card"; + card.innerHTML = ` + <div class="cp-meta"> + <span class="cp-id">${escapeHtml(cp.id)}</span> + <span class="cp-desc">${escapeHtml(cp.description || "")}</span> + <span class="cp-time">${escapeHtml(cp.time || "")} · ${cp.files_count || 0} files${cp.git_sha ? " · " + escapeHtml(cp.git_sha.slice(0,7)) : ""}</span> + </div> + <button class="btn btn-ghost btn-sm" data-id="${escapeHtml(cp.id)}">Rollback</button> + `; + card.querySelector("button").onclick = () => rollback(cp.id); + box.append(card); + } +} + +async function rollback(id) { + if (!confirm("Roll back to checkpoint " + id + "?")) return; + try { + const res = await api("/api/checkpoints/rollback", { method: "POST", body: { checkpoint_id: id } }); + alert(res.message); + loadCheckpoints(); + } catch (e) { + alert("Rollback failed: " + e.message); + } +} + +/* ── Sessions ──────────────────────────────────────────────── */ +async function loadSessions() { + try { + const data = await api("/api/sessions"); + state.sessions = data.sessions || []; + renderSessions(); + } catch (e) { + console.warn(e); + } +} + +function renderSessions() { + const box = $("#sessions"); + box.innerHTML = ""; + if (!state.sessions.length) { + box.innerHTML = '<div class="empty">No saved sessions</div>'; + return; + } + for (const s of state.sessions) { + const card = document.createElement("div"); + card.className = "sess-card"; + card.innerHTML = ` + <div class="sess-meta"> + <span class="sess-id">${escapeHtml(s.id || "")}</span> + <span class="sess-title">${escapeHtml(s.title || "Untitled")}</span> + <span class="sess-time">${escapeHtml(s.time || "")}</span> + </div> + `; + box.append(card); + } +} + +/* ── Composer ──────────────────────────────────────────────── */ +function autoGrow(ta) { + ta.style.height = "auto"; + ta.style.height = Math.min(ta.scrollHeight, 200) + "px"; +} + +/* ── Wire up ───────────────────────────────────────────────── */ +document.addEventListener("DOMContentLoaded", () => { + $$(".nav-item").forEach(b => b.onclick = () => switchView(b.dataset.view)); + $("#clear-btn").onclick = () => { + $("#messages").innerHTML = ""; + }; + $("#close-file-btn").onclick = () => switchView("chat"); + + const form = $("#composer"); + const input = $("#input"); + form.onsubmit = (e) => { e.preventDefault(); sendPrompt(); }; + input.oninput = () => autoGrow(input); + input.onkeydown = (e) => { + if (e.key === "Enter" && !e.shiftKey) { + e.preventDefault(); + sendPrompt(); + } + }; + + boot(); +});
\ No newline at end of file diff --git a/src/agentux/web/static/index.html b/src/agentux/web/static/index.html new file mode 100644 index 0000000..10ac988 --- /dev/null +++ b/src/agentux/web/static/index.html @@ -0,0 +1,99 @@ +<!DOCTYPE html> +<html lang="en" data-theme="emerald"> +<head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <title>Agentux · Web Console</title> + <link rel="stylesheet" href="/styles.css" /> + <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⌋</text></svg>" /> +</head> +<body> + <div class="app"> + <!-- ────────────────────────── Sidebar ────────────────────────── --> + <aside class="sidebar"> + <div class="brand"> + <span class="brand-mark">⌋</span> + <div class="brand-text"> + <strong>AGENTUX</strong> + <span id="model-line" class="muted">—</span> + </div> + </div> + + <nav class="nav"> + <button class="nav-item active" data-view="chat"> + <span class="nav-icon">💬</span> Chat + </button> + <button class="nav-item" data-view="files"> + <span class="nav-icon">🗂</span> Workspace + </button> + <button class="nav-item" data-view="tools"> + <span class="nav-icon">🔧</span> Tools + </button> + <button class="nav-item" data-view="checkpoints"> + <span class="nav-icon">Snapshots</span> Checkpoints + </button> + <button class="nav-item" data-view="sessions"> + <span class="nav-icon">🧾</span> Sessions + </button> + </nav> + + <div class="sidebar-footer"> + <span id="workspace-line" class="muted">—</span> + </div> + </aside> + + <!-- ────────────────────────── Main ────────────────────────── --> + <main class="main"> + <header class="topbar"> + <div class="view-title"> + <h1 id="view-title">Chat</h1> + <p id="view-subtitle" class="muted">Ask anything. Tools run inline.</p> + </div> + <div class="topbar-actions"> + <button id="clear-btn" class="btn btn-ghost" title="Clear conversation">Clear</button> + </div> + </header> + + <!-- Chat view --> + <section class="view chat-view" id="view-chat"> + <div class="messages" id="messages"></div> + <form class="composer" id="composer"> + <textarea id="input" rows="1" placeholder="Send a message…" autocomplete="off"></textarea> + <button type="submit" id="send-btn" class="btn btn-primary">Send</button> + </form> + </section> + + <!-- Files view --> + <section class="view" id="view-files" hidden> + <div class="file-browser"> + <div class="file-tree" id="file-tree"></div> + <div class="file-viewer"> + <div class="file-viewer-head"> + <span id="file-path" class="muted">No file selected</span> + <button id="close-file-btn" class="btn btn-ghost btn-sm">✕</button> + </div> + <pre id="file-content" class="file-content"></pre> + </div> + </div> + </section> + + <!-- Tools view --> + <section class="view" id="view-tools" hidden> + <div class="tools-grid" id="tools-grid"></div> + </section> + + <!-- Checkpoints view --> + <section class="view" id="view-checkpoints" hidden> + <div class="checkpoints" id="checkpoints"></div> + </section> + + <!-- Sessions view --> + <section class="view" id="view-sessions" hidden> + <div class="sessions" id="sessions"></div> + </section> + </main> + </div> + + <script src="/app.js"></script> +</body> +</html>
\ No newline at end of file diff --git a/src/agentux/web/static/styles.css b/src/agentux/web/static/styles.css new file mode 100644 index 0000000..be1167b --- /dev/null +++ b/src/agentux/web/static/styles.css @@ -0,0 +1,442 @@ +/* ────────────────────────────────────────────────────────────── + Agentux Web Console — single-file stylesheet + Theme: emerald on near-black, with cyan and amber accents. + Zero dependencies. + ────────────────────────────────────────────────────────────── */ + +:root { + --bg: #0a0d12; + --bg-2: #11151c; + --bg-3: #1a1f2b; + --bg-elev: #202633; + --border: #2a3140; + --border-2: #343d4e; + --text: #e6e9ef; + --text-2: #a8b1bf; + --muted: #6b7383; + --emerald: #00ff88; + --emerald-d: #00c46a; + --cyan: #14d6ff; + --amber: #ffb020; + --red: #ff5d5d; + --purple: #b06bff; + --radius: 10px; + --shadow: 0 8px 28px rgba(0,0,0,.45); + --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace; + --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; +} + +[data-theme="emerald"] { + --accent: var(--emerald); + --accent-d: var(--emerald-d); + --accent-glow: rgba(0,255,136,.18); +} + +[data-theme="amber"] { + --accent: var(--amber); + --accent-d: #e69514; + --accent-glow: rgba(255,176,32,.18); +} + +[data-theme="cyan"] { + --accent: var(--cyan); + --accent-d: #09a8d6; + --accent-glow: rgba(20,214,255,.18); +} + +* { box-sizing: border-box; } + +html, body { + margin: 0; + height: 100%; + background: var(--bg); + color: var(--text); + font-family: var(--sans); + font-size: 14px; + -webkit-font-smoothing: antialiased; +} + +::selection { background: var(--accent-glow); } + +.app { + display: grid; + grid-template-columns: 240px 1fr; + height: 100vh; + overflow: hidden; +} + +/* ── Sidebar ─────────────────────────────────────────────── */ +.sidebar { + background: var(--bg-2); + border-right: 1px solid var(--border); + display: flex; + flex-direction: column; + padding: 16px 12px; + gap: 8px; +} + +.brand { + display: flex; + align-items: center; + gap: 10px; + padding: 6px 8px 14px; + border-bottom: 1px solid var(--border); + margin-bottom: 4px; +} +.brand-mark { + font-size: 26px; + line-height: 1; + color: var(--accent); + font-weight: 700; +} +.brand-text strong { + font-size: 15px; + letter-spacing: .14em; + display: block; +} +.muted { color: var(--muted); } +.muted.small { font-size: 11px; } + +.nav { display: flex; flex-direction: column; gap: 2px; } + +.nav-item { + display: flex; + align-items: center; + gap: 10px; + background: transparent; + border: 1px solid transparent; + color: var(--text-2); + font: inherit; + font-size: 13px; + padding: 8px 10px; + border-radius: 8px; + cursor: pointer; + text-align: left; + transition: background .12s, color .12s, border-color .12s; +} +.nav-item:hover { background: var(--bg-3); color: var(--text); } +.nav-item.active { + background: var(--accent-glow); + color: var(--accent); + border-color: var(--border-2); +} +.nav-icon { font-size: 14px; width: 16px; text-align: center; } + +.sidebar-footer { + margin-top: auto; + padding-top: 10px; + border-top: 1px solid var(--border); + font-size: 11px; +} + +/* ── Main ────────────────────────────────────────────────── */ +.main { + display: flex; + flex-direction: column; + min-width: 0; + overflow: hidden; +} + +.topbar { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 20px; + border-bottom: 1px solid var(--border); + background: var(--bg-2); + flex-shrink: 0; +} +.view-title h1 { margin: 0; font-size: 15px; font-weight: 600; letter-spacing: .02em; } +.view-title .muted { font-size: 12px; } + +.btn { + background: var(--bg-3); + border: 1px solid var(--border-2); + color: var(--text); + font: inherit; + font-size: 12px; + padding: 6px 12px; + border-radius: 8px; + cursor: pointer; + transition: background .12s, border-color .12s; +} +.btn:hover { background: var(--bg-elev); border-color: var(--border-2); } +.btn-primary { + background: var(--accent); + color: #06281a; + border-color: var(--accent); + font-weight: 600; +} +.btn-primary:hover { filter: brightness(1.08); } +.btn-primary:disabled { opacity: .45; cursor: not-allowed; } +.btn-ghost { background: transparent; } +.btn-sm { padding: 4px 8px; font-size: 11px; } + +.view { display: none; flex: 1; overflow: hidden; } +.view.active { display: flex; flex-direction: column; min-height: 0; } + +/* ── Chat ────────────────────────────────────────────────── */ +.chat-view { padding: 0; } + +.messages { + flex: 1; + overflow-y: auto; + padding: 20px 24px 8px; + display: flex; + flex-direction: column; + gap: 14px; +} + +.msg { + max-width: 820px; + width: 100%; + margin: 0; + animation: fade .25s ease; +} +@keyframes fade { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; } } + +.msg .who { + font-size: 11px; + font-weight: 600; + letter-spacing: .08em; + text-transform: uppercase; + margin-bottom: 6px; + color: var(--muted); +} +.msg.user .who { color: var(--cyan); } +.msg.assistant .who { color: var(--accent); } +.msg.system .who { color: var(--amber); } + +.msg .body { + white-space: pre-wrap; + word-break: break-word; + line-height: 1.55; + font-size: 14px; +} +.msg .body p { margin: 0 0 8px; } +.msg .body p:last-child { margin-bottom: 0; } +.msg .body code { + font-family: var(--mono); + font-size: 12.5px; + background: var(--bg-3); + padding: 1px 5px; + border-radius: 4px; +} +.msg .body pre { + background: var(--bg-3); + border: 1px solid var(--border); + border-radius: 8px; + padding: 10px 12px; + overflow-x: auto; + margin: 8px 0; +} +.msg .body pre code { background: none; padding: 0; } + +/* Markdown-ish tables */ +.msg .body table { + border-collapse: collapse; + margin: 8px 0; + font-size: 13px; +} +.msg .body th, .msg .body td { + border: 1px solid var(--border-2); + padding: 5px 10px; + text-align: left; +} +.msg .body th { background: var(--bg-3); } + +/* Tool card */ +.tool-card { + background: var(--bg-2); + border: 1px solid var(--border); + border-left: 3px solid var(--amber); + border-radius: 8px; + padding: 10px 12px; + margin: 6px 0; + font-size: 13px; +} +.tool-card .tool-head { + display: flex; + align-items: center; + gap: 8px; + color: var(--amber); + font-weight: 600; +} +.tool-card .tool-head .tool-name { font-family: var(--mono); font-size: 12px; } +.tool-card .tool-args { color: var(--text-2); margin-top: 4px; font-family: var(--mono); font-size: 11.5px; white-space: pre-wrap; word-break: break-word; } +.tool-card .tool-result { margin-top: 6px; color: var(--text-2); font-family: var(--mono); font-size: 11.5px; white-space: pre-wrap; word-break: break-word; max-height: 220px; overflow: auto; } +.tool-card .tool-tag { font-size: 10px; opacity: .7; text-transform: uppercase; letter-spacing: .06em; } +.tool-card.error { border-left-color: var(--red); } +.tool-card.error .tool-head { color: var(--red); } +.tool-card.running { border-left-color: var(--cyan); } +.tool-card.running .tool-head { color: var(--cyan); } + +.cursor::after { + content: "▍"; + color: var(--accent); + animation: blink 1s steps(2, start) infinite; + font-family: var(--mono); +} +@keyframes blink { 50% { opacity: 0; } } + +/* Composer */ +.composer { + display: flex; + gap: 10px; + align-items: flex-end; + padding: 12px 20px 16px; + border-top: 1px solid var(--border); + background: var(--bg-2); + flex-shrink: 0; +} +.composer textarea { + flex: 1; + resize: none; + max-height: 200px; + min-height: 44px; + background: var(--bg-3); + border: 1px solid var(--border-2); + border-radius: 10px; + color: var(--text); + font: inherit; + font-size: 14px; + padding: 11px 14px; + line-height: 1.5; + outline: none; + transition: border-color .12s, box-shadow .12s; +} +.composer textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-glow); } + +/* ── Files ───────────────────────────────────────────────── */ +.file-browser { + display: grid; + grid-template-columns: 280px 1fr; + height: 100%; + overflow: hidden; +} +.file-tree { + overflow-y: auto; + padding: 12px; + border-right: 1px solid var(--border); + font-family: var(--mono); + font-size: 12.5px; +} +.file-tree .tree-item { + display: flex; + align-items: center; + gap: 6px; + padding: 3px 6px; + border-radius: 5px; + cursor: pointer; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +.file-tree .tree-item:hover { background: var(--bg-3); } +.file-tree .tree-item.active { background: var(--accent-glow); color: var(--accent); } +.file-tree .tree-item .indent { width: 14px; display: inline-block; } +.file-tree .tree-item .f-icon { width: 16px; text-align: center; color: var(--muted); } + +.file-viewer { + display: flex; + flex-direction: column; + min-width: 0; + overflow: hidden; +} +.file-viewer-head { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px 14px; + border-bottom: 1px solid var(--border); + background: var(--bg-2); + font-family: var(--mono); + font-size: 12px; + flex-shrink: 0; +} +.file-content { + flex: 1; + margin: 0; + padding: 14px; + overflow: auto; + background: var(--bg); + color: var(--text-2); + font-family: var(--mono); + font-size: 12.5px; + line-height: 1.6; + white-space: pre; + tab-size: 4; +} + +/* ── Tools ───────────────────────────────────────────────── */ +.tools-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); + gap: 12px; + padding: 16px 20px; + align-content: start; +} +.tool-chip { + background: var(--bg-2); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 12px 14px; + cursor: pointer; + transition: border-color .12s, transform .12s; +} +.tool-chip:hover { border-color: var(--border-2); transform: translateY(-1px); } +.tool-chip .tool-chip-name { + font-family: var(--mono); + font-size: 13px; + color: var(--accent); + font-weight: 600; +} +.tool-chip .tool-chip-desc { + color: var(--text-2); + font-size: 12px; + margin-top: 4px; + line-height: 1.45; +} + +/* ── Checkpoints / sessions ──────────────────────────────── */ +.checkpoints, .sessions { + overflow-y: auto; + padding: 16px 20px; + display: flex; + flex-direction: column; + gap: 10px; +} +.cp-card, .sess-card { + background: var(--bg-2); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 12px 14px; + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} +.cp-card .cp-meta, .sess-card .sess-meta { display: flex; flex-direction: column; gap: 2px; } +.cp-card .cp-id, .sess-card .sess-id { font-family: var(--mono); font-size: 12px; color: var(--accent); } +.cp-card .cp-desc, .sess-card .sess-title { font-size: 13px; } +.cp-card .cp-time, .sess-card .sess-time { font-size: 11px; color: var(--muted); } +.cp-card .cp-files { font-size: 11px; color: var(--muted); } + +.empty { + color: var(--muted); + text-align: center; + padding: 40px 20px; + font-size: 13px; +} + +/* Scrollbar */ +::-webkit-scrollbar { width: 9px; height: 9px; } +::-webkit-scrollbar-track { background: transparent; } +::-webkit-scrollbar-thumb { background: var(--border-2); border-radius: 5px; } +::-webkit-scrollbar-thumb:hover { background: var(--border); } + +@media (max-width: 720px) { + .app { grid-template-columns: 1fr; } + .sidebar { display: none; } + .file-browser { grid-template-columns: 1fr; } +}
\ No newline at end of file diff --git a/src/agentux/workflow.py b/src/agentux/workflow.py new file mode 100644 index 0000000..126a3d5 --- /dev/null +++ b/src/agentux/workflow.py @@ -0,0 +1,124 @@ +"""Autonomous test-driven verification and self-healing workflow engine for Agentux. + +Provides automated test execution, failure diagnosis, surgical repair loops, +and rollback safety for software projects. +""" + +from __future__ import annotations + +import os +import subprocess +from typing import Any, Callable, Dict, List, Optional, Tuple + + +def detect_test_runner(root: str) -> Optional[str]: + """Detect the most likely test command for the current project root.""" + if os.path.isfile(os.path.join(root, "pyproject.toml")) or os.path.isfile(os.path.join(root, "setup.py")): + if os.path.isdir(os.path.join(root, "tests")): + return "python3 -m pytest" + if os.path.isfile(os.path.join(root, "go.mod")): + return "go test ./..." + if os.path.isfile(os.path.join(root, "package.json")): + return "npm test" + if os.path.isfile(os.path.join(root, "Cargo.toml")): + return "cargo test" + return None + + +class SelfHealingWorkflow: + """Manages autonomous test execution, error diagnosis, and self-repair cycles.""" + + def __init__(self, agent: Any, test_command: Optional[str] = None) -> None: + self.agent = agent + self.root = agent.config.working_dir or os.getcwd() + self.test_command = test_command or detect_test_runner(self.root) or "pytest" + + def run_tests_sync(self, cmd: Optional[str] = None) -> Tuple[int, str]: + """Execute test command and capture exit code and combined output.""" + command = cmd or self.test_command + try: + res = subprocess.run( + command, + shell=True, + cwd=self.root, + capture_output=True, + text=True, + timeout=60, + ) + output = (res.stdout or "") + (res.stderr or "") + return res.returncode, output.strip() + except subprocess.TimeoutExpired: + return 124, f"Tests timed out after 60 seconds (command: {command})." + except Exception as exc: + return 1, f"Failed to execute test command '{command}': {exc}" + + async def execute_repair_loop( + self, + cmd: Optional[str] = None, + max_attempts: int = 3, + on_progress: Optional[Callable[[str], None]] = None, + ) -> Dict[str, Any]: + """Execute test-driven self-healing loop until tests pass or attempts exhausted.""" + command = cmd or self.test_command + checkpoint_mgr = getattr(self.agent, "checkpoint_manager", None) + initial_cp = None + if checkpoint_mgr: + initial_cp = checkpoint_mgr.create_checkpoint(f"Pre-repair snapshot before '{command}'") + + def emit(msg: str) -> None: + if on_progress: + on_progress(msg) + elif hasattr(self.agent, "_emit"): + self.agent._emit("narration", msg) + + emit(f"🧪 Running test suite: `{command}`") + code, output = self.run_tests_sync(command) + + if code == 0: + return { + "success": True, + "attempts": 0, + "command": command, + "output": output, + "message": f"All tests passed on initial run ({command}).", + } + + emit(f"❌ Test run failed with code {code}. Beginning autonomous repair loop (max {max_attempts} attempts)...") + + attempt = 0 + while attempt < max_attempts: + attempt += 1 + emit(f"🔧 Repair cycle {attempt}/{max_attempts}: Analyzing tracebacks and applying fixes...") + + prompt = ( + f"The test command `{command}` failed with exit code {code}.\n\n" + f"--- Test Output ---\n{output[-2000:]}\n-------------------\n\n" + "Please analyze the failing test(s) or traceback, inspect the relevant files, " + "and apply a surgical fix to resolve the error. Keep changes focused only on the failure." + ) + + # Let agent run to repair + await self.agent.run(prompt, interactive=False) + + # Re-run tests to verify fix + emit(f"🧪 Re-running tests to verify attempt {attempt}...") + code, output = self.run_tests_sync(command) + if code == 0: + emit(f"✅ Success! All tests passing after attempt {attempt}.") + return { + "success": True, + "attempts": attempt, + "command": command, + "output": output, + "message": f"Successfully repaired and verified passing tests after {attempt} attempt(s).", + } + + emit(f"⚠️ Tests still failing after {max_attempts} attempts.") + return { + "success": False, + "attempts": attempt, + "command": command, + "output": output, + "initial_checkpoint": initial_cp.id if initial_cp else None, + "message": f"Tests still failing after {max_attempts} repair attempts. You can run `/undo` to revert.", + } |
