# API Reference Complete API reference for the MUD AI Player. ## Table of Contents - [Core Components](#core-components) - [Modules](#modules) - [Configuration](#configuration) - [Utilities](#utilities) --- ## Core Components ### TelnetClient Asynchronous telnet client for MUD connection. **Location:** `src.core.telnet_client.TelnetClient` ```python class TelnetClient: def __init__( self, host: str, port: int, max_retries: int = 3, retry_delay: float = 5.0, auto_reconnect: bool = True, ) ``` **Methods:** - `async connect() -> bool` - Connect to MUD server - `async connect_with_retry() -> bool` - Connect with retry logic - `async disconnect()` - Disconnect from server - `async send(command: str)` - Send command to server - `async receive_loop()` - Main receive loop - `set_receive_callback(callback: Callable)` - Set data callback **Example:** ```python client = TelnetClient("mud.example.com", 4000) await client.connect() await client.send("look") ``` ### GameState Central game state management. **Location:** `src.core.game_state.GameState` ```python @dataclass class GameState: character: Character current_room: Optional[Room] previous_room: Optional[Room] inventory: List[str] active_quests: List[Quest] combat_state: CombatState target: Optional[str] ``` **Methods:** - `is_in_combat() -> bool` - Check if in combat - `is_healthy(threshold: float = 0.7) -> bool` - Check health threshold - `update_from_prompt(prompt: ParsedPrompt)` - Update vitals - `update_room(parsed_room: ParsedRoom)` - Update current room - `update_combat(parsed_combat: ParsedCombat)` - Update combat state ### ANSIParser Parse and strip ANSI color codes. **Location:** `src.core.ansi_parser.ANSIParser` ```python class ANSIParser: def strip_ansi(self, text: str) -> str def parse_colors(self, text: str) -> List[ANSISegment] ``` --- ## Modules ### WorldMapper High-level automapper with hybrid storage. **Location:** `src.modules.mapper.WorldMapper` ```python class WorldMapper: def __init__( self, db_path: str = "data/maps/active/world.db", archive_dir: str = "data/maps/archive", enable_sync: bool = True, room_count_trigger: int = 500, time_interval_hours: float = 24.0, ) ``` **Methods:** - `on_room_enter(title, description, exits, npcs, items, zone) -> int` - Process arrival in a room, returns room ID - `on_move(direction: str)` - Record movement direction - `on_move_failed(direction: str)` - Record blocked exit - `find_path(to_room_id: int) -> Optional[List[str]]` - Find path from current room to target - `find_path_between(from_id: int, to_id: int) -> Optional[List[str]]` - Find path between two rooms - `get_next_exploration_target() -> Optional[Dict]` - Get next unexplored exit - `get_unexplored_exits(room_id: Optional[int]) -> List[str]` - Get unexplored directions from room - `search_rooms(query: str, top_k: int = 5) -> List[Dict]` - Semantic search on room descriptions - `close()` - Close mapper and create final snapshot **Properties:** - `current_room_id: Optional[int]` - `total_rooms: int` - `total_exits: int` - `sync_stats: Dict` ### DecisionEngine Central decision-making engine. **Location:** `src.modules.decision.engine.DecisionEngine` ```python class DecisionEngine: def __init__( self, combat_config: Optional[CombatConfig] = None, exploration_strategy: str = "random", ) ``` **Methods:** - `tick(game_state: GameState)` - Evaluate world and queue actions - `next_action() -> Optional[Action]` - Get most urgent action - `force_state(state_name: str, game_state: GameState)` - Force state transition - `register_state(state: BaseBehaviorState)` - Add custom behavior state **Properties:** - `current_state: BaseBehaviorState` - `current_state_name: str` ### ActionQueue Priority queue for actions. **Location:** `src.modules.decision.action_queue.ActionQueue` ```python class ActionQueue: def push(self, action: Action) def pop(self) -> Optional[Action] def peek(self) -> Optional[Action] def clear(self) def clear_by_source(self, source: str) @property def size(self) -> int @property def is_empty(self) -> bool ``` ### CombatAI Intelligent combat decision-making. **Location:** `src.modules.decision.combat_ai.CombatAI` ```python class CombatAI: def __init__(self, config: Optional[CombatConfig] = None) def decide(self, game_state: GameState) -> List[Action] def reset(self) ``` ### GoalManager Manage AI goals and objectives. **Location:** `src.modules.decision.goal_manager.GoalManager` ```python class GoalManager: def add_goal(self, goal: Goal) def remove_goal(self, goal_id: str) def get_current_goal(self, game_state: GameState) -> Optional[Goal] def get_active_goals(self) -> List[Goal] def set_default_goals(self) @property def active_goal_count(self) -> int ``` ### LLMBrain LLM integration with memory. **Location:** `src.modules.llm.brain.LLMBrain` ```python class LLMBrain: def __init__( self, config: LLMConfig, memory_db_path: str = "data/llm_memory.db", ) async def initialize() async def decide(game_state: GameState) -> Optional[str] async def social_reply( message: str, sender: str, character_class: str, character_name: str, ) -> Optional[str] @property def is_available(self) -> bool ``` ### SocialAI Detect and respond to social interactions. **Location:** `src.modules.llm.social_ai.SocialAI` ```python class SocialAI: def __init__( self, client: LLMClient, character_name: str, character_class: str, ) def detect_social_event(self, text: str) -> Optional[Dict] ``` ### CharacterCreator Automated character creation. **Location:** `src.modules.character.creator.CharacterCreator` ```python class CharacterCreator: def __init__(self, config: CreatorConfig) async def create_character(telnet: TelnetClient) -> bool ``` ### QuestManager Quest tracking and management. **Location:** `src.modules.quest.quest_manager.QuestManager` ```python class QuestManager: def add_quest(self, quest: Quest) def complete_quest(self, quest_id: str) def get_active_quests(self) -> List[Quest] def detect_quest_in_text(self, text: str) -> Optional[Quest] ``` ### ProgressionOptimizer Optimize grinding and progression. **Location:** `src.modules.progression.optimizer.ProgressionOptimizer` ```python class ProgressionOptimizer: def find_optimal_grind_area( self, game_state: GameState, world_mapper: WorldMapper, ) -> Optional[str] def should_grind(self, game_state: GameState) -> bool ``` ### MonitoringServer Web dashboard server. **Location:** `src.modules.web.server.MonitoringServer` ```python class MonitoringServer: def __init__( self, host: str = "127.0.0.1", port: int = 8080, game_state: Optional[Any] = None, world_mapper: Optional[Any] = None, decision_engine: Optional[Any] = None, ) async def start() async def stop() def log_event(self, event_type: str, message: str, data: Optional[Dict] = None) ``` --- ## Configuration ### load_config Load and validate configuration. **Location:** `src.config.settings.load_config` ```python def load_config(config_path: str = "config.yaml") -> Config ``` **Example:** ```python from src.config.settings import load_config config = load_config("config.yaml") print(config.mud.host) print(config.character.preferred_class) ``` ### Config Classes - `MudConfig` - MUD connection settings - `CharacterConfig` - Character preferences - `AIConfig` - AI engine settings - `LLMProviderConfig` - LLM configuration - `MapperConfig` - Mapper settings - `BehaviorConfig` - Behavior simulation - `LoggingConfig` - Logging settings - `MonitoringConfig` - Web dashboard settings --- ## Utilities ### setup_logger Configure application logging. **Location:** `src.utils.logger.setup_logger` ```python def setup_logger( level: str = "INFO", log_file: str = "data/logs/game.log", console: bool = True, max_file_size_mb: int = 10, backup_count: int = 5, ) -> logging.Logger ``` ### HumanBehavior Simulate human-like behavior. **Location:** `src.utils.human_behavior.HumanBehavior` ```python class HumanBehavior: def __init__( self, reaction_time_min_ms: int = 200, reaction_time_max_ms: int = 2000, pause_probability: float = 0.05, ) async def delay(self) def maybe_typo(self, text: str) -> str ``` --- ## Data Classes ### ParsedRoom ```python @dataclass class ParsedRoom: title: Optional[str] description: Optional[str] exits: List[str] npcs: List[str] items: List[str] ``` ### ParsedPrompt ```python @dataclass class ParsedPrompt: hp: Optional[int] max_hp: Optional[int] mp: Optional[int] max_mp: Optional[int] sp: Optional[int] max_sp: Optional[int] ``` ### ParsedCombat ```python @dataclass class ParsedCombat: attacker: Optional[str] target: Optional[str] action: str damage: Optional[int] is_combat: bool ``` ### Action ```python @dataclass class Action: command: str priority: ActionPriority description: str source: str ``` ### Goal ```python @dataclass class Goal: id: str name: str description: str priority: GoalPriority target_state: str conditions: List[Callable[[GameState], bool]] progress: float ``` --- ## Enums ### CombatState ```python class CombatState(Enum): IDLE = "idle" IN_COMBAT = "in_combat" FLEEING = "fleeing" ``` ### ActionPriority ```python class ActionPriority(Enum): CRITICAL = 1 HIGH = 2 MEDIUM = 3 LOW = 4 IDLE = 5 ``` ### GoalPriority ```python class GoalPriority(Enum): CRITICAL = 1 HIGH = 2 MEDIUM = 3 LOW = 4 ``` ### EventType ```python class EventType(Enum): ROOM = "room" PROMPT = "prompt" COMBAT = "combat" INVENTORY = "inventory" CHAT = "chat" UNKNOWN = "unknown" ``` --- ## Exceptions All custom exceptions inherit from `MUDAIPlayerException`: ```python class MUDAIPlayerException(Exception): """Base exception for MUD AI Player""" pass class ConnectionError(MUDAIPlayerException): """Connection-related errors""" pass class ParseError(MUDAIPlayerException): """Parsing errors""" pass class ConfigurationError(MUDAIPlayerException): """Configuration errors""" pass ```