Overview
Junkie is built on a multi-layered architecture that orchestrates AI agents to handle complex Discord interactions. The system integrates:- Agent Teams - Coordinated groups of specialized AI agents
- Context Management - PostgreSQL-backed message caching and history
- Tool Integration - E2B sandboxes, MCP servers, and search APIs
- Discord Integration - Event-driven message handling and backfill
Core Components
1. Team Orchestration Layer
The team orchestration is managed byagent_factory.py, which provides:
- LRU cache for team instances (
MAX_AGENTSlimit) - Per-user team isolation with async locks
- Automatic resource cleanup on eviction
- MCP connection lifecycle management
2. Message Processing Flow
chat_handler.py coordinates this flow:3. Database Layer
PostgreSQL stores conversation history with optimized indexing:database.py:36-64
4. Context Building
The context cache (context_cache.py) implements a two-tier retrieval strategy:
- Primary: Fetch from PostgreSQL (fast, persistent)
- Fallback: Fetch from Discord API and cache
Data Flow
Startup Sequence
-
Bot Ready (
chat_handler.py:53-96)- Initialize database pool
- Connect MCP tools
- Start backfill task for all channels
- Sync recent messages to catch offline edits
-
Message Events
on_message: Append to cache, process chatbot commandson_message_edit: Update cacheon_message_delete: Remove from cache
Request Lifecycle
chat_handler.py:116-178
Resource Management
Team Cache Eviction
When the cache exceedsMAX_AGENTS, the oldest team is evicted:
agent_factory.py:376-408
Database Connection Pooling
database.py:9-28
Execution Context
Tools access the current Discord channel via context variables:execution_context.py:4-15
This enables tools like HistoryTools to read messages from the current conversation context.
Configuration
Key environment variables:MAX_AGENTS- Maximum cached teams (LRU eviction)TEAM_LEADER_CONTEXT_LIMIT- Max messages in contextPOSTGRES_URL- Database connection stringCONTEXT_AGENT_MAX_MESSAGES- Max messages in cacheBACKFILL_MAX_FETCH_LIMIT- Max messages per backfill fetch