Module Structure

Agent Air is organized into four top-level modules, each with a distinct responsibility. This page documents the internal structure of each module and the key types they export.

Top-Level Organization

src/
├── lib.rs              # Crate root, re-exports public API
├── agent/              # Agent infrastructure and configuration
├── controller/         # LLM session management and tool execution
├── client/             # HTTP client and LLM provider implementations
└── tui/                # Terminal UI components and application

The crate root (lib.rs) defines four public modules:

pub mod agent;      // Agent infrastructure and configuration
pub mod client;     // LLM client interface and providers
pub mod controller; // LLM session controller and tool execution
pub mod tui;        // Terminal UI components and application

Agent Module

The agent module provides the core infrastructure for building LLM-powered agents.

File Structure

agent/
├── mod.rs          # Module exports and re-exports
├── config.rs       # AgentConfig trait and configuration loading
├── core.rs         # AgentAir struct and lifecycle management
├── error.rs        # AgentError type definitions
├── logger.rs       # Tracing-based logging infrastructure
├── messages.rs     # UiMessage enum and channel definitions
└── router.rs       # InputRouter for message routing

Key Exports

TypeDescription
AgentAirCentral orchestration struct that initializes all components
AgentConfigTrait for agent configuration (paths, prompts, name)
AgentErrorError type for agent-level operations
UiMessageEnum of messages sent from controller to TUI
InputRouterRoutes messages from TUI to controller
LoggerLogging infrastructure using tracing
LLMRegistryRegistry of configured LLM providers

Channel Type Aliases

pub type ToControllerTx = mpsc::Sender<ControllerInputPayload>;
pub type ToControllerRx = mpsc::Receiver<ControllerInputPayload>;
pub type FromControllerTx = mpsc::Sender<UiMessage>;
pub type FromControllerRx = mpsc::Receiver<UiMessage>;

Re-exports

The agent module re-exports commonly used controller types for convenience:

pub use crate::controller::{
    ControllerEvent, ControllerInputPayload, LLMController,
    LLMSessionConfig, PermissionRegistry, ToolResultStatus,
    TurnId, UserInteractionRegistry,
};

Controller Module

The controller module manages LLM interactions, session state, and tool execution.

File Structure

controller/
├── mod.rs              # Module exports
├── error.rs            # ControllerError type
├── llm_controller.rs   # Main LLMController with event loop
├── session/            # Session management
│   ├── mod.rs
│   ├── session.rs      # LLMSession struct
│   ├── manager.rs      # LLMSessionManager for multi-session
│   ├── config.rs       # LLMSessionConfig and CompactionConfig
│   └── compactor.rs    # ThresholdCompactor implementation
├── stateless/          # Stateless execution support
│   ├── mod.rs
│   ├── executor.rs     # StatelessExecutor
│   └── types.rs        # StatelessConfig, StatelessResult
├── tools/              # Tool execution framework
│   ├── mod.rs
│   ├── types.rs        # Executable trait, ToolContext, DisplayConfig
│   ├── executor.rs     # ToolExecutor for parallel execution
│   ├── registry.rs     # ToolRegistry for tool management
│   ├── ask_user_questions.rs    # Built-in user interaction tool
│   ├── ask_for_permissions.rs   # Built-in permission tool
│   └── web_search.rs            # Built-in web search tool
├── types/              # Core type definitions
│   ├── mod.rs
│   ├── enums.rs        # InputType, ControlCmd, MessageRole, etc.
│   ├── payload.rs      # ControllerEvent, ControllerInputPayload
│   ├── turnid.rs       # TurnId and TurnCounter
│   ├── message.rs      # Message enum
│   └── content.rs      # ContentBlock types
└── usage/              # Token tracking
    ├── mod.rs
    └── tracker.rs      # TokenUsageTracker

Key Exports

Core Controller Types:

TypeDescription
LLMControllerMain controller with 6-channel event loop
ControllerErrorError type for controller operations
ControllerEventEvents emitted by controller (streaming, tools, etc.)
ControllerInputPayloadMessages from TUI to controller

Session Types:

TypeDescription
LLMSessionSingle LLM conversation session
LLMSessionManagerManages multiple concurrent sessions
LLMSessionConfigSession configuration (model, system prompt, etc.)
CompactionConfigContext window compaction settings
SessionStatusSession state (idle, streaming, etc.)

Tool Types:

TypeDescription
ExecutableTrait for implementing tools
ToolExecutorExecutes tools in parallel
ToolRegistryRegistry for tool handlers
ToolContextContext passed to tool execution
ToolResultResult of tool execution
DisplayConfigTool display customization

Message Types:

TypeDescription
MessageLLM message (user or assistant)
ContentBlockText, tool use, or tool result content
TurnIdIdentifies message turns (u1, a1, u2, a2)
InputTypeData or Control input type
ControlCmdControl commands (Interrupt, Shutdown, etc.)

Registry Types:

TypeDescription
UserInteractionRegistryManages pending user questions
PermissionRegistryManages pending permission requests
PermissionRequestPermission request details
AskUserQuestionsRequestUser question request details

Client Module

The client module provides HTTP communication with LLM providers.

File Structure

client/
├── mod.rs              # LLMClient struct and module exports
├── error.rs            # LlmError type
├── http.rs             # HttpClient with TLS and retry logic
├── models.rs           # Message, MessageOptions, StreamEvent
├── traits.rs           # LlmProvider trait
└── providers/          # Provider implementations
    ├── mod.rs
    ├── anthropic.rs    # Anthropic Claude API
    └── openai.rs       # OpenAI GPT API

Key Exports

TypeDescription
LLMClientMain client struct for LLM communication
LlmProviderTrait for implementing LLM providers
LlmErrorError type for LLM operations
HttpClientHTTP client with TLS support
MessageRequest/response message model
MessageOptionsOptions for message requests
StreamEventStreamed response event

LLMClient Interface

pub struct LLMClient {
    http_client: HttpClient,
    provider: Box<dyn LlmProvider + Send + Sync>,
}

impl LLMClient {
    pub fn new(provider: Box<dyn LlmProvider + Send + Sync>) -> Result<Self, LlmError>;
    pub async fn send_message(&self, messages: &[Message], options: &MessageOptions) -> Result<Message, LlmError>;
    pub async fn send_message_stream(&self, messages: &[Message], options: &MessageOptions)
        -> Result<Pin<Box<dyn Stream<Item = Result<StreamEvent, LlmError>> + Send>>, LlmError>;
}

TUI Module

The tui module provides terminal UI components built on Ratatui.

File Structure

tui/
├── mod.rs              # Module exports and re-exports
├── app.rs              # App struct and main event loop
├── markdown.rs         # Markdown rendering utilities
├── table.rs            # Table rendering utilities
├── commands/           # Slash command system
│   ├── mod.rs
│   ├── traits.rs       # SlashCommand trait
│   ├── registry.rs     # CommandRegistry
│   └── standard.rs     # Built-in commands (quit, help, clear, etc.)
├── keys/               # Key handling
│   ├── mod.rs
│   ├── handler.rs      # KeyHandler trait, DefaultKeyHandler
│   ├── bindings.rs     # KeyBindings configuration
│   └── types.rs        # KeyEvent, KeyContext, AppKeyAction
├── layout/             # Layout system
│   ├── mod.rs
│   ├── template.rs     # LayoutTemplate system
│   ├── standard.rs     # Standard layout with panels
│   ├── minimal.rs      # Minimal layout
│   └── helpers.rs      # Layout utilities
├── themes/             # Theme system
│   ├── mod.rs
│   ├── theme.rs        # Theme struct and colors
│   └── themes/         # 45+ built-in theme definitions
└── widgets/            # UI widgets
    ├── mod.rs
    ├── chat.rs         # ChatView for message display
    ├── input.rs        # TextInput for user input
    ├── status_bar.rs   # Status bar widget
    ├── permission_panel.rs  # Permission request UI
    ├── question_panel.rs    # User question UI
    ├── session_picker.rs    # Session selection UI
    └── slash_popup.rs       # Slash command autocomplete

Key Exports

Application:

TypeDescription
AppMain application struct
AppConfigApplication configuration

Widgets:

TypeDescription
ChatViewChat message display with streaming
TextInputText input with cursor management
StatusBarStatus bar with token counts
PermissionPanelPermission request UI
QuestionPanelUser question UI
ConversationViewTrait for custom chat views

Commands:

TypeDescription
SlashCommandTrait for implementing commands
CommandRegistryCommand lookup and execution
CommandContextContext passed to command execution
CommandResultResult of command execution

Key Handling:

TypeDescription
KeyHandlerTrait for custom key handling
DefaultKeyHandlerStandard key handler
KeyBindingsConfigurable key bindings
ExitHandlerTrait for exit cleanup

Layout:

TypeDescription
LayoutTemplateLayout configuration
LayoutProviderTrait for custom layouts
LayoutContextContext for layout rendering

Themes:

TypeDescription
ThemeTheme colors and styles
ThemeInfoTheme metadata (name, description)
THEMESStatic map of built-in themes

Import Patterns

For Agent Developers

Most functionality is available through the agent module:

use agent_air::agent::{
    AgentAir, AgentConfig, AgentError,
    UiMessage, ControllerEvent, TurnId,
};

For Tool Developers

Import from the controller module:

use agent_air::controller::{
    Executable, ToolContext, ToolResult,
    DisplayConfig, DisplayResult,
};

For TUI Customization

Import from the tui module:

use agent_air::tui::{
    App, Theme, LayoutTemplate,
    SlashCommand, KeyHandler, Widget,
};

For Custom Providers

Import from the client module:

use agent_air::client::{
    LLMClient, LlmProvider, LlmError,
    Message, MessageOptions, StreamEvent,
};

Next Steps