Architecture 1 CLI - djvolz/coda-code-assistant GitHub Wiki
- Primary implementation:
coda/cli/main.py - Interactive mode:
coda/cli/interactive_cli.py,coda/cli/interactive.py - Command registry:
coda/cli/command_registry.py - Chat session:
coda/cli/chat_session.py - Provider management:
coda/cli/provider_manager.py - Tests:
tests/cli/ - Shared components:
coda/cli/shared/
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.
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
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
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
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
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: coda/cli/command_registry.py
class CommandRegistry:
"""Central registry for all CLI commands."""
def __init__(self):
self.commands: Dict[str, CommandDefinition] = {}
self._initialize_commands()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."""
passImplementation: 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...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
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"
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
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
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
Config File: ~/.config/coda/config.toml
Config Class: coda/configuration.py:CodaConfig
| 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 |
-
coda.configuration: Configuration management -
coda.providers: AI provider implementations -
coda.session: Session persistence -
coda.themes: UI theming system -
coda.agents: Agent system for tools
-
click>=8.1.7: Command-line interface creation -
prompt_toolkit>=3.0.36: Rich terminal UI -
rich>=13.7.0: Terminal formatting and tables
- Unit tests:
tests/cli/test_interactive_cli.py - Integration tests:
tests/cli/test_interactive.py - Command tests:
tests/cli/test_basic_commands.py
- Interactive Mode Tests: Tests CLI initialization and commands
- Basic Mode Tests: Tests basic mode functionality
- Help System Tests: Tests help text generation
-
ProviderError: Provider initialization failures -
ConfigurationError: Missing configuration -
KeyboardInterrupt: Handled for clean exit
try:
provider = initialize_provider()
except ProviderError as e:
self.display_error(e) # User-friendly error display- Lazy Loading: Commands loaded on-demand
- Streaming Responses: AI responses streamed character by character
- Async I/O: Interactive mode uses async for responsiveness
- No Credential Storage: API keys read from environment variables
- Path Validation: File paths validated before operations
- Command Injection: No shell command execution without explicit tools
# One-shot query
coda chat "What is Python?"
# Interactive mode
coda chat
# With specific provider
coda chat --provider ollama --model llama3cli = InteractiveCLI(
provider=mock_provider,
config=config,
theme=Theme.get_theme("monokai")
)
result = await cli.process_slash_command("/help")- Provider Module: Provider initialization and management
- Session Module: Session persistence and restoration
- Agent Module: Tool execution and agent interactions
- Theme Module: Applied throughout UI rendering
-
New Commands: Add to
command_registry.pyregistry -
New Modes: Extend
shared/modes.pyenums -
Custom Completers: Implement completer in
interactive_cli.py
- Windows Support: Limited prompt-toolkit features on Windows
- Emoji Rendering: Requires terminal with emoji support
All files referenced in this document: