Discord Bot Architecture
Last Updated: 2025-01-16
Primary Source: docs/project_status.md
Main File: discord-bot/src/index.ts
Supporting Files: discord-bot/src/backendClient.ts, discord-bot/src/registerCommands.ts, discord-bot/src/circuitBreaker.ts, discord-bot/src/config.ts
Overview
The Discord Bot provides a Discord interface for the ASO Universal Consciousness System. It handles message ingestion, slash commands, button interactions, and integrates with the backend API for state machine management, orchestrator operations, protocol management, and more.
Architecture
Discord Bot Flow
Core Components
1. Discord Bot Main
File: discord-bot/src/index.ts
Key Features:
- Discord.js client initialization
- Message event handling
- Interaction event handling
- Command routing
- Button interaction handling
- Channel context caching
Event Handlers:
handleMessage(message)
- Processes incoming Discord messages
- Checks if bot is mentioned or message is reply to bot
- Resolves channel context (protocol/machine)
- Sends message to backend
- Handles responses and splits long messages
handleInteraction(interaction)
- Routes slash commands to handlers
- Handles button interactions
- Processes command options
2. Backend Client
File: discord-bot/src/backendClient.ts
Purpose: Client for communicating with backend API
Key Functions:
sendDiscordMessage()- Send message to backendfetchChannelConfig()- Get channel configurationfetchStateMachineInstance()- Get state machine instancetransitionStateMachineInstance()- Transition staterecordInstanceApproval()- Record approvalrecordInstanceEvidence()- Record evidencerunInstanceOrchestrator()- Run orchestratorfetchInstanceTasks()- Get tasksfetchInstanceArtifacts()- Get artifactsfetchProtocolById()- Get protocollistProtocols()- List protocols- And many more...
3. Circuit Breaker
File: discord-bot/src/circuitBreaker.ts
Purpose: Prevents cascading failures when backend is down
Features:
- Circuit breaker pattern
- Failure threshold tracking
- Automatic recovery
- Fallback responses
4. Command Registration
File: discord-bot/src/registerCommands.ts
Purpose: Registers slash commands with Discord
Features:
- Command definition
- Command syncing
- Command validation
Slash Commands
Account Linking
/link
- Generates one-time link code
- Links Discord account to ASO account
- Returns code with expiration
Observer Configuration
/observer-config
Subcommands:
set- Set protocol/machine for channelinfo- Get channel configurationexport- Export protocol definitionexport-config- Export channel config
State Machine Management
/observer-instance instance_id:xxx
- View state machine instance details
- Shows machine, protocol, state, transitions
/observer-transition instance_id:xxx target_state:xxx reason:"..."
- Transition state machine
- Requires guards to be satisfied
- Triggers state actions
/flow-status instance_id:xxx
- Get current flow status
- Shows protocol, instance, phase, tasks, artifacts
- Lists available actions
/flow-diagram channel_id:xxx
- Generate flow diagram
- Shows phase timeline, navigation path, errors
/flow-back checkpoint_id:xxx or phase:xxx
- Return to checkpoint or phase
- Enables error recovery
Guard Management
/observer-approve instance_id:xxx notes:"..."
- Record observer approval
- Satisfies
observerApprovalguard - Triggers auto-advance if configured
/observer-evidence instance_id:xxx description:"..." proof_url:"..."
- Record verification evidence
- Satisfies
testsOrDemoAttachedguard - Triggers auto-advance if configured
Coder Orchestrator
/observer-orchestrate instance_id:xxx
- Trigger orchestrator execution
- Runs pending tasks
- Returns execution results
/observer-artifacts instance_id:xxx
- View tasks and artifacts
- Shows task status, persona assignments
- Lists artifacts with summaries
/observer-assign task_id:xxx persona_id:xxx status:xxx notes:"..."
- Reassign task to persona
- Update task status
- Add task notes
/observer-artifact-view artifact_id:xxx
- View full artifact content
- Syntax highlighting for code blocks
- Shows persona, status, creation date
/observer-artifact-review artifact_id:xxx approve:true notes:"..."
- Review artifact
- Approve or reject
- Add review notes
/observer-personas preset:xxx
- List available coder personas
- Filter by preset (documentation, triage, automations)
Protocol Management
/observer-protocol
Subcommands:
list- List all protocolsinfo- Get protocol detailshistory- View version historyexport- Export protocol (JSON/YAML)diff- Compare protocol versionsimport- Import protocol definitionupdate- Update protocolannotate- Annotate versiondeprecate- Deprecate protocolclone- Clone protocolapprove- Approve versionlatest- Get latest versionpending- List pending approvalsexport-machine- Export state machine
Ritual Management
/observer-ritual instance_id:xxx type:xxx
- View ritual memories
- Filter by type (gratitude, clarity_summary, etc.)
/observer-gratitude instance_id:xxx message:"..." mention:"..."
- Record gratitude ritual
- Stores as protocol memory
System Settings
/settings
Subcommands:
list- List public settingsget key:xxx- Get setting valueset key:xxx value:xxx- Set setting value
Search
/search query:"..."
- Perform web search
- Triggers backend web search
- Returns search results
Button Interactions
Button Types
Action Buttons
- Execute actions
- View artifacts
- Approve guards
- Transition states
Cancel Buttons
- Cancel suggestions
- Ephemeral responses
Ask Questions Buttons
- Request clarification
- Ephemeral responses
Button Handling
Function: handleButtonInteraction(interaction)
Process:
- Defer reply immediately (within 3 seconds)
- Execute button action via backend
- Update interaction with result
- Handle long messages (split into chunks)
- Attach components (next suggestions)
Message Handling
Message Processing
Function: handleMessage(message)
Process:
- Check if bot should respond:
- DMs: Always respond (if enabled)
- Guild channels: Only if mentioned or replying to bot
- Resolve channel context (protocol/machine)
- Remove bot mentions from content
- Send to backend via
sendDiscordMessage() - Handle response:
- Split long messages intelligently
- Send as reply + follow-ups
- Attach interactive components
Message Splitting
Function: splitMessageIntelligently(text, maxLength)
Strategy:
- Try to split at sentence boundaries (., !, ?)
- Fall back to line breaks
- Fall back to word boundaries
- Last resort: split at maxLength
Channel Context
Context Resolution
Function: resolveChannelContext(message)
Process:
- Check cache first
- Fetch from backend if not cached
- Use defaults if no config found
- Cache result
Context Includes:
protocolId- Active protocolmachineId- Active state machineupdatedAt- Cache timestamp
Backend Integration
API Communication
Client: backendClient.ts
Features:
- Axios-based HTTP client
- Circuit breaker integration
- Error handling
- Request/response logging
Base URL: Configured via BACKEND_URL environment variable
Authentication:
- API key authentication
- Shared secret for Discord messages
Circuit Breaker
Purpose: Prevent cascading failures
States:
- Closed - Normal operation
- Open - Backend is down, reject requests
- Half-Open - Testing if backend recovered
Configuration:
- Failure threshold
- Timeout duration
- Recovery timeout
Command Registration
File: discord-bot/src/registerCommands.ts
Process:
- Define command structures
- Register with Discord API
- Sync commands on startup
- Handle registration errors
Command Structure:
- Name
- Description
- Options (parameters)
- Subcommands
- Permissions
Configuration
File: discord-bot/src/config.ts
Environment Variables:
DISCORD_TOKEN- Bot tokenBACKEND_URL- Backend API URLBACKEND_API_KEY- API key for authenticationDEFAULT_PROTOCOL_ID- Default protocolDEFAULT_MACHINE_ID- Default state machineALLOW_DM_MESSAGES- Allow DMsBUTTON_MODE- Button handling mode (bot/http)COMMAND_SYNC_MODE- Command sync mode
Data Flow
Source Files
Primary Sources:
discord-bot/src/index.ts- Main bot filediscord-bot/src/backendClient.ts- Backend API clientdiscord-bot/src/registerCommands.ts- Command registrationdiscord-bot/src/circuitBreaker.ts- Circuit breakerdiscord-bot/src/config.ts- Configuration
Related Files:
backend/src/controllers/discord.controller.ts- Discord API endpointsbackend/src/services/discord.service.ts- Discord service
Related Documentation
- State Machine System - Workflow management
- Coder Orchestrator System - Task execution
- Protocol Routing - Protocol assignment
- 03-PLATFORMS/Discord-Bot.md - Discord integration overview