"""Command processing system for AI Sidebar slash commands.""" from dataclasses import dataclass from typing import Callable, Optional @dataclass class CommandResult: """Result of command execution.""" success: bool message: str data: dict | None = None class CommandProcessor: """Parses and executes slash commands.""" def __init__(self): """Initialize command processor with command registry.""" self._handlers: dict[str, Callable] = {} def register_command(self, command: str, handler: Callable) -> None: """ Register a command handler. Args: command: Command string (e.g., "/new", "/model") handler: Callable that takes command arguments and returns CommandResult """ self._handlers[command.lower()] = handler def is_command(self, text: str) -> bool: """ Check if text starts with a command. Args: text: User input text Returns: True if text starts with a registered command """ if not text or not text.startswith("/"): return False # Extract command (first word) parts = text.strip().split(maxsplit=1) command = parts[0].lower() return command in self._handlers def execute(self, text: str) -> CommandResult: """ Parse and execute command. Args: text: User input text starting with command Returns: CommandResult with execution status and message """ if not text or not text.startswith("/"): return CommandResult( success=False, message="Invalid command format. Commands must start with '/'." ) # Parse command and arguments parts = text.strip().split(maxsplit=1) command = parts[0].lower() args = parts[1] if len(parts) > 1 else "" # Check if command is registered if command not in self._handlers: return CommandResult( success=False, message=f"Unknown command: {command}. Type /help for available commands." ) # Execute command handler try: handler = self._handlers[command] return handler(args) except Exception as e: return CommandResult( success=False, message=f"Error executing command: {str(e)}" )