src — src

Module: src-src Cohesion: 0.80 Members: 0

src — src

This document provides a comprehensive overview of the src/index.ts module, which serves as the main entry point for the Code Buddy CLI application. It covers the module's purpose, architecture, key components, execution flow, and its integration with other parts of the codebase.

src/index.ts: Code Buddy CLI Entry Point

The src/index.ts module is the heart of the Code Buddy CLI. It is responsible for:

Core Principles

  1. Lazy Loading for Performance: The most critical architectural decision in index.ts is the extensive use of lazy loading. Heavy modules (like React, Ink, OpenAI client, core agent logic, and most subcommands) are not imported at startup. Instead, they are loaded dynamically only when their functionality is explicitly requested (e.g., when the UI is rendered, or a specific subcommand is invoked). This drastically reduces the initial memory footprint and startup time.
  2. Robustness and Error Handling: The module includes comprehensive error handling for uncaught exceptions and unhandled promise rejections, leveraging a crash handler and graceful shutdown manager to attempt clean exits and session recovery.
  3. Configurability: Code Buddy prioritizes configurability through environment variables, user settings files (~/.codebuddy/user-settings.json), project-level settings (.codebuddy/settings.json), and command-line options, with a clear precedence order.
  4. Headless vs. Interactive Modes: The CLI seamlessly switches between an interactive terminal UI (powered by Ink/React) and a headless mode for scripting and automation, based on the presence of --prompt or piped input.

Startup Sequence

The startup sequence is carefully orchestrated to be as fast and resilient as possible:

  1. Early Initialization:

  1. Performance Tracking: recordStartupPhase is used to track the duration of key startup steps, which can be logged if PERF_TIMING or DEBUG environment variables are enabled.
  2. Lazy Import System Setup: The lazyLoad function and lazyImport object are defined. This is the core mechanism for deferring module imports.
  3. Environment Loading (ensureEnvLoaded): This asynchronous function loads .env files from the launch directory and current working directory. It also attempts to configure HTTP/HTTPS proxies based on environment variables. This is called early but lazily to ensure environment variables are available for subsequent configuration steps.
  4. Graceful Shutdown & Error Handling:

  1. Commander.js Setup: The program instance is initialized with name, description, and version.
  2. Command Registration:

CLI Command Handling

The index.ts module uses commander.js to define a rich command-line interface.

Main Command (codebuddy [message...] [options])

The primary program.action handler is responsible for the core Code Buddy experience.

graph TD
    A[program.action(message, options)] --> B{Apply --profile}
    B --> C{Handle --setup, --init, --list-models, --list-prompts, --list-agents, --continue, --resume}
    C -- Handled --> Z[Exit]
    C -- Not Handled --> D(Ensure Env Loaded & Change CWD)
    D --> E(Initialize Workspace Isolation)
    E --> F(Initialize Observability)
    F --> G(Load API Key, Base URL, Model)
    G --> H{Is it a Headless Run? (--prompt, piped input)}
    H -- Yes --> I(Call processPromptHeadless)
    I --> J(Call finalizeHeadlessRun & Exit)
    H -- No --> K(Initialize Renderers & Agent)
    K --> L(Handle Crash Recovery)
    L --> M(Lazy Load React, Ink, ChatInterface)
    M --> N(Render ChatInterface)
    N --> O(Start Background Tasks: Plugins, Updates, Tools.md, Preloading)
    O --> P(Wait for UI exit)
    P --> J

Key Logic within program.action:

Headless Mode (--prompt, --print, or piped input)

When a prompt is provided via --prompt, --print, or standard input (piped), Code Buddy enters headless mode.

Interactive Mode

If no explicit prompt is given, Code Buddy launches its interactive terminal UI.

Subcommands

Subcommands extend the CLI's functionality.

Configuration and State Management

Error Handling and Graceful Shutdown

The module is designed for resilience:

  1. Log the error.
  2. Use crashHandler to save context for potential session recovery.
  3. Initiate a graceful shutdown with an error exit code.
  4. As a last resort, force exit if graceful shutdown fails.

Key Functions and Data Structures

Connections to the Codebase

src/index.ts acts as the central orchestrator, connecting to almost every major subsystem of Code Buddy:

This module is the primary interface for users and the initial bootstrap for all Code Buddy operations, making its design crucial for performance, usability, and stability.