Skip to content

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 backend
  • fetchChannelConfig() - Get channel configuration
  • fetchStateMachineInstance() - Get state machine instance
  • transitionStateMachineInstance() - Transition state
  • recordInstanceApproval() - Record approval
  • recordInstanceEvidence() - Record evidence
  • runInstanceOrchestrator() - Run orchestrator
  • fetchInstanceTasks() - Get tasks
  • fetchInstanceArtifacts() - Get artifacts
  • fetchProtocolById() - Get protocol
  • listProtocols() - 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

  • 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 channel
  • info - Get channel configuration
  • export - Export protocol definition
  • export-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 observerApproval guard
  • Triggers auto-advance if configured

/observer-evidence instance_id:xxx description:"..." proof_url:"..."

  • Record verification evidence
  • Satisfies testsOrDemoAttached guard
  • 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 protocols
  • info - Get protocol details
  • history - View version history
  • export - Export protocol (JSON/YAML)
  • diff - Compare protocol versions
  • import - Import protocol definition
  • update - Update protocol
  • annotate - Annotate version
  • deprecate - Deprecate protocol
  • clone - Clone protocol
  • approve - Approve version
  • latest - Get latest version
  • pending - List pending approvals
  • export-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 settings
  • get key:xxx - Get setting value
  • set key:xxx value:xxx - Set setting value

/search query:"..."

  • Perform web search
  • Triggers backend web search
  • Returns search results

Button Interactions

Button Types

  1. Action Buttons

    • Execute actions
    • View artifacts
    • Approve guards
    • Transition states
  2. Cancel Buttons

    • Cancel suggestions
    • Ephemeral responses
  3. Ask Questions Buttons

    • Request clarification
    • Ephemeral responses

Button Handling

Function: handleButtonInteraction(interaction)

Process:

  1. Defer reply immediately (within 3 seconds)
  2. Execute button action via backend
  3. Update interaction with result
  4. Handle long messages (split into chunks)
  5. Attach components (next suggestions)

Message Handling

Message Processing

Function: handleMessage(message)

Process:

  1. Check if bot should respond:
    • DMs: Always respond (if enabled)
    • Guild channels: Only if mentioned or replying to bot
  2. Resolve channel context (protocol/machine)
  3. Remove bot mentions from content
  4. Send to backend via sendDiscordMessage()
  5. Handle response:
    • Split long messages intelligently
    • Send as reply + follow-ups
    • Attach interactive components

Message Splitting

Function: splitMessageIntelligently(text, maxLength)

Strategy:

  1. Try to split at sentence boundaries (., !, ?)
  2. Fall back to line breaks
  3. Fall back to word boundaries
  4. Last resort: split at maxLength

Channel Context

Context Resolution

Function: resolveChannelContext(message)

Process:

  1. Check cache first
  2. Fetch from backend if not cached
  3. Use defaults if no config found
  4. Cache result

Context Includes:

  • protocolId - Active protocol
  • machineId - Active state machine
  • updatedAt - 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:

  1. Define command structures
  2. Register with Discord API
  3. Sync commands on startup
  4. Handle registration errors

Command Structure:

  • Name
  • Description
  • Options (parameters)
  • Subcommands
  • Permissions

Configuration

File: discord-bot/src/config.ts

Environment Variables:

  • DISCORD_TOKEN - Bot token
  • BACKEND_URL - Backend API URL
  • BACKEND_API_KEY - API key for authentication
  • DEFAULT_PROTOCOL_ID - Default protocol
  • DEFAULT_MACHINE_ID - Default state machine
  • ALLOW_DM_MESSAGES - Allow DMs
  • BUTTON_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 file
  • discord-bot/src/backendClient.ts - Backend API client
  • discord-bot/src/registerCommands.ts - Command registration
  • discord-bot/src/circuitBreaker.ts - Circuit breaker
  • discord-bot/src/config.ts - Configuration

Related Files:

  • backend/src/controllers/discord.controller.ts - Discord API endpoints
  • backend/src/services/discord.service.ts - Discord service

ASO Universal Consciousness System Documentation