### Broca Development Setup and Configuration Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/README.md Guides users through setting up the Broca development environment. This includes cloning the repository, configuring essential environment variables via a .env file, installing Python dependencies, and running the main application script. ```bash # Clone the repository git clone https://github.com/actuallyrizzn/broca-2.git cd broca-2 ``` ```ini # Copy and fill .env file cp .env.example .env # Edit .env with your credentials and settings # TELEGRAM_API_ID=your_api_id # TELEGRAM_API_HASH=your_api_hash # TELEGRAM_PHONE=your_phone_number # LETTA_API_ENDPOINT=your_letta_endpoint # LETTA_API_KEY=your_letta_key # DEBUG_MODE=true # for testing ``` ```bash # Install dependencies pip install -r requirements.txt # Run the application python main.py ``` -------------------------------- ### Broca 2 Base Installation and Setup Source: https://github.com/actuallyrizzn/broca-2/blob/main/README.md Steps to clone the Broca 2 repository and install it as a base for agent instances. This includes setting up the master folder and installing the package. ```bash # Typically your home directory or a dedicated user folder mkdir ~/sanctum cd ~/sanctum git clone https://github.com/yourusername/broca-2.git broca2 cd broca2 pip install -e . ``` -------------------------------- ### Configuration File Management Example Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/configuration.md Provides a step-by-step example of how to add and document a new configuration option. This process involves updating configuration files (`settings.json`, `.env`), modifying application code (e.g., `common/config.py`), and documenting the change. ```APIDOC Adding a New Config Option: 1. Update `settings.json` or `.env`: Example `settings.json` update: { "my_new_option": "value" } 2. Update Application Code: Modify `common/config.py` to read and validate the new option. 3. Document the Option: Add the new option to this configuration guide. 4. Test: Verify functionality with various inputs and edge cases. ``` -------------------------------- ### Install Letta Python Client Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/letta notes.md Installs the Letta Python client library using pip. This command fetches and installs the necessary packages to interact with the Letta service from your Python environment. ```bash pip install letta-client ``` -------------------------------- ### Minimal Plugin Example (Python) Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/plugin_development.md Demonstrates a minimal plugin structure for Broca 2, inheriting from the base `Plugin` class. It defines basic lifecycle methods (`start`, `stop`) and a message handler (`_echo`) to process incoming messages, printing them to the console. This serves as a template for creating custom plugins. ```python from plugins import Plugin class EchoPlugin(Plugin): def get_name(self): return "echo" def get_platform(self): return "cli" def get_message_handler(self): return self._echo async def start(self): print("EchoPlugin started!") async def stop(self): print("EchoPlugin stopped!") async def _echo(self, message, *args, **kwargs): print(f"Echo: {message}") ``` -------------------------------- ### Settings Management CLI Commands Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/cli_reference.md Provides examples for configuring system behavior using the broca-admin settings commands. Covers getting, setting, and debugging configurations. ```sh broca-admin settings get broca-admin settings set message_mode live broca-admin settings mode echo broca-admin settings debug --enable broca-admin settings refresh 10 ``` -------------------------------- ### Broca Admin CLI Command Example Source: https://github.com/actuallyrizzn/broca-2/blob/main/README.md An example of using the Broca admin CLI tool to interact with a running Broca instance, such as listing items in a queue. ```bash broca-admin queue list ``` -------------------------------- ### Plugin Configuration in settings.json Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/configuration.md Demonstrates how plugin-specific configurations can be integrated into the main `settings.json` file. This example shows the structure for Telegram API credentials and session strings. ```json { "telegram": { "api_id": "...", "api_hash": "...", "session_string": "..." } } ``` -------------------------------- ### Install Dependencies Source: https://github.com/actuallyrizzn/broca-2/blob/main/README.md Installs the project dependencies in editable mode, making the package available for development. ```bash pip install -e . ``` -------------------------------- ### Configure Environment Source: https://github.com/actuallyrizzn/broca-2/blob/main/README.md Copies the example environment file and prompts the user to edit it with their specific settings. ```bash cp .env.example .env # Edit .env with your settings ``` -------------------------------- ### Run Broca 2 Server Source: https://github.com/actuallyrizzn/broca-2/blob/main/README.md Starts the Sanctum: Broca 2 core runtime server using Python's module execution. ```bash python -m broca2.main ``` -------------------------------- ### Module Docstring Example Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/code review/db-refactor.md Provides an example of a concise module-level docstring to be added to each new file (`users.py`, `messages.py`, `queue.py`, `shared.py`) to briefly describe its purpose. ```python """User-related database operations (get_or_create_user, platform lookup, etc).""" ``` -------------------------------- ### Update Application Start Method with Plugin Initialization Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/broca-2-plan.md Demonstrates the updated `start` method for an application, ensuring the plugin manager is initialized before other components like Telegram and the queue processor. This ensures a proper startup sequence for asynchronous operations. ```python async def start(self): # Start plugin manager first await self.plugin_manager.start() # Start other components await self.telegram.start() await self.queue_processor.start() ``` -------------------------------- ### Plugin Skeleton Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/plugin_development.md Provides a basic structure for a Sanctum: Broca 2 plugin, including required methods like get_name, get_platform, get_message_handler, start, and stop. ```python from plugins import Plugin class MyPlugin(Plugin): def get_name(self): return "my_plugin" def get_platform(self): return "my_platform" def get_message_handler(self): return self._handle_message async def start(self): # Startup logic pass async def stop(self): # Cleanup logic pass ``` -------------------------------- ### Run Broca 2 Agent Instance Source: https://github.com/actuallyrizzn/broca-2/blob/main/README.md Demonstrates how to start a specific agent's Broca 2 instance using Python's module execution or via process managers like PM2 for persistent execution. ```bash # From the agent folder cd ~/sanctum/agent-721679f6-c8af-4e01-8677-dc042dc80368 python -m broca2.main # Or use a process manager like PM2 pm2 start "broca-agent-1" --interpreter python -- -m broca2.main pm2 start "broca-agent-2" --interpreter python -- -m broca2.main ``` -------------------------------- ### Create Block Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/letta notes.md Provides an example of creating a new block with specified value and label using the letta_client. The client must be initialized with an authentication token. The created block will be associated with the provided value and label. ```python from letta_client import Letta client = Letta( token="YOUR_TOKEN", ) client.blocks.create( value="value", label="label", ) ``` -------------------------------- ### Broca Startup Log Output Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/telegram-bot-plugin.md Example log messages indicating successful loading and initialization of the Telegram bot plugin during Broca startup. ```text INFO PluginManager Loaded plugin: telegram_bot INFO TelegramBotPlugin initialized INFO Telegram bot started ``` -------------------------------- ### Python Logging Setup Function Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/code review/Common_Module_Refactor.md Defines a function to set up basic logging configuration for the application. It configures the logging level and message format, intended to be called once per entry point. ```python import logging def setup_logging(level=logging.INFO): logging.basicConfig( level=level, format="[%(asctime)s] [%(levelname)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S" ) ``` -------------------------------- ### Plugin Settings Retrieval Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/plugin_development.md Shows how a plugin can expose its specific settings using the get_settings method. ```python def get_settings(self): return {"api_key": "...", "debug": False} ``` -------------------------------- ### Broca 2 Configuration and Logging Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/broca-2-plan.md Highlights the migration of configuration and logging setups. This includes common configuration practices and logging mechanisms with emoji support, ensuring consistent setup across the project. ```python # Configuration and Logging: # - Common config setup (common/config.py) # - Logging setup with emoji support (common/logging.py) ``` -------------------------------- ### Install Telegram Plugin Dependencies Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/telegram-bot-plugin.md Installs the necessary dependencies for the Telegram plugin, including aiogram, using pip. The `[telegram]` extra ensures aiogram and its related packages are included. ```bash pip install -e .[telegram] ``` -------------------------------- ### CLITestPlugin Implementation Skeleton Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/cli-test-plugin.md Provides a basic Python skeleton for the CLITestPlugin. It implements the minimal required interface for testing the Broca 2 plugin lifecycle and serves as a starting point for new plugins. It includes start, stop, get_name, get_platform, and get_message_handler methods. ```python from runtime.core.plugin import Plugin class CLITestPlugin(Plugin): """A minimal no-op plugin used for testing.""" async def start(self) -> None: print("CLITestPlugin started") async def stop(self) -> None: print("CLITestPlugin stopped") def get_name(self) -> str: return "cli_test" def get_platform(self) -> str: return "cli" def get_message_handler(self): # This plugin does not process external messages return lambda *args, **kwargs: None ``` -------------------------------- ### Run Broca with Telegram Plugin Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/telegram-bot-plugin.md Command to start the Broca application. The plugin is automatically discovered and loaded by the core `PluginManager` upon startup. ```bash python -m broca2.main ``` -------------------------------- ### Configuration Access Migration Example Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/code review/Common_Module_Refactor.md Illustrates the refactoring of direct environment variable access using os.getenv() to a centralized configuration utility function get_env_var. This promotes consistent configuration handling across the project. ```python from common.config import get_env_var api_id = get_env_var("TELEGRAM_API_ID", required=True) api_hash = get_env_var("TELEGRAM_API_HASH", required=True) phone = get_env_var("TELEGRAM_PHONE", required=True) ``` -------------------------------- ### Message Handler Implementation Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/plugin_development.md Demonstrates how to implement the message handler for a plugin, including returning the handler and the handler function itself. ```python def get_message_handler(self): return self._handle_message async def _handle_message(self, message, *args, **kwargs): # Process message pass ``` -------------------------------- ### Basic settings.json Structure Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/configuration.md Illustrates the fundamental structure of the `settings.json` file, which holds core runtime settings for the application. It includes parameters like debug mode, queue refresh intervals, retry counts, and message processing modes. ```json { "debug_mode": false, "queue_refresh": 5, "max_retries": 3, "message_mode": "live" } ``` -------------------------------- ### Centralized Logging Setup Source: https://github.com/actuallyrizzn/broca-2/blob/main/README.md This command creates a symbolic link to centralize agent logs. It links the main '~/sanctum/logs/' directory into each agent's log directory, allowing for easier log aggregation. ```bash ln -s ~/sanctum/logs/ ~/sanctum/agent-*/logs ``` -------------------------------- ### Instantiate Letta Python Client Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/letta notes.md Demonstrates how to instantiate the Letta client in Python. It shows connections to a local server via a base URL or to Letta Cloud using an API token. ```python from letta_client import Letta # connect to a local server client = Letta(base_url="http://localhost:8283") # connect to Letta Cloud client = Letta(token="LETTA_API_KEY") ``` -------------------------------- ### Standardize Letta Client Initialization Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/code review/code_review.md Consolidates Letta client methods into a single access point, implementing a proper singleton pattern with thread safety. Includes comprehensive error handling, logging, configuration validation, and documentation. ```python class LettaClient: _instance = None _lock = threading.Lock() def __new__(cls, *args, **kwargs): if cls._instance is None: with cls._lock: if cls._instance is None: cls._instance = super(LettaClient, cls).__new__(cls) cls._instance._initialized = False return cls._instance def __init__(self, config): if self._initialized: return self.config = config self.validate_config() self.logger = logging.getLogger(__name__) self.logger.info("LettaClient initialized") # ... other initialization logic ... self._initialized = True def validate_config(self): if not self.config or 'api_key' not in self.config: raise ConfigurationError("Missing API key in configuration") # ... other validation ... def get_instance(config): client = LettaClient(config) return client # Usage: # config = {"api_key": "your_key", "endpoint": "..."} # client = LettaClient.get_instance(config) ``` -------------------------------- ### SQL: Create Letta Users Table (v2) Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/schema_migration.md Defines the new 'letta_users' table for master user records, independent of specific platforms. It includes creation timestamps, activity, and agent-specific metadata. ```sql CREATE TABLE letta_users ( id INTEGER PRIMARY KEY AUTOINCREMENT, created_at TEXT DEFAULT CURRENT_TIMESTAMP, last_active TEXT, -- Letta-agent specific metadata agent_preferences TEXT, -- JSON field for agent preferences conversation_history_limit INTEGER DEFAULT 10, custom_instructions TEXT, is_active BOOLEAN DEFAULT true ) ``` -------------------------------- ### Create and Configure Agent-Specific Broca 2 Instance Source: https://github.com/actuallyrizzn/broca-2/blob/main/README.md Instructions for creating a dedicated directory for an agent, copying base configuration files, and editing them for agent-specific settings like environment variables. ```bash # For each Letta agent, create a folder named after the agent ID mkdir ~/sanctum/agent-721679f6-c8af-4e01-8677-dc042dc80368 cd ~/sanctum/agent-721679f6-c8af-4e01-8677-dc042dc80368 # Copy base configuration cp ~/sanctum/broca2/.env.example .env cp ~/sanctum/broca2/settings.json . # Edit agent-specific configuration nano .env # Set AGENT_ENDPOINT, AGENT_API_KEY, and other agent-specific settings ``` -------------------------------- ### Extending Command Handlers Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/telegram-bot-plugin.md Example of how to register additional command handlers within the `TelegramBotPlugin.start()` method by utilizing `Dispatcher.message.register(...)`. ```python class TelegramBotPlugin(BrocaPlugin): async def start(self): # ... other initialization ... self.dispatcher.message.register(my_custom_handler, filters.COMMAND) # ... start polling ... async def my_custom_handler(message: types.Message): await message.answer("This is a custom command response!") ``` -------------------------------- ### Agent Client Initialization and Processing Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/project_analysis.md Details the AgentClient class for interacting with an agent API. It covers initialization, message processing with fallback logic, and resource cleanup. Configuration is managed via environment variables. ```Python class AgentClient: """Implements the AgentClient class for interacting with the agent API.""" def __init__(self): # Uses environment variables for configuration (AGENT_ID, DEBUG_MODE) # Implements singleton pattern for Letta client access pass def initialize(self) -> bool: """Verifies agent existence and establishes connection with Letta service.""" # Returns boolean success status pass def process_message(self, message): """Handles message processing through agent API, supporting debug mode.""" # Processes different message types (reasoning_message, content) # Implements fallback to reasoning if no content found pass def cleanup(self): """Handles resource cleanup.""" # Currently minimal implementation pass ``` -------------------------------- ### JSON Configuration for Retry Mechanism Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/504_gateway_timeout_issue.md Example of settings in `settings.json` to configure retry behavior and enable timeout recovery. Includes parameters like `max_retries`, `timeout_recovery_enabled`, `timeout_recovery_delay`, and `timeout_recovery_attempts`. ```json { "debug_mode": false, "queue_refresh": 5, "max_retries": 3, "message_mode": "live", "timeout_recovery_enabled": true, "timeout_recovery_delay": 10, "timeout_recovery_attempts": 2 } ``` -------------------------------- ### Broca Admin CLI: Queue Operations Source: https://github.com/actuallyrizzn/broca-2/blob/main/README.md Demonstrates common queue management commands using the broca-admin CLI tool, including listing and flushing messages. ```bash # Queue management broca-admin queue list broca-admin queue flush ``` -------------------------------- ### User Management CLI Commands Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/cli_reference.md Illustrates commands for managing users via the broca-admin CLI. Covers listing, adding, and removing users. ```sh broca-admin users list broca-admin users add broca-admin users remove ``` -------------------------------- ### Duplicate Letta Client Initialization Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/bugfix_todo.md Illustrates the original approach of global Letta client initialization, which could conflict with agent client instances. The fix involved creating a singleton client. ```Python client = Letta( base_url=os.getenv('LETTA_SERVER_URL'), token=os.getenv('LETTA_SERVER_PASSWORD') ) ``` -------------------------------- ### Clone Repository Source: https://github.com/actuallyrizzn/broca-2/blob/main/README.md Clones the Sanctum: Broca 2 repository from GitHub to your local machine. ```bash git clone https://github.com/yourusername/broca-2.git cd broca-2 ``` -------------------------------- ### Broca 2 CLI Tools Recreation Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/broca-2-plan.md Describes the recreation of existing 'settings' page functionalities into CLI commands. This includes tools for managing queues (list, flush, delete) and users (list, with future expansion). ```cli # CLI Tools Recreation: # - Recreate settings page functionality as CLI commands. # - Queue tools: list queue, flush message, delete message, flush all, delete all. # - User tools: list users (with future features). # - Conversation tools: list conversations (with future features). ``` -------------------------------- ### Broca 2 Environment Variables Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/configuration.md Lists and describes the environment variables used to configure Sanctum: Broca 2. These variables are crucial for sensitive data like API keys and connection endpoints, as well as operational parameters. ```APIDOC Environment Variables: LETTA_API_KEY: Description: Letta agent API key Example: "abc123" LETTA_API_ENDPOINT: Description: Letta agent API endpoint URL Example: "https://api.letta.ai" TELEGRAM_API_ID: Description: Telegram API ID Example: "123456" TELEGRAM_API_HASH: Description: Telegram API hash Example: "abcdef123456" TELEGRAM_PHONE: Description: Telegram phone number Example: "+1234567890" DEBUG_MODE: Description: Enable/disable debug mode Example: "true" QUEUE_REFRESH: Description: Queue refresh interval (seconds) Example: "5" MAX_RETRIES: Description: Max retry attempts for failures Example: "3" MESSAGE_MODE: Description: Message processing mode (live/echo/listen) Example: "live" ``` -------------------------------- ### SQL: Create Queue Table (v1) Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/schema_migration.md Defines the initial 'queue' table structure for managing message processing tasks. It links messages to users and tracks the status and attempts of processing. ```sql CREATE TABLE queue ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, -- References Telegram user_id message_id INTEGER, -- References messages.id status TEXT, -- pending/processing/done/failed attempts INTEGER DEFAULT 0, timestamp TEXT DEFAULT CURRENT_TIMESTAMP ) ``` -------------------------------- ### Python Status System Definitions Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/bugfix_todo.md Defines core status states, valid state transitions, display categories, and properties for messages within the Broca-2 project's proposed status system. These structures guide status management and UI representation. ```Python MESSAGE_STATES = { 'RECEIVED': 'Message received, not yet queued', 'QUEUED': 'Added to processing queue', 'PROCESSING': 'Currently being processed', 'COMPLETED': 'Successfully processed', 'FAILED': 'Processing failed', 'STORED': 'Stored without processing (Listen mode)', 'ECHOED': 'Echoed back without processing (Echo mode)', 'RETRYING': 'Scheduled for retry', 'CANCELLED': 'Processing cancelled', 'ARCHIVED': 'Moved to archive' } ``` ```Python STATE_TRANSITIONS = { 'RECEIVED': ['QUEUED', 'CANCELLED'], 'QUEUED': ['PROCESSING', 'CANCELLED'], 'PROCESSING': ['COMPLETED', 'FAILED', 'STORED', 'ECHOED'], 'FAILED': ['RETRYING', 'ARCHIVED', 'CANCELLED'], 'RETRYING': ['QUEUED'], 'COMPLETED': ['ARCHIVED'], 'STORED': ['ARCHIVED'], 'ECHOED': ['ARCHIVED'], 'CANCELLED': ['ARCHIVED'], 'ARCHIVED': [] # Terminal state } ``` ```Python DISPLAY_CATEGORIES = { 'ACTIVE': [ 'QUEUED', 'PROCESSING', 'RETRYING' ], 'COMPLETED': [ 'COMPLETED', 'STORED', 'ECHOED' ], 'PROBLEMATIC': [ 'FAILED', 'CANCELLED' ], 'INACTIVE': [ 'ARCHIVED' ] } ``` ```Python STATUS_PROPERTIES = { 'RECEIVED': {'color': 'gray', 'icon': 'đŸ“Ĩ', 'priority': 1}, 'QUEUED': {'color': 'blue', 'icon': '📋', 'priority': 2}, 'PROCESSING': {'color': 'yellow', 'icon': 'âš™ī¸', 'priority': 3}, 'COMPLETED': {'color': 'green', 'icon': '✅', 'priority': 4}, 'FAILED': {'color': 'red', 'icon': '❌', 'priority': 5}, 'STORED': {'color': 'purple', 'icon': '💾', 'priority': 4}, 'ECHOED': {'color': 'cyan', 'icon': '🔄', 'priority': 4}, 'RETRYING': {'color': 'orange', 'icon': '🔁', 'priority': 2}, 'CANCELLED': {'color': 'gray', 'icon': 'âšī¸', 'priority': 5}, 'ARCHIVED': {'color': 'gray', 'icon': 'đŸ“Ļ', 'priority': 6} } ``` -------------------------------- ### Broca 2 Multi-Agent Folder Structure Source: https://github.com/actuallyrizzn/broca-2/blob/main/README.md Illustrates the recommended directory layout for managing multiple Broca 2 instances and their agent-specific configurations on a single machine. ```bash ~/sanctum/ ├── broca2/ # Base Broca 2 installation │ ├── main.py │ ├── runtime/ │ ├── plugins/ │ └── ... ├── agent-721679f6-c8af-4e01-8677-dc042dc80368/ # Agent-specific instance │ ├── .env # Agent-specific environment │ ├── settings.json # Agent-specific settings │ ├── sanctum.db # Agent-specific database │ └── logs/ # Agent-specific logs ├── agent-9a2b3c4d-5e6f-7890-abcd-ef1234567890/ # Another agent │ ├── .env │ ├── settings.json │ ├── sanctum.db │ └── logs/ └── shared/ # Shared resources (optional) ├── templates/ └── configs/ ``` -------------------------------- ### Interactive Python Testing Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/code review/db-refactor.md Demonstrates how to test module imports and function access using an interactive Python session after migrating functions, confirming that the new structure works as expected. ```bash python -i >>> from database.operations import get_or_create_user >>> help(get_or_create_user) ``` -------------------------------- ### Broca 2 Plugin Interface - Base Class Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/broca-2-plan.md Defines the abstract `Plugin` base class for the Broca 2 plugin system. It specifies required methods like `start()`, `stop()`, `get_name()`, and optional methods for settings management, ensuring a consistent plugin structure. ```python # Core Plugin Interface (Required for both Telegram and CLI) # Create abstract Plugin base class in plugins/__init__.py: # - Required methods: start(), stop(), get_name() # - Optional methods: get_settings(), validate_settings() # - Event handling interface for message processing # - DO NOT: # - Add plugin-specific methods to base class # - Implement complex event routing logic # - Create plugin dependency management ``` -------------------------------- ### Lettacli List Agents Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/letta notes.md Retrieves a list of all agents managed by the system. Requires initialization with an API token. ```python from letta_client import Letta client = Letta( token="YOUR_TOKEN", ) client.agents.list() ``` -------------------------------- ### Python Main Entrypoint Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/broca-2-plan.md The main.py script serves as the entrypoint for the Broca 2 runtime. It initializes and runs the core asynchronous event loop, orchestrating the system's operations. ```python import asyncio from runtime.loop import run_runtime if __name__ == "__main__": asyncio.run(run_runtime()) ``` -------------------------------- ### Broca 2 Configuration File Management Source: https://github.com/actuallyrizzn/broca-2/blob/main/README.md Details on managing agent-specific configuration files (.env, settings.json) and how shared configurations can be linked or copied into agent directories. ```bash # Each agent has its own configuration ~/sanctum/agent-721679f6-c8af-4e01-8677-dc042dc80368/.env ~/sanctum/agent-721679f6-c8af-4e01-8677-dc042dc80368/settings.json # Shared configurations can be symlinked or copied ln -s ~/sanctum/shared/templates/telegram_config.json ~/sanctum/agent-*/ telegram_config.json ``` -------------------------------- ### Broca Admin CLI: Settings Management Source: https://github.com/actuallyrizzn/broca-2/blob/main/README.md Illustrates how to set system configurations, such as the message processing mode, via the broca-admin CLI. ```bash # Settings broca-admin settings set message_mode live ``` -------------------------------- ### Broca Admin CLI: User Management Source: https://github.com/actuallyrizzn/broca-2/blob/main/README.md Shows how to list users managed by the broca-admin CLI tool. ```bash # User management broca-admin users list ``` -------------------------------- ### SQL: Create Platform Profiles Table (v2) Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/schema_migration.md Defines the new 'platform_profiles' table to link master users to specific platform accounts. It stores platform details, user IDs, usernames, and metadata. ```sql CREATE TABLE platform_profiles ( id INTEGER PRIMARY KEY AUTOINCREMENT, letta_user_id INTEGER, -- References letta_users.id platform TEXT, -- 'telegram', 'discord', 'email', etc. platform_user_id TEXT, -- Platform-specific user ID username TEXT, -- Platform username display_name TEXT, -- Platform display/first name metadata TEXT, -- JSON field for platform-specific data created_at TEXT DEFAULT CURRENT_TIMESTAMP, last_active TEXT, UNIQUE(platform, platform_user_id) ) ``` -------------------------------- ### Broca Project Structure Overview Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/README.md Provides a hierarchical view of the Broca project's directory and file structure. It outlines the organization of core components, database operations, Telegram integration, web interface, templates, static assets, and the main application entry point. ```treeview broca/ ├── core/ │ ├── agent.py # Agent client implementation │ └── queue.py # Queue processing logic ├── database/ │ ├── models.py # Database models and schema │ └── operations/ │ ├── shared.py # Shared database operations │ ├── users.py # User-related operations │ ├── messages.py # Message-related operations │ └── queue.py # Queue-related operations ├── telegram/ │ ├── client.py # Telegram client setup │ └── handlers.py # Message handling logic ├── web/ │ └── app.py # Flask dashboard application ├── templates/ # Dashboard HTML templates ├── static/ # Static assets for dashboard └── main.py # Application entry point ``` -------------------------------- ### Create and Manage Core Memory Blocks Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/letta notes.md Provides Python code for creating, retrieving, modifying, attaching, and detaching core memory blocks. It emphasizes the need to cache block IDs locally due to the unreliability of the `client.blocks.list()` method. ```python # Create a new block block = client.blocks.create( label=f"Persona_{username}", value={ "name": username, "preferences": {}, "conversation_history": [] } ) # Store block ID in database user_record.block_id = block.id user_record.save() # Core block operations (using cached block ID) client.blocks.retrieve(block_id=user_record.block_id) client.blocks.modify(block_id=user_record.block_id, value=new_content) client.agents.blocks.attach(agent_id=agent_id, block_id=user_record.block_id) client.agents.blocks.detach(agent_id=agent_id, block_id=user_record.block_id) # NEVER use list() for block discovery # client.blocks.list() # DO NOT USE - unreliable ``` ```python # Create and manage a user's persona block block_label = f"Persona_{username}" block_content = { "name": username, "preferences": {}, "conversation_history": [] } # Create the block first block = client.blocks.create( label=block_label, value=block_content ) # Store block ID in database user_record.block_id = block.id user_record.save() ``` -------------------------------- ### Python CLI Queue Command Starter Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/broca-2-plan.md This snippet from cli/queue.py demonstrates how to register a CLI command for flushing the message queue. It defines the command structure and a placeholder function for the actual flush logic. ```python def register(subparsers): q = subparsers.add_parser("flush-queue", help="Flush the entire message queue") q.set_defaults(func=flush_queue) def flush_queue(args): print("\u0043\u006c\u0065\u0061\u006e\u0069\u006e\u0067\u0020\u0074\u0068\u0065\u0020\u006d\u0065\u0073\u0073\u0061\u0067\u0065\u0020\u0071\u0075\u0065\u0075\u0065\u002e\u002e\u002e") # TODO: Connect to DB and delete all queue entries ``` -------------------------------- ### Core Plugin Management: PluginManager Integration Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/broca-2-plan.md Shows how the main application entry point (`main.py`) is modified to utilize the `PluginManager` for handling multiple plugins. This includes loading plugin configurations and supporting concurrent plugin operations. ```python # Example modification in main.py # ... plugin_manager = PluginManager(config) await plugin_manager.load_plugins() await plugin_manager.start_plugins() # ... # For shutdown: # await plugin_manager.stop_plugins() ``` -------------------------------- ### Telegram Bot Configuration Reference Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/telegram-bot-plugin.md Detailed reference for environment variables used to configure the Telegram Bot Plugin. Includes requirements, defaults, and descriptions for each setting. ```apidoc TELEGRAM_BOT_TOKEN: Required: ✅ Default: – Description: Bot token from BotFather. TELEGRAM_OWNER_ID: Required: âš ī¸* Default: – Description: Numeric Telegram user id of the bot owner. TELEGRAM_OWNER_USERNAME: Required: âš ī¸* Default: – Description: Username of the bot owner (without `@`). TELEGRAM_MESSAGE_MODE: Required: ❌ Default: `echo` Description: `echo`, `listen` or `live`. TELEGRAM_BUFFER_DELAY: Required: ❌ Default: `5` Description: Seconds to wait before flushing the buffer. *Note: Exactly one of `TELEGRAM_OWNER_ID` or `TELEGRAM_OWNER_USERNAME` must be provided to restrict bot usage to the owner. ``` -------------------------------- ### Database Operations and Models (Python) Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/project_analysis.md Outlines the database layer, including operations for CRUD queries and database models/schemas. It also mentions database migration files. ```python class DatabaseOperations: # Handles database CRUD operations and queries. def get_record(self, query: str) -> any: pass def save_record(self, data: any) -> None: pass class DatabaseModels: # Defines database models and schemas. pass # Database migrations are managed in a dedicated directory. ``` -------------------------------- ### Lettacli Create Identity Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/letta notes.md Creates a new identity for the agent. Requires specifying an identifier key, name, and identity type (e.g., 'org'). ```curl curl -X POST http://localhost:8283/v1/identities/ \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "identifier_key": "identifier_key", "name": "name", "identity_type": "org" }' ``` -------------------------------- ### Cleanup Operations File Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/code review/db-refactor.md Command to search the codebase for any remaining references to the old `operations.py` file, ensuring it has been fully removed and replaced by the new module structure. ```bash grep -r 'operations.py' ``` -------------------------------- ### Queue Management CLI Commands Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/cli_reference.md Demonstrates common operations for managing the message queue using the broca-admin CLI. Includes listing, flushing, and deleting queue items. ```sh broca-admin queue list broca-admin queue flush broca-admin queue delete ``` -------------------------------- ### Centralize Configuration Management Source: https://github.com/actuallyrizzn/broca-2/blob/main/broca2/docs/code review/code_review.md Establishes a dedicated configuration module for managing environment variables and application settings. Includes implementation of environment variable management and configuration validation. ```python import os from dotenv import load_dotenv class ConfigurationManager: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super(ConfigurationManager, cls).__new__(cls) cls._instance._loaded = False return cls._instance def __init__(self): if self._loaded: return load_dotenv() # Load variables from .env file self.settings = {} self.load_settings() self._loaded = True def load_settings(self): self.settings['DATABASE_URL'] = os.getenv('DATABASE_URL') self.settings['API_KEY'] = os.getenv('API_KEY') self.settings['DEBUG'] = os.getenv('DEBUG', 'False').lower() in ('true', '1', 't') self.validate_settings() def validate_settings(self): if not self.settings.get('DATABASE_URL'): raise ValueError("DATABASE_URL environment variable not set") if not self.settings.get('API_KEY'): raise ValueError("API_KEY environment variable not set") def get(self, key, default=None): return self.settings.get(key, default) # Usage: # config_manager = ConfigurationManager() # db_url = config_manager.get('DATABASE_URL') # api_key = config_manager.get('API_KEY') # debug_mode = config_manager.get('DEBUG') ```