# OpenOSRS Automated Login System\n\nThis document describes the automated login system for the OpenOSRS modernized client, designed to enable AI agents to seamlessly connect to and play RuneScape.\n\n## Overview\n\nThe automated login system provides:\n- **Secure credential management** with AES encryption\n- **Intelligent connection management** with world selection optimization\n- **Comprehensive state tracking** with detailed monitoring\n- **Retry logic and error handling** for reliable connections\n- **Auto-reconnect capabilities** for uninterrupted gameplay\n- **Full integration** with the ModernizedClient API\n\n## Quick Start\n\n### Basic Usage\n\n```java\n// Initialize the client\nModernizedClient client = new ModernizedClient();\nclient.start().get();\n\n// Set login credentials\nclient.setLoginCredentials(\"username\", \"password\");\n\n// Enable auto-reconnect\nclient.setAutoReconnect(true);\n\n// Start automated login (30 second timeout)\nclient.login(30).thenAccept(success -> {\n    if (success) {\n        System.out.println(\"Successfully logged in!\");\n        // Start your agent's gameplay logic\n    } else {\n        System.out.println(\"Login failed: \" + \n            client.getLoginManager().getLastError());\n    }\n});\n```\n\n### Running the Example\n\n```bash\n# Direct login (development/testing)\njava -cp build/classes examples.ExampleAgentWithLogin --direct myusername mypassword\n\n# Load from encrypted credentials file\njava -cp build/classes examples.ExampleAgentWithLogin --file agent-creds.dat\n\n# Create new encrypted credentials file\njava -cp build/classes examples.ExampleAgentWithLogin --create myuser mypass mycreds.dat\n```\n\n## Core Components\n\n### LoginManager\n\nThe main orchestrator for the login process.\n\n```java\nLoginManager loginManager = client.getLoginManager();\n\n// Start login with timeout\nCompletableFuture<Boolean> loginResult = loginManager.login(30);\n\n// Get current state\nLoginState state = loginManager.getCurrentState();\n\n// Check if logged in\nboolean loggedIn = loginManager.isLoggedIn();\n\n// Get status information\nString status = loginManager.getStatus();\n\n// Get last error if login failed\nString error = loginManager.getLastError();\n```\n\n### LoginCredentials\n\nSecure credential storage with encryption.\n\n```java\nLoginCredentials credentials = new LoginCredentials();\ncredentials.setCredentials(\"username\", \"password\");\n\n// Save to encrypted file\nboolean saved = credentials.saveToFile(\"creds.dat\", \"master-password\");\n\n// Load from encrypted file\nLoginCredentials loaded = new LoginCredentials();\nboolean loadSuccess = loaded.loadFromFile(\"creds.dat\", \"master-password\");\n\n// Validate credentials\nboolean valid = credentials.isValid();\n```\n\n### GameConnectionManager\n\nHandles network connections and world selection.\n\n```java\nGameConnectionManager connectionManager = new GameConnectionManager();\n\n// Connect to game servers\nboolean connected = connectionManager.connect(30); // 30 second timeout\n\n// Select optimal world (low ping, available)\nint worldId = connectionManager.selectOptimalWorld();\n\n// Check connection status\nboolean isConnected = connectionManager.isConnected();\nlong pingMs = connectionManager.getCurrentPing();\n```\n\n### LoginStateTracker\n\nMonitors login progress and provides callbacks.\n\n```java\nLoginStateTracker tracker = new LoginStateTracker();\n\n// Set state change callback\ntracker.setStateChangeCallback((oldState, newState) -> {\n    System.out.println(\"Login state changed: \" + oldState + \" -> \" + newState);\n});\n\n// Get current state\nLoginState currentState = tracker.getCurrentState();\n\n// Get detailed status\nString detailedStatus = tracker.getDetailedStatus();\n\n// Get login session summary\nString summary = tracker.getSessionSummary();\n```\n\n## Login States\n\nThe system tracks the following states:\n\n- `DISCONNECTED` - Not connected to game servers\n- `CONNECTING` - Establishing network connection\n- `CONNECTED` - Connected but not authenticated\n- `AUTHENTICATING` - Sending login credentials\n- `LOGGED_IN` - Successfully authenticated and in game\n- `FAILED` - Login process failed\n- `RECONNECTING` - Attempting to reconnect after disconnection\n\n## Advanced Features\n\n### Auto-Reconnect\n\n```java\n// Enable automatic reconnection\nclient.setAutoReconnect(true);\n\n// The client will automatically attempt to reconnect if disconnected\n// Uses exponential backoff to avoid overwhelming servers\n```\n\n### State Monitoring\n\n```java\n// Monitor login state changes\nclient.setupLoginMonitoring((oldState, newState) -> {\n    System.out.println(\"State transition: \" + oldState + \" -> \" + newState);\n    \n    if (newState == LoginState.LOGGED_IN) {\n        // Start your agent's main logic\n        startAgentBehavior();\n    } else if (newState == LoginState.FAILED) {\n        // Handle login failure\n        handleLoginFailure();\n    }\n});\n```\n\n### Credential File Encryption\n\nCredentials are stored using AES encryption:\n\n```java\n// Create and save encrypted credentials\nLoginCredentials creds = new LoginCredentials();\ncreds.setCredentials(\"username\", \"password\");\ncreds.saveToFile(\"agent-creds.dat\", \"secure-master-password\");\n\n// Later, load encrypted credentials\nLoginCredentials loadedCreds = new LoginCredentials();\nloadedCreds.loadFromFile(\"agent-creds.dat\", \"secure-master-password\");\n```\n\n**Security Note**: Use a strong master password and store it securely. The master password is used to encrypt/decrypt the credentials file.\n\n## Error Handling\n\nThe system provides comprehensive error information:\n\n```java\nif (!loginResult) {\n    String error = loginManager.getLastError();\n    \n    // Common error types:\n    // - \"Invalid credentials\"\n    // - \"Connection timeout\"\n    // - \"Server unavailable\"\n    // - \"Account locked\"\n    // - \"World is full\"\n    \n    System.out.println(\"Login failed: \" + error);\n}\n```\n\n## Testing\n\nRun the comprehensive test suite:\n\n```bash\n./gradlew test --tests \"*LoginSystemTest*\"\n```\n\nThe test suite covers:\n- Credential validation and encryption\n- State tracking and transitions\n- Connection management\n- Integration with ModernizedClient\n- Error handling scenarios\n\n## Best Practices for AI Agents\n\n### 1. Reliable Connection\n\n```java\n// Always enable auto-reconnect for agents\nclient.setAutoReconnect(true);\n\n// Use appropriate timeouts\nclient.login(60); // 60 seconds for slower connections\n```\n\n### 2. State Monitoring\n\n```java\n// Monitor connection state continuously\nclient.setupLoginMonitoring((oldState, newState) -> {\n    if (newState == LoginState.DISCONNECTED) {\n        // Pause agent activities until reconnected\n        pauseAgentActivities();\n    } else if (newState == LoginState.LOGGED_IN) {\n        // Resume agent activities\n        resumeAgentActivities();\n    }\n});\n```\n\n### 3. Credential Security\n\n```java\n// Store credentials in encrypted files, not in source code\nString credentialsFile = \"agent-\" + agentId + \"-creds.dat\";\nif (client.loadLoginCredentials(credentialsFile)) {\n    client.login();\n} else {\n    System.err.println(\"Failed to load credentials\");\n}\n```\n\n### 4. Error Recovery\n\n```java\n// Implement retry logic for transient failures\nif (!loginResult) {\n    String error = loginManager.getLastError();\n    if (error.contains(\"timeout\") || error.contains(\"server unavailable\")) {\n        // Wait and retry for transient errors\n        Thread.sleep(5000);\n        client.login();\n    } else {\n        // Handle permanent errors (invalid credentials, etc.)\n        handlePermanentError(error);\n    }\n}\n```\n\n## Integration with Agent Workflows\n\nThe login system is designed to integrate seamlessly with agent decision-making:\n\n```java\npublic class MyAgent {\n    private ModernizedClient client;\n    private boolean gameplayActive = false;\n    \n    public void start() {\n        client = new ModernizedClient();\n        client.start();\n        \n        // Setup login monitoring\n        client.setupLoginMonitoring((oldState, newState) -> {\n            switch (newState) {\n                case LOGGED_IN:\n                    gameplayActive = true;\n                    startMainGameplayLoop();\n                    break;\n                case DISCONNECTED:\n                case FAILED:\n                    gameplayActive = false;\n                    pauseAllActivities();\n                    break;\n            }\n        });\n        \n        // Load credentials and login\n        if (client.loadLoginCredentials(\"my-agent-creds.dat\")) {\n            client.setAutoReconnect(true);\n            client.login();\n        }\n    }\n    \n    private void startMainGameplayLoop() {\n        // Your agent's main gameplay logic\n        while (gameplayActive && client.isLoggedIn()) {\n            // Perform agent actions\n            performAgentActions();\n            \n            // Brief pause between actions\n            Thread.sleep(1000);\n        }\n    }\n}\n```\n\n## Troubleshooting\n\n### Common Issues\n\n1. **Login Timeout**\n   - Increase timeout value\n   - Check network connectivity\n   - Try different world servers\n\n2. **Invalid Credentials**\n   - Verify username/password\n   - Check if account is locked\n   - Ensure credentials file is not corrupted\n\n3. **Connection Failed**\n   - Check firewall settings\n   - Verify game servers are online\n   - Try connecting manually first\n\n### Debug Information\n\n```java\n// Enable detailed logging\nSystem.setProperty(\"openosrs.login.debug\", \"true\");\n\n// Get detailed status\nString status = client.getLoginStatus();\nSystem.out.println(\"Login Status: \" + status);\n\n// Get connection information\nGameConnectionManager conn = client.getLoginManager().getConnectionManager();\nSystem.out.println(\"Connected: \" + conn.isConnected());\nSystem.out.println(\"Ping: \" + conn.getCurrentPing() + \"ms\");\n```\n\n## Future Enhancements\n\nPlanned improvements:\n- Multi-account support for managing multiple agents\n- World-hopping for optimal gameplay conditions\n- Login queue management for busy servers\n- Advanced reconnection strategies\n- Integration with proxy servers for distributed agents\n\n---\n\n**Note**: This login system is designed specifically for AI agents to automate RuneScape gameplay. Always comply with game rules and terms of service when using automated clients.\n