Architecture - djvolz/coda-code-assistant GitHub Wiki

Architecture Overview

Code References

  • Module structure: coda/ directory
  • CLI implementation: coda/cli/main.py, coda/cli/interactive_cli.py, coda/cli/command_registry.py
  • Provider system: coda/providers/base.py:94-130, coda/providers/registry.py:18-35
  • Agent framework: coda/agents/agent.py, coda/agents/decorators.py:7-47
  • Tool system: coda/tools/base.py:142-169, coda/tools/executor.py
  • Session management: coda/session/manager.py, coda/session/database.py

Introduction

Coda Code Assistant is a sophisticated command-line interface tool that provides interactive AI-powered assistance for software development tasks. This architecture documentation provides a comprehensive understanding of the system's design, components, and interactions based on analysis of the actual codebase.

System Overview

Coda Code Assistant follows a modular architecture pattern with clear separation of concerns. The system is organized into distinct layers as found in the coda/ directory structure:

graph TB
    subgraph "User Interface Layer"
        CLI[CLI Interface]
        Interactive[Interactive Mode]
    end
    
    subgraph "Core Layer"
        Session[Session Management]
        Commands[Command Registry]
        Context[Context Management]
    end
    
    subgraph "Provider Layer"
        Provider[Provider Interface]
        OCI[OCI GenAI]
        Ollama[Ollama]
        Mock[Mock Provider]
        LiteLLM[LiteLLM]
    end
    
    subgraph "Tools Layer"
        Tools[Tool Executor]
        FileTools[File Tools]
        GitTools[Git Tools]
        WebTools[Web Tools]
        ShellTools[Shell Tools]
        MCP[MCP Integration]
    end
    
    subgraph "Agent Layer"
        Agent[Agent Framework]
        BuiltinTools[Built-in Tools]
        FunctionTool[Function Tools]
    end
    
    CLI --> Commands
    Interactive --> Commands
    Commands --> Session
    Session --> Context
    Commands --> Provider
    Provider --> OCI
    Provider --> Ollama
    Provider --> Mock
    Provider --> LiteLLM
    Commands --> Tools
    Tools --> FileTools
    Tools --> GitTools
    Tools --> WebTools
    Tools --> ShellTools
    Tools --> MCP
    Commands --> Agent
    Agent --> BuiltinTools
    Agent --> FunctionTool
Loading

Core Design Principles

1. Modularity

  • Each component has a single, well-defined responsibility as evidenced by the directory structure
  • Modules communicate through clear interfaces (e.g., BaseProvider in coda/providers/base.py:94-130)
  • Dependencies are minimized and explicit through imports

2. Extensibility

  • Provider system allows easy addition of new AI providers via ProviderRegistry (coda/providers/registry.py:18-35)
  • Tool system supports plugin-style extensions through ToolRegistry (coda/tools/base.py:142-169)
  • Command registry enables dynamic command addition (coda/cli/command_registry.py)

3. Testability

  • Mock provider enables comprehensive testing (coda/providers/mock_provider.py)
  • Dependency injection facilitates unit testing throughout the codebase
  • Clear separation between business logic and I/O operations

4. User Experience

  • Interactive mode for conversational interactions (coda/cli/interactive_cli.py)
  • Rich command-line interface with color support via Theme system (coda/themes.py)
  • Comprehensive help and documentation system

High-Level Components

CLI Module (coda/cli/)

The command-line interface module handles user interactions, command parsing, and output formatting. It provides both one-shot command execution and interactive chat sessions.

Key Components (verified in codebase):

  • main.py: Entry point and argument parsing
  • interactive_cli.py: InteractiveCLI class implementation
  • command_registry.py: CommandRegistry class for dynamic command registration
  • chat_session.py: ChatSession class for managing conversations
  • shared/: Shared components including commands, help, and modes

Agents Module (coda/agents/)

The agent framework provides autonomous task execution capabilities with tool integration.

Key Components (verified in codebase):

  • agent.py: Core Agent class implementation
  • tool_adapter.py: MCPToolAdapter for tool integration
  • function_tool.py: FunctionTool class for function-based tools
  • decorators.py: @tool decorator implementation (lines 7-47)
  • builtin_tools.py: Pre-built tool implementations
  • types.py: Type definitions for the agent system

Providers Module (coda/providers/)

Abstracts different AI model providers behind a common interface defined in BaseProvider (base.py:94-130).

Key Components (verified in codebase):

  • base.py: BaseProvider abstract class (lines 94-130)
  • registry.py: ProviderRegistry singleton (lines 18-35)
  • litellm_provider.py: LiteLLM integration
  • ollama_provider.py: Ollama local model support
  • oci_genai.py: Oracle Cloud Infrastructure GenAI
  • mock_provider.py: Testing provider

Tools Module (coda/tools/)

Implements various tools that can be used by agents and chat sessions.

Key Components (verified in codebase):

  • base.py: BaseTool abstract class and ToolRegistry (lines 142-169)
  • executor.py: ToolExecutor for running tools with permissions
  • file_tools.py: File system operations
  • git_tools.py: Git repository operations
  • web_tools.py: Web interaction tools
  • shell_tools.py: Shell command execution
  • mcp_manager.py: MCP (Model Context Protocol) server integration

Session Module (coda/session/)

Manages conversation state, history, and persistence using SQLAlchemy.

Key Components (verified in codebase):

  • manager.py: SessionManager class for lifecycle management
  • database.py: SessionDatabase SQLite persistence layer
  • context.py: ContextManager for accumulating conversation context
  • models.py: SQLAlchemy ORM models for sessions and messages

Architecture Patterns

1. Registry Pattern

Used for dynamic registration of commands, providers, and tools. Enables plugin-style extensibility.

Implementation in coda/providers/registry.py:25-35:

def register(self, name: str, provider_class: Type[BaseProvider]) -> None:
    """Register a provider class."""
    self._providers[name] = provider_class

Implementation in coda/tools/base.py:149-157:

def register(self, tool: Type[BaseTool], category: Optional[str] = None) -> None:
    """Register a tool class."""
    tool_name = tool.name
    self._tools[tool_name] = tool

2. Strategy Pattern

Providers implement a common interface (BaseProvider in base.py:94-130), allowing runtime selection of AI backend.

Abstract strategy defined in coda/providers/base.py:108-118:

@abstractmethod
async def chat(
    self,
    messages: List[Dict[str, Any]],
    model: Optional[str] = None,
    **kwargs: Any
) -> AsyncIterator[str]:
    """Send chat messages to the provider."""

3. Decorator Pattern

Function tools use decorators for easy tool creation from regular functions.

Implementation in coda/agents/decorators.py:22-42: The @tool decorator wraps functions to add tool metadata and create FunctionTool instances.

Usage example from coda/agents/builtin_tools.py:12-15:

@tool(description="Get the current date and time")
def get_current_time() -> str:
    """Returns the current date and time."""
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

4. Chain of Responsibility

Tool execution follows a permission and validation chain before execution as implemented in ToolExecutor (coda/tools/executor.py).

Data Flow

Chat Interaction Flow

The following sequence diagram illustrates the actual flow as implemented in the codebase:

sequenceDiagram
    participant User
    participant CLI
    participant Session
    participant Provider
    participant Tools
    
    User->>CLI: Input command/message
    CLI->>Session: Create/Load session (SessionManager)
    Session->>Session: Add user message (database.py)
    CLI->>Provider: Send conversation (via ProviderRegistry)
    Provider->>Provider: Process with AI model
    
    alt Tool calls requested
        Provider->>Tools: Execute tool calls (ToolExecutor)
        Tools->>Tools: Validate permissions
        Tools->>Tools: Execute specific tool
        Tools->>Provider: Return results
        Provider->>Provider: Process with results
    end
    
    Provider->>CLI: Return response (streaming)
    CLI->>Session: Save assistant message
    Session->>Session: Persist to SQLite database
    CLI->>User: Display response (with theme formatting)
Loading

Deployment Architecture

Coda Code Assistant is designed as a standalone CLI application with minimal external dependencies:

graph LR
    subgraph "Local Machine"
        CLI[Coda CLI]
        DB[(SQLite DB)]
        Config[Config Files - config.toml]
    end
    
    subgraph "External Services"
        OCI[OCI GenAI API]
        Ollama[Ollama Server - Local]
        LiteLLM[LiteLLM Proxy]
        MCP[MCP Servers]
    end
    
    CLI --> DB
    CLI --> Config
    CLI --> OCI
    CLI --> Ollama
    CLI --> LiteLLM
    CLI --> MCP
Loading

Security Considerations

Based on code analysis:

  1. Tool Permissions: Granular permission system in coda/tools/permissions.py
  2. Provider Authentication: Secure credential management for API keys via environment variables
  3. Session Isolation: Each session maintains isolated context in SQLite database
  4. Input Validation: Validation throughout tool implementations

Performance Characteristics

Based on implementation analysis:

  1. Lazy Loading: Providers loaded on-demand via registry pattern
  2. Streaming Responses: Async iterators for streaming AI responses (all providers)
  3. Efficient Context Management: Context windowing in ContextManager
  4. Database Optimization: SQLite with proper indexing for session queries

Verification Checklist

  • All file paths verified to exist
  • All line numbers checked for accuracy
  • All class/function names validated
  • Code patterns verified with actual implementations
  • Module structure matches codebase reality

Next Steps

For detailed information about specific modules, see:

For integration documentation (Coming Soon):

  • Provider Integration Guide
  • Tool Development Guide
  • Agent Creation Guide
⚠️ **GitHub.com Fallback** ⚠️