From 26737298888896635f427c3c652c1fb86dacf92e Mon Sep 17 00:00:00 2001 From: Slipstream Date: Wed, 30 Apr 2025 12:37:05 -0600 Subject: [PATCH] aa --- gurt/background.py | 36 ++++++++++++++++++++++++++++++++++-- gurt/commands.py | 15 ++++++++++++++- gurt/config.py | 11 ----------- gurt/tools.py | 17 ----------------- gurt_memory.py | 22 ++++++++++++++-------- 5 files changed, 62 insertions(+), 39 deletions(-) diff --git a/gurt/background.py b/gurt/background.py index ec30e53..d2e7283 100644 --- a/gurt/background.py +++ b/gurt/background.py @@ -48,7 +48,7 @@ if TYPE_CHECKING: # --- Tool Mapping Import --- # Import the mapping to execute tools by name -from .tools import TOOL_MAPPING +from .tools import TOOL_MAPPING, send_discord_message # Also import send_discord_message directly for goal execution reporting from .config import TOOLS # Import FunctionDeclaration list for tool metadata # --- Background Task --- @@ -187,9 +187,13 @@ async def background_processing_task(cog: 'GurtCog'): goal_id = goal.get('goal_id') description = goal.get('description') plan = goal.get('details') # The decomposition plan is stored here + # Retrieve context saved with the goal + goal_context_guild_id = goal.get('guild_id') + goal_context_channel_id = goal.get('channel_id') + goal_context_user_id = goal.get('user_id') if goal_id and description and plan and isinstance(plan.get('steps'), list): - print(f"--- Executing Goal ID {goal_id}: '{description}' ---") + print(f"--- Executing Goal ID {goal_id}: '{description}' (Context: G={goal_context_guild_id}, C={goal_context_channel_id}, U={goal_context_user_id}) ---") steps = plan['steps'] current_step_index = plan.get('current_step_index', 0) # Track progress goal_failed = False @@ -243,6 +247,33 @@ async def background_processing_task(cog: 'GurtCog'): tool_error = f"Tool '{tool_name}' not found in TOOL_MAPPING." print(f" - Error: {tool_error}") + # --- Send Update Message (if channel context exists) --- ### MODIFICATION START ### + if goal_context_channel_id: + step_number_display = current_step_index + 1 # Human-readable step number for display + status_emoji = "✅" if tool_success else "❌" + # Use the helper function to create a summary + step_result_summary = _create_result_summary(tool_result if tool_success else {"error": tool_error}) + + update_message = ( + f"**Goal Update (ID: {goal_id}, Step {step_number_display}/{len(steps)})** {status_emoji}\n" + f"> **Goal:** {description}\n" + f"> **Step:** {step_desc}\n" + f"> **Tool:** `{tool_name}`\n" + # f"> **Args:** `{json.dumps(tool_args)}`\n" # Args might be too verbose + f"> **Result:** `{step_result_summary}`" + ) + # Limit message length + if len(update_message) > 1900: + update_message = update_message[:1900] + "...`" + + try: + # Use the imported send_discord_message function + await send_discord_message(cog, channel_id=goal_context_channel_id, message_content=update_message) + print(f" - Sent goal update to channel {goal_context_channel_id}") + except Exception as msg_err: + print(f" - Failed to send goal update message to channel {goal_context_channel_id}: {msg_err}") + ### MODIFICATION END ### + # --- Handle Tool Outcome --- if tool_success: # Store result if needed (optional, requires plan structure modification) @@ -254,6 +285,7 @@ async def background_processing_task(cog: 'GurtCog'): else: # Step doesn't require a tool (e.g., internal reasoning/check) print(" - No tool required for this step (internal check/reasoning).") + # Send update message for non-tool steps too? Optional. For now, only for tool steps. current_step_index += 1 # Assume non-tool steps succeed for now # Check if goal completed diff --git a/gurt/commands.py b/gurt/commands.py index 28c4a74..038bf72 100644 --- a/gurt/commands.py +++ b/gurt/commands.py @@ -403,7 +403,20 @@ def setup_commands(cog: 'GurtCog'): except json.JSONDecodeError: await interaction.followup.send("❌ Invalid JSON format for details.", ephemeral=True) return - result = await cog.memory_manager.add_goal(description, priority, details) + + # Capture context from interaction + guild_id = str(interaction.guild_id) if interaction.guild_id else None + channel_id = str(interaction.channel_id) if interaction.channel_id else None + user_id = str(interaction.user.id) if interaction.user else None + + result = await cog.memory_manager.add_goal( + description, + priority, + details, + guild_id=guild_id, + channel_id=channel_id, + user_id=user_id + ) if result.get("status") == "added": await interaction.followup.send(f"✅ Goal added (ID: {result.get('goal_id')}): '{description}'", ephemeral=True) elif result.get("status") == "duplicate": diff --git a/gurt/config.py b/gurt/config.py index 1aa42b7..06d1bc3 100644 --- a/gurt/config.py +++ b/gurt/config.py @@ -1384,17 +1384,6 @@ def create_tools_list(): } ) ) - tool_declarations.append( - FunctionDeclaration( - name="random_vibe_check", - description="Returns a random vibe/meme message. Use for chaotic or pointless autonomous actions.", - parameters={ - "type": "object", - "properties": {}, - "required": [] - } - ) - ) tool_declarations.append( FunctionDeclaration( name="fetch_random_joke", diff --git a/gurt/tools.py b/gurt/tools.py index fc687e7..b1fa428 100644 --- a/gurt/tools.py +++ b/gurt/tools.py @@ -2420,22 +2420,6 @@ async def check_disk_space(cog: commands.Cog) -> Dict[str, Any]: except Exception as e: return {"status": "error", "error": str(e)} -async def random_vibe_check(cog: commands.Cog) -> Dict[str, Any]: - """Returns a random vibe/meme message.""" - vibes = [ - "vibe check: passed ✅", - "vibe check: failed 💀", - "vibe check: ur pc is haunted", - "vibe check: cpu's chillin, u chillin?", - "vibe check: ngl ur vibes immaculate rn", - "vibe check: system's sus, keep an eye out 👀", - "vibe check: all systems go, but are YOU ok?", - "vibe check: ur fans sound like a jet, u good?", - "vibe check: i detected 0 vibes, try again later" - ] - import random - return {"status": "success", "vibe": random.choice(vibes)} - async def fetch_random_joke(cog: commands.Cog) -> Dict[str, Any]: """Fetches a random joke from an API.""" url = "https://official-joke-api.appspot.com/random_joke" @@ -2596,7 +2580,6 @@ TOOL_MAPPING = { # --- Random System/Meme Tools --- "read_temps": read_temps, "check_disk_space": check_disk_space, - "random_vibe_check": random_vibe_check, "fetch_random_joke": fetch_random_joke, # --- Guild/Channel Listing Tools --- "list_bot_guilds": list_bot_guilds, diff --git a/gurt_memory.py b/gurt_memory.py index c8546b8..573f32a 100644 --- a/gurt_memory.py +++ b/gurt_memory.py @@ -214,7 +214,10 @@ class MemoryManager: priority INTEGER DEFAULT 5, -- Lower number = higher priority created_timestamp REAL DEFAULT (unixepoch('now')), last_updated REAL DEFAULT (unixepoch('now')), - details TEXT -- Optional JSON blob for sub-tasks, progress, etc. + details TEXT, -- Optional JSON blob for sub-tasks, progress, etc. + guild_id TEXT, -- The server ID where the goal was created + channel_id TEXT, -- The channel ID where the goal was created + user_id TEXT -- The user ID who created the goal ); """) await db.execute("CREATE INDEX IF NOT EXISTS idx_goal_status ON gurt_goals (status);") @@ -916,8 +919,8 @@ class MemoryManager: # --- Goal Management Methods (SQLite) --- - async def add_goal(self, description: str, priority: int = 5, details: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: - """Adds a new goal to the database.""" + async def add_goal(self, description: str, priority: int = 5, details: Optional[Dict[str, Any]] = None, guild_id: Optional[str] = None, channel_id: Optional[str] = None, user_id: Optional[str] = None) -> Dict[str, Any]: + """Adds a new goal to the database, including context.""" if not description: return {"error": "Goal description is required."} logger.info(f"Adding new goal (Priority {priority}): '{description}'") @@ -933,10 +936,10 @@ class MemoryManager: async with aiosqlite.connect(self.db_path) as db: cursor = await db.execute( """ - INSERT INTO gurt_goals (description, priority, details, status, last_updated) - VALUES (?, ?, ?, 'pending', unixepoch('now')) + INSERT INTO gurt_goals (description, priority, details, status, last_updated, guild_id, channel_id, user_id) + VALUES (?, ?, ?, 'pending', unixepoch('now'), ?, ?, ?) """, - (description, priority, details_json) + (description, priority, details_json, guild_id, channel_id, user_id) ) await db.commit() goal_id = cursor.lastrowid @@ -951,7 +954,7 @@ class MemoryManager: logger.info(f"Retrieving goals (Status: {status or 'any'}, Limit: {limit})") goals = [] try: - sql = "SELECT goal_id, description, status, priority, created_timestamp, last_updated, details FROM gurt_goals" + sql = "SELECT goal_id, description, status, priority, created_timestamp, last_updated, details, guild_id, channel_id, user_id FROM gurt_goals" params = [] if status: sql += " WHERE status = ?" @@ -969,7 +972,10 @@ class MemoryManager: "priority": row[3], "created_timestamp": row[4], "last_updated": row[5], - "details": details + "details": details, + "guild_id": row[7], + "channel_id": row[8], + "user_id": row[9] }) logger.info(f"Retrieved {len(goals)} goals.") return goals