Command System#
The centralized command system provides unified slash command processing across all interfaces (CLI, OpenWebUI, etc.) with extensible command categories and rich autocompletion.
This system enables consistent command handling, context-aware execution, and seamless integration across different framework interfaces through a unified registry and execution model.
Core Components#
Command Registry#
- class osprey.commands.CommandRegistry[source]#
Bases:
objectCentralized registry for all slash commands across framework interfaces.
The CommandRegistry provides unified command management with support for command registration, discovery, validation, and execution. The registry maintains command metadata, handles aliases, and coordinates execution with rich context information for interface-specific behavior.
- Key Features:
Unified command storage with category organization
Alias support for command shortcuts and compatibility
Context-aware execution with interface-specific behavior
Automatic help generation and command discovery
Extensible registration patterns for custom commands
Error handling with user-friendly feedback
- Registry Lifecycle:
Initialization: Auto-registration of core framework commands
Registration: Application and custom command registration
Discovery: Command lookup by name, alias, or category
Execution: Context-aware command execution with validation
Completion: Autocompletion support for interactive interfaces
- Parameters:
commands (Dict[str, Command]) – Internal command storage by name
aliases (Dict[str, str]) – Alias to command name mapping for shortcuts
console (Console) – Rich console for formatted output and error display
Note
The registry is designed as a singleton pattern accessed through get_command_registry() for consistent command state across interfaces.
Warning
Command names and aliases must be unique across the registry. Registration will raise ValueError for conflicts.
Examples
Basic registry usage:
registry = CommandRegistry() # Register a custom command registry.register(Command( name="status", category=CommandCategory.SERVICE, handler=status_handler, help_text="Show service status" )) # Execute a command result = await registry.execute("/status", context)
Command discovery:
# Get all CLI commands cli_commands = registry.get_commands_by_category(CommandCategory.CLI) # Check if command exists if registry.has_command("help"): cmd = registry.get_command("help")
- register(command)[source]#
Register a command in the registry with validation and alias handling.
Registers a new command in the central registry, performing validation to ensure command names and aliases are unique. The registration process includes conflict detection, alias mapping, and command metadata storage for subsequent discovery and execution.
- Parameters:
command (Command) – Command instance with complete metadata and handler
- Raises:
ValueError – If command name is empty or conflicts with existing commands
ValueError – If command aliases conflict with existing commands or aliases
Note
Commands are validated for completeness and uniqueness before registration. All aliases are automatically mapped to the primary command name.
Examples
Register a simple command:
registry.register(Command( name="status", category=CommandCategory.SERVICE, handler=status_handler, help_text="Show service status" ))
Register command with aliases:
registry.register(Command( name="help", aliases=["h", "?"], category=CommandCategory.CLI, handler=help_handler, help_text="Show command help" ))
- get_commands_by_category(category)[source]#
Get all commands in a specific category.
- Return type:
list[Command]
- get_all_commands(include_hidden=False)[source]#
Get all registered commands.
- Return type:
list[Command]
- get_completions(prefix, context=None)[source]#
Get command completions for a given prefix.
- Return type:
list[str]
- async execute(command_line, context)[source]#
Execute a command from a command line.
- Return type:
CommandResult | dict[str, Any]
Command Types#
- class osprey.commands.Command(name, category, description, handler, aliases=<factory>, help_text=None, syntax=None, requires_args=False, valid_options=None, interface_restrictions=None, hidden=False, deprecated=False)[source]#
Bases:
objectComplete specification for a slash command with metadata and execution constraints.
The Command class provides a comprehensive definition for slash commands in the Osprey Framework. It includes execution handlers, validation constraints, interface restrictions, and rich metadata for help generation and autocompletion.
Command Lifecycle:
Definition: Command created with required fields and optional metadata
Registration: Command registered in CommandRegistry with validation
Discovery: Command discovered through registry lookup and filtering
Execution: Command executed with context and argument validation
Completion: Command provides autocompletion suggestions
Core Components:
Required Fields: name, category, description, handler for basic functionality
Metadata: aliases, help_text, syntax for user experience and documentation
Constraints: requires_args, valid_options, interface_restrictions for validation
Display: hidden, deprecated flags for command visibility and lifecycle
- Parameters:
name (str) – Unique command identifier used for registration and execution
category (CommandCategory) – Command category for organization and filtering
description (str) – Brief description for help text and documentation
handler (CommandHandler) – Function or callable that executes the command logic
aliases (List[str]) – Alternative names for the command (shortcuts, compatibility)
help_text (Optional[str]) – Detailed help text with usage examples and options
syntax (Optional[str]) – Command syntax pattern for help display and validation
requires_args (bool) – Whether the command requires arguments to execute
valid_options (Optional[List[str]]) – List of valid argument values for validation
interface_restrictions (Optional[List[str]]) – List of interfaces where command is available
hidden (bool) – Whether command is hidden from help and autocompletion
deprecated (bool) – Whether command is deprecated (shown with warning)
Examples
Simple command definition:
command = Command( name="status", category=CommandCategory.SERVICE, description="Show service status", handler=status_handler )
Command with validation and help:
command = Command( name="planning", category=CommandCategory.AGENT_CONTROL, description="Control planning mode", handler=planning_handler, aliases=["plan"], valid_options=["on", "off", "enabled", "disabled"], help_text="Enable or disable planning mode.\n\nOptions:\n on/enabled - Enable planning\n off/disabled - Disable planning", interface_restrictions=["cli", "openwebui"] )
Hidden administrative command:
command = Command( name="internal_debug", category=CommandCategory.CUSTOM, description="Internal debugging command", handler=debug_handler, hidden=True, requires_args=True )
- name: str#
- category: CommandCategory#
- description: str#
- handler: CommandHandler#
- aliases: list[str]#
- help_text: str | None = None#
- syntax: str | None = None#
- requires_args: bool = False#
- valid_options: list[str] | None = None#
- interface_restrictions: list[str] | None = None#
- deprecated: bool = False#
- __post_init__()[source]#
Initialize computed fields and auto-generate missing metadata.
Automatically generates help_text from description if not provided, and creates syntax patterns based on valid_options and requires_args settings for consistent command documentation and validation.
- is_valid_for_interface(interface_type)[source]#
Check if command is valid for the given interface type.
Validates whether the command can be executed in the specified interface based on interface_restrictions. Commands without restrictions are available in all interfaces.
- Parameters:
interface_type (str) – Interface identifier (“cli”, “openwebui”, “api”, etc.)
- Returns:
True if command is available in the interface, False otherwise
- Return type:
bool
Examples
Check CLI availability:
if command.is_valid_for_interface("cli"): # Command can be used in CLI pass
- validate_option(option)[source]#
Validate command arguments against defined constraints.
Performs validation of command arguments based on requires_args and valid_options settings. Used by the command registry to ensure proper command usage before execution.
- Parameters:
option (Optional[str]) – Command argument to validate (None if no argument provided)
- Returns:
True if argument is valid, False if validation fails
- Return type:
bool
- Validation Rules:
If requires_args=True, option cannot be None
If valid_options is set, option must be in the list
If no constraints, any option (including None) is valid
Examples
Validate planning command:
# Command with valid_options=["on", "off"] command.validate_option("on") # True command.validate_option("invalid") # False command.validate_option(None) # True (optional)
- __init__(name, category, description, handler, aliases=<factory>, help_text=None, syntax=None, requires_args=False, valid_options=None, interface_restrictions=None, hidden=False, deprecated=False)#
- class osprey.commands.CommandContext(interface_type='unknown', user_id=None, session_id=None, cli_instance=None, console=None, agent_state=None, gateway=None, config=None, service_instance=None, extra=<factory>)[source]#
Bases:
objectExecution context information available to command handlers.
CommandContext provides rich contextual information to command handlers, enabling context-aware command execution with access to interface state, agent configuration, and service instances. The context supports multiple interface types while maintaining type safety and extensibility.
- Context Categories:
Interface Context: Interface type, user identification, session management CLI Context: CLI instance access, console output, terminal control Agent Context: Current agent state, gateway access, configuration Service Context: Service instance access, deployment information Extension Context: Custom context data for application-specific commands
- Parameters:
interface_type (str) – Interface identifier (“cli”, “openwebui”, “api”, etc.)
user_id (Optional[str]) – User identifier for multi-user interfaces
session_id (Optional[str]) – Session identifier for state management
cli_instance (Optional[Any]) – CLI interface instance for direct access
console (Optional[Any]) – Rich console instance for formatted output
agent_state (Optional[Dict[str, Any]]) – Current agent state for state-aware commands
gateway (Optional[Any]) – Gateway instance for message processing
config (Optional[Dict[str, Any]]) – Framework configuration for service access
service_instance (Optional[Any]) – Service instance for service-specific commands
extra (Dict[str, Any]) – Additional context data for custom extensions
Note
Context fields are populated based on the executing interface and command category. Not all fields are available in all contexts.
Examples
CLI command context:
context = CommandContext( interface_type="cli", cli_instance=cli, console=rich_console, agent_state=current_state )
Service command context:
context = CommandContext( interface_type="api", service_instance=jupyter_service, config=framework_config )
- interface_type: str = 'unknown'#
- user_id: str | None = None#
- session_id: str | None = None#
- cli_instance: Any | None = None#
- console: Any | None = None#
- agent_state: dict[str, Any] | None = None#
- gateway: Any | None = None#
- config: dict[str, Any] | None = None#
- service_instance: Any | None = None#
- extra: dict[str, Any]#
- __init__(interface_type='unknown', user_id=None, session_id=None, cli_instance=None, console=None, agent_state=None, gateway=None, config=None, service_instance=None, extra=<factory>)#
- class osprey.commands.CommandResult(value)[source]#
Bases:
EnumStandardized result types for command execution flow control.
Command results enable interfaces to coordinate execution flow and handle different command outcomes appropriately. Results provide clear semantics for command processing continuation, state changes, and interface control.
- Results:
CONTINUE: Command processed, continue with normal message flow HANDLED: Command fully processed, stop further message processing EXIT: Request interface termination (CLI exit, session end) AGENT_STATE_CHANGED: Agent control state modified, may affect execution
Note
Interfaces should handle each result type appropriately based on their execution model and user experience requirements.
- CONTINUE = 'continue'#
- HANDLED = 'handled'#
- EXIT = 'exit'#
- AGENT_STATE_CHANGED = 'agent_state_changed'#
- class osprey.commands.CommandCategory(value)[source]#
Bases:
EnumCategories of slash commands for organization and interface validation.
Command categories provide hierarchical organization and enable interface-specific command filtering. Each category represents a distinct functional domain with specific execution contexts and validation requirements.
- Categories:
CLI: Interface and user experience commands (help, clear, exit, history) AGENT_CONTROL: Agent behavior and execution control (planning, approval, debug) SERVICE: Framework service management (status, logs, metrics, restart) CUSTOM: Application-specific and user-defined extensions
Note
Categories are used for command discovery, autocompletion filtering, and interface-specific command availability validation.
- CLI = 'cli'#
- AGENT_CONTROL = 'agent'#
- SERVICE = 'service'#
- CUSTOM = 'custom'#
Registry Functions#
- async osprey.commands.execute_command(command_line, context)[source]#
Execute a command globally.
- Return type:
CommandResult | dict[str, Any]
Command Categories#
- osprey.commands.register_cli_commands(registry)[source]#
Register CLI interface commands for user experience and interface control.
Registers essential CLI commands that provide user interface control, help systems, and session management. These commands are designed for interactive terminal interfaces and provide rich formatted output using the Rich library.
- Registered Commands:
/help [command]: Display available commands or detailed help for specific command /exit, /quit: Exit the current CLI session /clear: Clear the terminal screen
- Parameters:
registry (CommandRegistry) – Command registry instance for command registration
Note
CLI commands are interface-specific and may not be available in non-interactive contexts like OpenWebUI or API interfaces.
Examples
Command usage in CLI:
/help # Show all available commands /help planning # Show detailed help for planning command /clear # Clear terminal screen /exit # Exit CLI session
- osprey.commands.register_agent_control_commands(registry)[source]#
Register agent control commands for behavior and execution management.
Registers commands that control agent execution behavior, planning modes, approval workflows, and performance optimizations. These commands modify the agent control state and affect how the framework processes requests and executes capabilities.
- Registered Commands:
/planning:on|off: Enable or disable planning mode for execution coordination /approval:enabled|disabled|selective: Control human approval workflows /task:on|off: Control task extraction bypass for performance /caps:on|off: Control capability selection bypass for performance
- Parameters:
registry (CommandRegistry) – Command registry instance for command registration
Note
Agent control commands return state change dictionaries instead of CommandResult values. These changes are applied to the agent control state.
Warning
Agent control changes affect framework behavior and should be used carefully in production environments.
Examples
Agent control usage:
/planning:on # Enable planning mode /approval:selective # Enable selective approval /task:off # Bypass task extraction for performance /caps:off # Bypass capability selection for performance
Usage Examples#
Basic Command Execution#
from osprey.commands import get_command_registry, CommandContext
# Get the global registry
registry = get_command_registry()
# Create execution context
context = CommandContext(
interface_type="cli",
console=console
)
# Execute a command
result = await registry.execute("/help", context)
Custom Command Registration#
from osprey.commands import Command, CommandCategory, CommandResult
def my_handler(args: str, context: CommandContext) -> CommandResult:
context.console.print(f"Custom command executed with args: {args}")
return CommandResult.HANDLED
# Register custom command
registry = get_command_registry()
registry.register(Command(
name="custom",
category=CommandCategory.CUSTOM,
description="My custom command",
handler=my_handler,
help_text="Execute custom functionality"
))
Interface Integration#
# CLI interface integration
context = CommandContext(
interface_type="cli",
cli_instance=cli,
console=rich_console
)
# OpenWebUI interface integration
context = CommandContext(
interface_type="openwebui",
user_id="user123",
session_id="session456"
)
# Execute commands with appropriate context
result = await registry.execute(user_input, context)
See also
- CLI Reference
CLI usage and available slash commands
- Gateway Architecture
Gateway integration with command system
- State Management Architecture
Agent state management for command execution