Core Agent Loop and Tools
Relevant source files
The following files were used as context for generating this wiki page:The agent system is a foundational module for building interactive, tool-using AI applications within the project. It provides a generic Agent class that manages state, orchestrates an event-driven loop for interacting with LLMs, and executes tools. This core is leveraged by different applications, such as the coding-agent CLI and the mom Slack bot, each providing a specific implementation and user interface around the central agent logic.
The architecture is designed to be extensible, allowing different LLM providers, tools, and persistence mechanisms to be plugged in. The agent communicates its state and progress through a series of events, which UI components like the TuiRenderer subscribe to for displaying real-time updates.
Agent Architecture
The agent system is composed of several key components that work together to process user prompts and execute tasks.
This diagram shows the high-level components of the agent architecture, from the UI layer down to the LLM API.
Sources: packages/coding-agent/src/main.ts:822-853, packages/mom/src/agent.ts:503-516
Key Components
| Component | Description | Source Files |
|---|---|---|
Agent | The main class that orchestrates the entire process. It manages state, handles the event loop, and calls the LLM provider. | packages/coding-agent/src/main.ts:822 |
AgentState | An object containing the current state of the agent, including messages, system prompt, selected model, and tools. | packages/coding-agent/src/tui/tui-renderer.ts:403 |
ProviderTransport | An abstraction for communicating with different LLM APIs (e.g., Anthropic, OpenAI). It is responsible for fetching the correct API key. | packages/coding-agent/src/main.ts:833-853 |
| Tools | A collection of functions the agent can execute, such as bash, read, write, and edit. Each tool has a defined name, description, and parameter schema. | packages/coding-agent/src/tools/index.ts, packages/mom/src/tools/index.js |
SessionManager / ChannelStore | Responsible for persisting the agent's state, including message history (log.jsonl) and memory (MEMORY.md), to the filesystem. | packages/coding-agent/src/session-manager.ts, packages/mom/src/agent.ts:38 |
Agent Lifecycle and Event Flow
The agent operates on an event-driven loop that begins when a user submits a prompt. The Agent class emits a series of events that consumers (like a TUI or a Slack bot handler) can subscribe to in order to react to state changes.
The following sequence diagram illustrates the typical flow of an agent run that involves a tool call.
Agent Events
The agent's execution is communicated through a series of events. UI components subscribe to these to provide real-time feedback.
| Event | Description |
|---|---|
agent_start | Fired when agent.prompt() is called. |
message_start | Fired when a new message (user or assistant) begins. |
message_update | Fired as content (text, thinking, tool calls) streams from the LLM. |
message_end | Fired when a message is complete. Contains the final content and stop reason. |
tool_execution_start | Fired just before a tool is executed. |
tool_execution_end | Fired after a tool finishes, containing the result or an error. |
agent_end | Fired when the entire agent run is complete. |
Sources: packages/coding-agent/src/tui/tui-renderer.ts:445-608, packages/mom/src/agent.ts:645-843
System Prompt Construction
A critical part of the agent's setup is the dynamic construction of the system prompt. This prompt provides the LLM with essential context about its environment, capabilities, and operational guidelines.
The buildSystemPrompt function in both coding-agent and mom aggregates several pieces of information:
- Core Identity and Guidelines: A base prompt defining the agent's persona (e.g., "expert coding assistant" or "mom, a Slack bot assistant").
- Tool Descriptions: A list of available tools and their functions.
- Environment Details: Information about the execution environment, such as the current working directory and whether it's running in Docker.
- Workspace Layout: A description of the directory structure the agent can access.
- Memory: Content from
MEMORY.mdfiles (both global and channel-specific) is injected to provide long-term context. - Context Files: Project-specific context from files like
AGENTS.mdorCLAUDE.mdfound in the current directory or parent directories. - Date and Time: The current date and time.
This diagram illustrates the process in the mom agent.
Tooling
Tools are a central feature, enabling the agent to interact with the file system, execute commands, and perform other actions.
Standard Tools
Both the coding-agent and mom implementations share a common set of core tools.
| Tool Name | Description | Implementations |
|---|---|---|
bash | Execute shell commands. This is the primary tool for arbitrary actions. | coding-agent, mom |
read | Read file contents, with support for truncation and pagination. | coding-agent, mom |
write | Create or overwrite files. | coding-agent, mom |
edit | Perform surgical find-and-replace edits on files. | coding-agent, mom |
grep | Search file contents for patterns. | coding-agent |
find | Find files by glob pattern. | coding-agent |
ls | List directory contents. | coding-agent |
attach | Share files from the agent's workspace back to Slack. | mom |
Sources: packages/coding-agent/src/tools/index.ts:11-17, packages/mom/src/tools/index.js, packages/coding-agent/test/tools.test.ts
Tool Management
The coding-agent includes a tools-manager to ensure that external binary dependencies for certain tools (like fd for file searching) are available. If a tool is not found in the system's PATH, it attempts to download a compatible binary into a local tools directory.
This process involves:
- Checking if the tool exists in the local tools directory or system
PATH. - If not found, fetching the latest release version from the tool's GitHub repository.
- Constructing the correct asset URL for the user's platform and architecture.
- Downloading and extracting the binary.
- Making the binary executable.
Sources: packages/coding-agent/src/tools-manager.ts:108-164
Custom CLI Tools ("Skills")
The mom agent introduces the concept of "Skills," which are custom CLI tools the agent can create and reuse for recurring tasks. These are stored in the workspace and documented in MEMORY.md so the agent can remember how to use them. This allows the agent to be extended with new capabilities over time, such as interacting with email or other APIs.
Sources: packages/mom/README.md:118-147, packages/mom/src/agent.ts:303-309
Context and State Persistence
The agents are designed to be stateless within a single run, but they persist context across runs using a dedicated workspace directory.
Workspace Directory
Both agents operate within a defined data directory. This directory contains all artifacts related to their operation, ensuring persistence and providing a transparent view into the agent's work.
A typical structure for the mom agent's data directory is:
./data/
├── MEMORY.md # Global memory (all channels)
├── skills/ # Global custom CLI tools
└── C123ABC/ # Directory for a specific Slack channel
├── MEMORY.md # Channel-specific memory
├── log.jsonl # Full message history for the channel
├── attachments/ # User-shared files
├── scratch/ # Agent's working directory
└── skills/ # Channel-specific tools
Sources: packages/mom/README.md:94-106
Message History
All messages, including user prompts, assistant responses, and tool I/O, are logged to a log.jsonl file within the relevant session or channel directory. This provides a complete audit trail and allows the agent to retrieve historical context beyond the immediate conversation window by querying this file.
The mom agent implements a "turn-based" context retrieval system, where it fetches the last 50 "turns" (a user message or a sequence of bot messages) to build its prompt context, which is more efficient than using a raw line count.
Sources: packages/mom/src/agent.ts:70-150, packages/mom/README.md:171-188
Context Compaction
The coding-agent features an advanced context management strategy called "compaction." When the conversation history grows too large for the model's context window, the compact function is triggered. It uses an LLM to summarize the older parts of the conversation, replacing a long series of messages with a concise summary. This allows the agent to maintain long-term context without overflowing the prompt. This can be triggered manually (/compact) or automatically when context usage exceeds a configured threshold.
Sources: packages/coding-agent/src/main.ts:1115-1144, packages/coding-agent/src/tui/tui-renderer.ts:1180-1237
Conclusion
The Core Agent Loop and Tools provide a robust and flexible foundation for building sophisticated AI assistants. The event-driven architecture allows for clean separation between the core logic and the UI, as demonstrated by its use in both a terminal-based coding assistant and a Slack bot. Key features like dynamic system prompts, extensible tooling, and advanced context management through persistence and compaction enable the agents to handle complex, long-running tasks effectively.