Skip to content

Architecture 1 CLI

Danny Volz edited this page Jul 9, 2025 · 3 revisions

CLI Module Architecture

Code References

Overview

The CLI module is responsible for the command-line interface of Coda Code Assistant. It provides both a basic mode for simple interactions and a rich interactive mode with auto-completion, themes, and advanced features. The main entry point is the main() function in coda/cli/main.py.

Module Structure

coda/cli/
├── __init__.py              # Module initialization
├── main.py                  # Entry point and basic mode
├── interactive.py           # Interactive mode runner
├── interactive_cli.py       # Interactive CLI implementation
├── chat_session.py          # Chat session management
├── command_registry.py      # Command definitions
├── provider_manager.py      # Provider initialization
├── error_handler.py         # Error handling
├── basic_commands.py        # Basic mode commands
├── agent_chat.py            # Agent integration
├── model_selector.py        # Model selection UI
├── theme_selector.py        # Theme selection UI
├── tool_chat.py            # Tool chat integration
└── shared/                  # Shared components
    ├── commands.py          # Command handler base
    ├── help.py             # Help formatting
    └── modes.py            # Developer modes

Key Components

Component 1: Entry Point

Location: coda/cli/main.py

Purpose: Main entry point that determines CLI mode and initializes the application

Key Functions:

  • main(): Click command that handles CLI arguments and mode selection
  • run_basic_mode(): Executes basic CLI mode without prompt-toolkit
  • show_welcome_banner(): Displays welcome message with version info

Component 2: Command Registry

Location: coda/cli/command_registry.py

Purpose: Centralized registry of all CLI commands with metadata and autocomplete support

Key Classes:

  • CommandType: Enum defining command categories
  • CommandDefinition: Dataclass for command metadata
  • CommandRegistry: Central registry managing all commands

Component 3: Interactive CLI

Location: coda/cli/interactive_cli.py

Purpose: Rich interactive interface with prompt-toolkit integration

Key Classes:

  • SlashCommand: Command representation
  • SlashCommandCompleter: Auto-completion provider
  • InteractiveCLI: Main interactive CLI implementation

Component 4: Chat Session

Location: coda/cli/chat_session.py

Purpose: Manages conversation flow for both basic and interactive modes

Key Methods:

  • stream_response(): Handles streaming AI responses
  • run_one_shot(): Single prompt execution
  • run_interactive(): Interactive chat loop

Implementation Details

Design Patterns Used

Registry Pattern

Implementation: coda/cli/command_registry.py

class CommandRegistry:
    """Central registry for all CLI commands."""
    
    def __init__(self):
        self.commands: Dict[str, CommandDefinition] = {}
        self._initialize_commands()

Command Pattern

Implementation: coda/cli/shared/commands.py

The command handler base class implements the command pattern:

class CommandHandler(ABC):
    """Abstract base class for command handling."""
    
    @abstractmethod
    async def handle_command(self, command: str, args: str) -> CommandResult:
        """Handle a command with arguments."""
        pass

Template Method Pattern

Implementation: coda/cli/shared/commands.py

Base class provides shared implementations that subclasses can use:

async def handle_mode_command(self, mode_name: str) -> CommandResult:
    """Shared implementation for mode switching."""
    # Implementation details...

Data Flow

sequenceDiagram
    participant User
    participant Main as main.py
    participant CLI as InteractiveCLI
    participant Registry as CommandRegistry
    participant Session as ChatSession
    participant Provider
    
    User->>Main: coda chat
    Main->>Main: Load configuration
    Main->>CLI: Initialize interactive mode
    CLI->>Registry: Load command definitions
    
    loop Interactive Session
        CLI->>User: Display prompt
        User->>CLI: Input message/command
        alt Slash Command
            CLI->>Registry: Lookup command
            CLI->>CLI: Execute command handler
        else Chat Message
            CLI->>Session: Process message
            Session->>Provider: Send to AI
            Provider->>Session: Stream response
            Session->>CLI: Display response
        end
    end
Loading

Class Hierarchy

classDiagram
    CommandHandler <|-- InteractiveCLI
    CommandHandler <|-- BasicCommands
    
    class CommandHandler {
        <<abstract>>
        +handle_command(command, args)
        +handle_mode_command(mode)
        +handle_model_command(args)
    }
    
    class InteractiveCLI {
        +get_input()
        +process_slash_command()
        +run()
    }
    
    class BasicCommands {
        +handle_command()
        +get_user_input()
    }
    
    note for CommandHandler "Base command handler class"
    note for InteractiveCLI "Rich interactive CLI implementation"
Loading

API Reference

Public Functions

main(basic: bool, provider: str, model: str, chat: tuple, one_shot: bool) -> None

Location: coda/cli/main.py

Purpose: Main CLI entry point

Parameters:

  • basic (bool): Use basic mode without prompt-toolkit
  • provider (str): Provider name to use
  • model (str): Model name to use
  • chat (tuple): Initial chat messages
  • one_shot (bool): Exit after first response

Public Classes

InteractiveCLI

Location: coda/cli/interactive_cli.py

Purpose: Rich interactive CLI with auto-completion and themes

Key Methods:

  • __init__(self, provider, config, theme): Constructor
  • get_input(self) -> Optional[str]: Get user input with features
  • process_slash_command(self, command: str) -> bool: Handle commands
  • run(self): Main interactive loop

ChatSession

Location: coda/cli/chat_session.py

Purpose: Manages chat conversations with AI providers

Key Methods:

  • __init__(self, provider, config, theme, mode): Constructor
  • stream_response(self, prompt: str): Stream AI response
  • run_interactive(self, handler): Interactive chat loop

Configuration

Config File: ~/.config/coda/config.toml Config Class: coda/configuration.py:CodaConfig

Configuration Options

Option Type Default Description
default_provider str "ollama" Default AI provider
theme str "monokai" UI color theme
autosave.enabled bool True Auto-save sessions
debug bool False Debug mode

Dependencies

Internal Dependencies

  • coda.configuration: Configuration management
  • coda.providers: AI provider implementations
  • coda.session: Session persistence
  • coda.themes: UI theming system
  • coda.agents: Agent system for tools

External Dependencies

  • click>=8.1.7: Command-line interface creation
  • prompt_toolkit>=3.0.36: Rich terminal UI
  • rich>=13.7.0: Terminal formatting and tables

Testing

Test Coverage

  • Unit tests: tests/cli/test_interactive_cli.py
  • Integration tests: tests/cli/test_interactive.py
  • Command tests: tests/cli/test_basic_commands.py

Key Test Cases

  1. Interactive Mode Tests: Tests CLI initialization and commands
  2. Basic Mode Tests: Tests basic mode functionality
  3. Help System Tests: Tests help text generation

Error Handling

Exception Types

  • ProviderError: Provider initialization failures
  • ConfigurationError: Missing configuration
  • KeyboardInterrupt: Handled for clean exit

Error Flow

try:
    provider = initialize_provider()
except ProviderError as e:
    self.display_error(e)  # User-friendly error display

Performance Considerations

  1. Lazy Loading: Commands loaded on-demand
  2. Streaming Responses: AI responses streamed character by character
  3. Async I/O: Interactive mode uses async for responsiveness

Security Considerations

  1. No Credential Storage: API keys read from environment variables
  2. Path Validation: File paths validated before operations
  3. Command Injection: No shell command execution without explicit tools

Examples

Basic Usage

# One-shot query
coda chat "What is Python?"

# Interactive mode
coda chat

# With specific provider
coda chat --provider ollama --model llama3

Advanced Usage

cli = InteractiveCLI(
    provider=mock_provider,
    config=config,
    theme=Theme.get_theme("monokai")
)
result = await cli.process_slash_command("/help")

Integration Points

With Other Modules

  1. Provider Module: Provider initialization and management
  2. Session Module: Session persistence and restoration
  3. Agent Module: Tool execution and agent interactions
  4. Theme Module: Applied throughout UI rendering

Extension Points

  1. New Commands: Add to command_registry.py registry
  2. New Modes: Extend shared/modes.py enums
  3. Custom Completers: Implement completer in interactive_cli.py

Known Limitations

  1. Windows Support: Limited prompt-toolkit features on Windows
  2. Emoji Rendering: Requires terminal with emoji support

References

Related Documentation

Source Files

All files referenced in this document:

Clone this wiki locally