Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
refactor: Implement path-aware session management with nested storage
cyhhaofbd61d5e9cd8
diff --git a/core/controller.py b/core/controller.oldsimilarity index 97%rename from core/controller.pyrename to core/controller.oldindex b101141d8..22995b511 100644--- a/core/controller.py+++ b/core/controller.old@@ -194,7 +194,6 @@ Use the buttons below to manage your Claude Code sessions, or simply type any meawait self.im_client.send_message(target_context,confirmation_text,- parse_mode='markdown',reply_to=user_message_ts)else:@@ -203,8 +202,7 @@ Use the buttons below to manage your Claude Code sessions, or simply type any meconfirmation_text = f"⏳ {formatter.format_text('Processing...')}"await self.im_client.send_message(target_context,- confirmation_text,- parse_mode='MarkdownV2'+ confirmation_text)# Check if we have a client for this session@@ -303,12 +301,10 @@ Use the buttons below to manage your Claude Code sessions, or simply type any me# Format and send messageformatted_message = self.claude_client.format_message(message)if formatted_message and formatted_message.strip():- parse_mode = 'markdown' if self.config.platform == "slack" else 'MarkdownV2'await self.im_client.send_message(target_context,formatted_message,- parse_mode=parse_mode,- reply_to=thread_id if self.config.platform == "slack" else None+ reply_to=thread_id if self.im_client.should_use_thread_for_reply() else None)# Check if this was a ResultMessage (query complete)@@ -325,8 +321,7 @@ Use the buttons below to manage your Claude Code sessions, or simply type any meawait self.im_client.send_message(target_context,ready_msg,- parse_mode=parse_mode,- reply_to=thread_id if self.config.platform == "slack" else None+ reply_to=thread_id if self.im_client.should_use_thread_for_reply() else None)except asyncio.CancelledError:@@ -344,7 +339,7 @@ Use the buttons below to manage your Claude Code sessions, or simply type any meawait self.im_client.send_message(target_context,error_msg,- reply_to=thread_id if self.config.platform == "slack" else None+ reply_to=thread_id if self.im_client.should_use_thread_for_reply() else None)except:pass@@ -381,7 +376,7 @@ Use the buttons below to manage your Claude Code sessions, or simply type any meawait self.im_client.send_message(target_context,error_msg,- reply_to=thread_id if self.config.platform == "slack" else None+ reply_to=thread_id if self.im_client.should_use_thread_for_reply() else None)except Exception as e:@@ -667,8 +662,7 @@ Use the buttons below to manage your Claude Code sessions, or simply type any meawait self.im_client.send_message_with_buttons(target_context,"⚙️ *Settings \\- Message Visibility*\n\nSelect which message types to hide from Claude output:",- keyboard,- parse_mode='MarkdownV2' if self.config.platform == "telegram" else 'markdown'+ keyboard)async def _handle_settings_slack(self, context: MessageContext):@@ -703,8 +697,7 @@ Use the buttons below to manage your Claude Code sessions, or simply type any meawait self.im_client.send_message_with_buttons(target_context,"⚙️ *Personalization Settings*\n\nConfigure how Claude Code messages appear in your Slack workspace.",- keyboard,- parse_mode='MarkdownV2' if self.config.platform == "telegram" else 'markdown'+ keyboard)async def handle_callback_query(self, context: MessageContext, callback_data: str):@@ -850,8 +843,7 @@ _Tip: All commands work in DMs, channels, and threads!_"""# For Slack, we might send an ephemeral messageawait self.im_client.send_message(context,- f"{display_name} messages are now {action}",- parse_mode='MarkdownV2' if self.config.platform == "telegram" else 'markdown'+ f"{display_name} messages are now {action}")elif callback_data == "info_msg_types":diff --git a/core/controller_refactored.py b/core/controller_refactored.pynew file mode 100644index 000000000..5fcae6deb--- /dev/null+++ b/core/controller_refactored.py@@ -0,0 +1,347 @@+"""Core controller that coordinates between modules and handlers"""++import asyncio+import os+import logging+from typing import Optional, Dict, Any+from config.settings import AppConfig+from modules.im import BaseIMClient, MessageContext, IMFactory+from modules.im.formatters import TelegramFormatter, SlackFormatter+from modules.claude_client import ClaudeClient+from modules.session_manager import SessionManager+from modules.settings_manager import SettingsManager+from core.handlers import (+ CommandHandlers,+ SessionHandler,+ SettingsHandler,+ MessageHandler+)++logger = logging.getLogger(__name__)+++class Controller:+ """Main controller that coordinates all bot operations"""++ def __init__(self, config: AppConfig):+ """Initialize controller with configuration"""+ self.config = config++ # Session tracking (must be initialized before handlers)+ self.claude_sessions: Dict[str, Any] = {}+ self.receiver_tasks: Dict[str, asyncio.Task] = {}+ self.stored_session_mappings: Dict[str, str] = {}++ # Initialize core modules+ self._init_modules()++ # Initialize handlers+ self._init_handlers()++ # Setup callbacks+ self._setup_callbacks()++ # Background task for cleanup+ self.cleanup_task: Optional[asyncio.Task] = None++ # Restore session mappings on startup+ self.session_handler.restore_session_mappings()++ # Restore last saved working directory+ self._restore_saved_cwd()++ def _init_modules(self):+ """Initialize core modules"""+ # Create IM client with platform-specific formatter+ self.im_client: BaseIMClient = IMFactory.create_client(self.config)++ # Create platform-specific formatter+ if self.config.platform == "telegram":+ formatter = TelegramFormatter()+ elif self.config.platform == "slack":+ formatter = SlackFormatter()+ else:+ logger.warning(f"Unknown platform: {self.config.platform}, using Telegram formatter")+ formatter = TelegramFormatter()++ # Inject formatter into clients+ self.im_client.formatter = formatter+ self.claude_client = ClaudeClient(self.config.claude, formatter)++ # Initialize managers+ self.session_manager = SessionManager()+ self.settings_manager = SettingsManager()++ def _init_handlers(self):+ """Initialize all handlers with controller reference"""+ self.command_handler = CommandHandlers(self)+ self.session_handler = SessionHandler(self)+ self.settings_handler = SettingsHandler(self)+ self.message_handler = MessageHandler(self)++ # Set cross-references between handlers+ self.message_handler.set_session_handler(self.session_handler)++ def _setup_callbacks(self):+ """Setup callback connections between modules"""+ # Create command handlers dict+ command_handlers = {+ 'start': self.command_handler.handle_start,+ 'clear': self.command_handler.handle_clear,+ 'cwd': self.command_handler.handle_cwd,+ 'set_cwd': self.command_handler.handle_set_cwd,+ 'settings': self.settings_handler.handle_settings+ }++ # Register callbacks with the IM client+ self.im_client.register_callbacks(+ on_message=self.message_handler.handle_user_message,+ on_command=command_handlers,+ on_callback_query=self.message_handler.handle_callback_query,+ on_settings_update=self.handle_settings_update,+ on_change_cwd=self.handle_change_cwd_submission+ )++ # Utility methods used by handlers+ def _restore_saved_cwd(self):+ """Restore the last saved working directory from user settings"""+ try:+ # Get all user settings+ all_settings = self.settings_manager.settings++ # Find the most recently used custom_cwd+ saved_cwd = None+ for user_id, user_settings in all_settings.items():+ if hasattr(user_settings, 'custom_cwd') and user_settings.custom_cwd:+ saved_cwd = user_settings.custom_cwd+ logger.info(f"Found saved working directory from user {user_id}: {saved_cwd}")+ # Use the first non-null custom_cwd found+ # In the future, could use timestamps to find the most recent+ break++ # Apply the saved working directory if found+ if saved_cwd and os.path.exists(saved_cwd):+ self.config.claude.cwd = saved_cwd+ logger.info(f"Restored working directory to: {saved_cwd}")+ else:+ logger.info(f"Using default working directory from config: {self.config.claude.cwd}")++ except Exception as e:+ logger.error(f"Error restoring saved working directory: {e}")+ # Continue with default from config++ def _get_settings_key(self, context: MessageContext) -> str:+ """Get settings key based on context"""+ if self.config.platform == "telegram" and context.channel_id != context.user_id:+ return context.channel_id+ return context.user_id++ def _get_target_context(self, context: MessageContext) -> MessageContext:+ """Get target context for sending messages"""+ if self.im_client.should_use_thread_for_reply() and context.thread_id:+ return MessageContext(+ user_id=context.user_id,+ channel_id=context.channel_id,+ thread_id=context.thread_id,+ message=context.message,+ platform_specific=context.platform_specific+ )+ return context++ # Settings update handler (for Slack modal)+ async def handle_settings_update(self, user_id: str, hidden_message_types: list, channel_id: str = None):+ """Handle settings update (typically from Slack modal)"""+ try:+ # Determine settings key+ settings_key = channel_id if channel_id else user_id++ # Update settings+ user_settings = self.settings_manager.get_user_settings(settings_key)+ user_settings.hidden_message_types = hidden_message_types++ # Save settings - using the correct method name+ self.settings_manager.save_settings()++ logger.info(f"Updated settings for {settings_key}: hidden types = {hidden_message_types}")++ # Create context for sending confirmation+ context = MessageContext(+ user_id=user_id,+ channel_id=channel_id if channel_id else user_id,+ message="",+ platform_specific={}+ )++ # Send confirmation+ await self.im_client.send_message(+ context,+ "✅ Settings updated successfully!"+ )++ except Exception as e:+ logger.error(f"Error updating settings: {e}")+ # Create context for error message+ context = MessageContext(+ user_id=user_id,+ channel_id=channel_id if channel_id else user_id,+ message="",+ platform_specific={}+ )+ await self.im_client.send_message(+ context,+ f"❌ Failed to update settings: {str(e)}"+ )++ # Working directory change handler (for Slack modal)+ async def handle_change_cwd_submission(self, user_id: str, new_cwd: str, channel_id: str = None):+ """Handle working directory change submission (from Slack modal)"""+ try:+ import os++ # Validate and expand the path+ validated_path = os.path.abspath(os.path.expanduser(new_cwd))++ # Create context for messages+ context = MessageContext(+ user_id=user_id,+ channel_id=channel_id if channel_id else user_id,+ message="",+ platform_specific={}+ )++ if not os.path.exists(validated_path):+ await self.im_client.send_message(+ context,+ f"❌ Path does not exist: {new_cwd}"+ )+ return++ if not os.path.isdir(validated_path):+ await self.im_client.send_message(+ context,+ f"❌ Path is not a directory: {new_cwd}"+ )+ return++ # Update the global config directly+ self.config.claude.cwd = validated_path++ # Save to user settings for persistence+ # Determine settings key+ settings_key = channel_id if channel_id else user_id+ user_settings = self.settings_manager.get_user_settings(settings_key)+ user_settings.custom_cwd = validated_path+ self.settings_manager.update_user_settings(settings_key, user_settings)++ # Clear all sessions to apply new cwd+ # Note: This affects ALL users since we're changing the global config+ for session_id in list(self.claude_sessions.keys()):+ await self.session_handler.cleanup_session(session_id)++ # Send confirmation+ await self.im_client.send_message(+ context,+ f"✅ Working directory changed to:\n`{validated_path}`\n\nAll sessions have been reset to use the new directory."+ )++ logger.info(f"Changed working directory for {settings_key} to {validated_path}")++ except Exception as e:+ logger.error(f"Error changing working directory: {e}")+ # Create context for error message+ context = MessageContext(+ user_id=user_id,+ channel_id=channel_id if channel_id else user_id,+ message="",+ platform_specific={}+ )+ await self.im_client.send_message(+ context,+ f"❌ Failed to change working directory: {str(e)}"+ )++ # Main run method+ def run(self):+ """Run the controller"""+ logger.info(f"Starting Claude Proxy Controller with {self.config.platform} platform...")++ # Start cleanup task+ loop = asyncio.new_event_loop()+ asyncio.set_event_loop(loop)++ # Start cleanup task+ self.cleanup_task = loop.create_task(self.periodic_cleanup())++ try:+ # Run the IM client (blocking)+ self.im_client.run()+ except KeyboardInterrupt:+ logger.info("Received keyboard interrupt, shutting down...")+ except Exception as e:+ logger.error(f"Error in main run loop: {e}", exc_info=True)+ finally:+ loop.run_until_complete(self.cleanup())++ async def periodic_cleanup(self):+ """Periodically clean up inactive sessions"""+ while True:+ try:+ await asyncio.sleep(300) # Check every 5 minutes++ # Clean up completed receiver tasks+ completed_tasks = []+ for session_id, task in self.receiver_tasks.items():+ if task.done():+ completed_tasks.append(session_id)++ for session_id in completed_tasks:+ del self.receiver_tasks[session_id]+ logger.info(f"Cleaned up completed receiver task for session {session_id}")++ # Clean up inactive Claude sessions+ inactive_sessions = []+ current_time = asyncio.get_event_loop().time()++ for session_id, client in self.claude_sessions.items():+ # Check if client has been inactive (customize as needed)+ if hasattr(client, 'last_activity'):+ if current_time - client.last_activity > 1800: # 30 minutes+ inactive_sessions.append(session_id)++ for session_id in inactive_sessions:+ await self.session_handler.cleanup_session(session_id)+ logger.info(f"Cleaned up inactive session {session_id}")++ except Exception as e:+ logger.error(f"Error in periodic cleanup: {e}")++ async def cleanup(self):+ """Cleanup resources"""+ logger.info("Cleaning up controller resources...")++ # Cancel cleanup task+ if self.cleanup_task and not self.cleanup_task.done():+ self.cleanup_task.cancel()+ try:+ await self.cleanup_task+ except asyncio.CancelledError:+ pass++ # Cancel all receiver tasks+ for session_id, task in self.receiver_tasks.items():+ if not task.done():+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass++ # Cleanup all Claude sessions+ for session_id in list(self.claude_sessions.keys()):+ await self.session_handler.cleanup_session(session_id)++ # Stop IM client if it has a stop method+ if self.im_client and hasattr(self.im_client, 'stop'):+ await self.im_client.stop()++ logger.info("Controller cleanup complete")\ No newline at end of filediff --git a/core/handlers/__init__.py b/core/handlers/__init__.pynew file mode 100644index 000000000..f987ddf99--- /dev/null+++ b/core/handlers/__init__.py@@ -0,0 +1,13 @@+"""Handler modules for organizing controller functionality"""++from .command_handlers import CommandHandlers+from .session_handler import SessionHandler+from .settings_handler import SettingsHandler+from .message_handler import MessageHandler++__all__ = [+ 'CommandHandlers',+ 'SessionHandler',+ 'SettingsHandler',+ 'MessageHandler'+]\ No newline at end of filediff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.pynew file mode 100644index 000000000..52fcb99ca--- /dev/null+++ b/core/handlers/command_handlers.py@@ -0,0 +1,274 @@+"""Command handlers for bot commands like /start, /clear, /cwd, etc."""++import os+import logging+from typing import Optional+from modules.im import MessageContext, InlineKeyboard, InlineButton++logger = logging.getLogger(__name__)+++class CommandHandlers:+ """Handles all bot command operations"""++ def __init__(self, controller):+ """Initialize with reference to main controller"""+ self.controller = controller+ self.config = controller.config+ self.im_client = controller.im_client+ self.session_manager = controller.session_manager+ self.settings_manager = controller.settings_manager++ async def handle_start(self, context: MessageContext, args: str = ""):+ """Handle /start command with interactive buttons"""+ platform_name = self.config.platform.capitalize()++ # Get user and channel info+ try:+ user_info = await self.im_client.get_user_info(context.user_id)+ except Exception as e:+ logger.warning(f"Failed to get user info: {e}")+ user_info = {"id": context.user_id}++ try:+ channel_info = await self.im_client.get_channel_info(context.channel_id)+ except Exception as e:+ logger.warning(f"Failed to get channel info: {e}")+ channel_info = {+ "id": context.channel_id,+ "name": (+ "Direct Message"+ if context.channel_id.startswith("D")+ else context.channel_id+ ),+ }++ # For non-Slack platforms, use traditional text message+ if self.config.platform != "slack":+ formatter = self.im_client.formatter++ # Build welcome message using formatter to handle escaping properly+ lines = [+ formatter.format_bold("Welcome to Claude Code Remote Control Bot!"),+ "",+ f"Platform: {formatter.format_text(platform_name)}",+ f"User ID: {formatter.format_code_inline(context.user_id)}",+ f"Channel/Chat ID: {formatter.format_code_inline(context.channel_id)}",+ "",+ formatter.format_bold("Commands:"),+ formatter.format_text("/start - Show this message"),+ formatter.format_text("/clear - Reset session and start fresh"),+ formatter.format_text("/cwd - Show current working directory"),+ formatter.format_text("/set_cwd <path> - Set working directory"),+ formatter.format_text("/settings - Personalization settings"),+ "",+ formatter.format_bold("How it works:"),+ formatter.format_text(+ "• Send any message and it's immediately sent to Claude Code"+ ),+ formatter.format_text(+ "• Each chat maintains its own conversation context"+ ),+ formatter.format_text("• Use /clear to reset the conversation"),+ ]++ message_text = formatter.format_message(*lines)+ await self.im_client.send_message(context, message_text)+ return++ # For Slack, create interactive buttons using Block Kit+ user_name = user_info.get("real_name") or user_info.get("name") or "User"++ # Create interactive buttons for commands+ buttons = [+ # Row 1: Directory management+ [+ InlineButton(text="📁 Current Dir", callback_data="cmd_cwd"),+ InlineButton(text="📂 Change Work Dir", callback_data="cmd_change_cwd"),+ ],+ # Row 2: Session and Settings+ [+ InlineButton(text="🔄 Reset Session", callback_data="cmd_clear"),+ InlineButton(text="⚙️ Settings", callback_data="cmd_settings"),+ ],+ # Row 3: Help+ [InlineButton(text="ℹ️ How it Works", callback_data="info_how_it_works")],+ ]++ keyboard = InlineKeyboard(buttons=buttons)++ welcome_text = f"""🎉 **Welcome to Claude Code Remote Control Bot!**++👋 Hello **{user_name}**!+🔧 Platform: **{platform_name}**+📍 Channel: **{channel_info.get('name', 'Unknown')}**++**Quick Actions:**+Use the buttons below to manage your Claude Code sessions, or simply type any message to start chatting with Claude!"""++ target_context = self.controller._get_target_context(context)+ await self.im_client.send_message_with_buttons(+ target_context, welcome_text, keyboard+ )++ async def handle_clear(self, context: MessageContext, args: str = ""):+ """Handle clear command - clears session and disconnects Claude client"""+ try:+ # Import SessionHandler to get base session ID+ from core.handlers.session_handler import SessionHandler++ # Create temporary handler to get base session ID+ temp_handler = SessionHandler(self.controller)+ base_session_id = temp_handler.get_base_session_id(context)++ # Clear all path mappings for this base session+ self.settings_manager.clear_session_mapping(+ context.user_id, base_session_id+ )++ # Clear session and disconnect clients+ response = await self.session_manager.clear_session(context.user_id)+ logger.info(f"User {context.user_id} cleared session")++ # Add reset message+ full_response = f"{response}\n🔄 Claude session has been reset."++ # Send the complete response+ await self.im_client.send_message(context, full_response)+ logger.info(f"Sent clear response to user {context.user_id}")++ except Exception as e:+ logger.error(f"Error clearing session: {e}", exc_info=True)+ try:+ await self.im_client.send_message(+ context, f"❌ Error clearing session: {str(e)}"+ )+ except Exception as send_error:+ logger.error(+ f"Failed to send error message: {send_error}", exc_info=True+ )++ async def handle_cwd(self, context: MessageContext, args: str = ""):+ """Handle cwd command - show current working directory"""+ try:+ # Always use config.claude.cwd as the single source of truth+ current_cwd = self.config.claude.cwd+ absolute_path = os.path.abspath(current_cwd)++ # Build response using formatter to avoid escaping issues+ formatter = self.im_client.formatter++ # Format path properly with code block+ path_line = f"📁 Current Working Directory:\n{formatter.format_code_inline(absolute_path)}"++ # Build status lines+ status_lines = []+ if os.path.exists(absolute_path):+ status_lines.append("✅ Directory exists")+ else:+ status_lines.append("⚠️ Directory does not exist")++ status_lines.append("💡 This is where Claude Code will execute commands")++ # Combine all parts+ response_text = path_line + "\n" + "\n".join(status_lines)++ await self.im_client.send_message(context, response_text)+ except Exception as e:+ logger.error(f"Error getting cwd: {e}")+ await self.im_client.send_message(+ context, f"Error getting working directory: {str(e)}"+ )++ async def handle_set_cwd(self, context: MessageContext, args: str):+ """Handle set_cwd command - change working directory"""+ try:+ if not args:+ await self.im_client.send_message(context, "Usage: /set_cwd <path>")+ return++ new_path = args.strip()++ # Expand user path and get absolute path+ expanded_path = os.path.expanduser(new_path)+ absolute_path = os.path.abspath(expanded_path)++ # Check if directory exists+ if not os.path.exists(absolute_path):+ # Try to create it+ try:+ os.makedirs(absolute_path, exist_ok=True)+ logger.info(f"Created directory: {absolute_path}")+ except Exception as e:+ await self.im_client.send_message(+ context, f"❌ Cannot create directory: {str(e)}"+ )+ return++ if not os.path.isdir(absolute_path):+ formatter = self.im_client.formatter+ error_text = f"❌ Path exists but is not a directory: {formatter.format_code_inline(absolute_path)}"+ await self.im_client.send_message(context, error_text)+ return++ # Update the global config directly+ self.config.claude.cwd = absolute_path++ # Also save to user settings for persistence+ settings_key = self.controller._get_settings_key(context)+ settings = self.settings_manager.get_user_settings(settings_key)+ settings.custom_cwd = absolute_path+ self.settings_manager.update_user_settings(settings_key, settings)++ logger.info(f"User {context.user_id} changed cwd to: {absolute_path}")++ formatter = self.im_client.formatter+ response_text = (+ f"✅ Working directory changed to:\n"+ f"{formatter.format_code_inline(absolute_path)}"+ )+ await self.im_client.send_message(context, response_text)++ except Exception as e:+ logger.error(f"Error setting cwd: {e}")+ await self.im_client.send_message(+ context, f"❌ Error setting working directory: {str(e)}"+ )++ async def handle_change_cwd_modal(self, context: MessageContext):+ """Handle Change Work Dir button - open modal for Slack"""+ if self.config.platform != "slack":+ # For non-Slack platforms, just send instructions+ await self.im_client.send_message(+ context,+ "📂 To change working directory, use:\n`/set_cwd <path>`\n\nExample:\n`/set_cwd ~/projects/myapp`",+ )+ return++ # For Slack, open a modal dialog+ trigger_id = (+ context.platform_specific.get("trigger_id")+ if context.platform_specific+ else None+ )++ if trigger_id and hasattr(self.im_client, "open_change_cwd_modal"):+ try:+ # Get current CWD to show in modal+ current_cwd = self.config.claude.cwd++ await self.im_client.open_change_cwd_modal(+ trigger_id, current_cwd, context.channel_id+ )+ except Exception as e:+ logger.error(f"Error opening change CWD modal: {e}")+ await self.im_client.send_message(+ context,+ "❌ Failed to open directory change dialog. Please try again.",+ )+ else:+ # No trigger_id, show instructions+ await self.im_client.send_message(+ context,+ "📂 Click the 'Change Work Dir' button in the /start menu to change working directory.",+ )diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pynew file mode 100644index 000000000..7dad8c0a0--- /dev/null+++ b/core/handlers/message_handler.py@@ -0,0 +1,243 @@+"""Message routing and Claude communication handlers"""++import asyncio+import logging+import os+from typing import Optional, Dict, Any, List+from modules.im import MessageContext+logger = logging.getLogger(__name__)+++class MessageHandler:+ """Handles message routing and Claude communication"""++ def __init__(self, controller):+ """Initialize with reference to main controller"""+ self.controller = controller+ self.config = controller.config+ self.im_client = controller.im_client+ self.session_manager = controller.session_manager+ self.settings_manager = controller.settings_manager+ self.formatter = controller.im_client.formatter+ self.session_handler = None # Will be set after creation+ self.receiver_tasks = controller.receiver_tasks++ def set_session_handler(self, session_handler):+ """Set reference to session handler"""+ self.session_handler = session_handler++ def _get_settings_key(self, context: MessageContext) -> str:+ """Get settings key based on context"""+ if self.config.platform == "telegram" and context.channel_id != context.user_id:+ return context.channel_id+ return context.user_id++ def _get_target_context(self, context: MessageContext) -> MessageContext:+ """Get target context for sending messages"""+ # For Slack, use thread for replies if enabled+ if self.im_client.should_use_thread_for_reply() and context.thread_id:+ return MessageContext(+ user_id=context.user_id,+ channel_id=context.channel_id,+ thread_id=context.thread_id,+ message=context.message,+ platform_specific=context.platform_specific+ )+ return context++ def get_relative_path(self, abs_path: str) -> str:+ """Convert absolute path to relative path from working directory"""+ try:+ # Always use config.claude.cwd as the single source of truth+ cwd = self.config.claude.cwd+ cwd = os.path.abspath(os.path.expanduser(cwd))++ # Convert input path to absolute+ abs_path = os.path.abspath(os.path.expanduser(abs_path))++ # Try to get relative path+ rel_path = os.path.relpath(abs_path, cwd)++ # If relative path goes up too many directories, use absolute+ if rel_path.startswith("../.."):+ return abs_path++ return rel_path+ except Exception:+ # If any error, return original path+ return abs_path++ async def handle_user_message(self, context: MessageContext, message: str):+ """Process regular user messages and send to Claude"""+ try:+ # Get or create Claude session+ base_session_id, working_path, composite_key = self.session_handler.get_session_info(context)+ client = await self.session_handler.get_or_create_claude_session(context)++ # Send immediate acknowledgment for better UX+ ack_message = await self.im_client.send_message(+ context,+ "📨 Message received, processing..."+ )++ # Send message to Claude+ await client.query(message, session_id=composite_key)+ logger.info(f"Sent message to Claude for session {composite_key}")++ # Delete acknowledgment message+ if ack_message and hasattr(self.im_client, 'delete_message'):+ try:+ await self.im_client.delete_message(context.channel_id, ack_message)+ except Exception as e:+ logger.debug(f"Could not delete ack message: {e}")++ # Start receiver if not already running+ if composite_key not in self.receiver_tasks or self.receiver_tasks[composite_key].done():+ logger.info(f"Starting message receiver for session {composite_key}")+ self.receiver_tasks[composite_key] = asyncio.create_task(+ self._receive_messages(client, base_session_id, working_path, context)+ )++ except Exception as e:+ logger.error(f"Error processing user message: {e}", exc_info=True)+ _, _, composite_key = self.session_handler.get_session_info(context)+ await self.session_handler.handle_session_error(composite_key, context, e)++ async def _receive_messages(self, client, base_session_id: str, working_path: str, context: MessageContext):+ """Receive messages from Claude SDK client"""+ try:+ settings_key = self._get_settings_key(context)+ settings = self.settings_manager.get_user_settings(settings_key)+ target_context = self._get_target_context(context)++ async for message in client.receive_messages():+ try:+ # Check for SystemMessage init to capture session_id+ if hasattr(message, "__class__") and message.__class__.__name__ == "SystemMessage":+ if hasattr(message, 'subtype') and message.subtype == 'init':+ if hasattr(message, 'data') and 'session_id' in message.data:+ claude_session_id = message.data['session_id']+ self.session_handler.capture_session_id(+ base_session_id,+ working_path,+ claude_session_id,+ context.user_id+ )++ # Skip certain messages+ if hasattr(self.controller, 'claude_client') and self.controller.claude_client._is_skip_message(message):+ continue++ # Determine message type by class name+ message_type = None+ if hasattr(message, "__class__"):+ class_name = message.__class__.__name__+ if class_name == "SystemMessage":+ message_type = "system"+ elif class_name == "UserMessage":+ message_type = "user"+ elif class_name == "AssistantMessage":+ message_type = "assistant"+ elif class_name == "ResultMessage":+ message_type = "result"++ # Check if this message type should be hidden+ if message_type and self.settings_manager.is_message_type_hidden(settings_key, message_type):+ logger.info(f"Skipping {message_type} message for settings key {settings_key} (hidden in settings)")+ continue++ # Format and send message using claude_client+ if hasattr(self.controller, 'claude_client'):+ formatted_message = self.controller.claude_client.format_message(message)+ if formatted_message and formatted_message.strip():+ await self.im_client.send_message(+ target_context,+ formatted_message+ )++ # Check if this was a ResultMessage (query complete)+ if message_type == "result":+ # Mark session as not active+ session = await self.controller.session_manager.get_or_create_session(+ context.user_id,+ context.channel_id+ )+ if session:+ composite_key = f"{base_session_id}:{working_path}"+ session.session_active[composite_key] = False++ except Exception as e:+ logger.error(f"Error processing message from Claude: {e}", exc_info=True)+ # Continue processing other messages+ continue++ except Exception as e:+ composite_key = f"{base_session_id}:{working_path}"+ logger.error(f"Error in message receiver for session {composite_key}: {e}", exc_info=True)+ await self.session_handler.handle_session_error(composite_key, context, e)++ async def handle_callback_query(self, context: MessageContext, callback_data: str):+ """Route callback queries to appropriate handlers"""+ try:+ logger.info(f"handle_callback_query called with data: {callback_data} for user {context.user_id}")++ # Import handlers to avoid circular dependency+ from .settings_handler import SettingsHandler+ from .command_handlers import CommandHandlers++ settings_handler = SettingsHandler(self.controller)+ command_handlers = CommandHandlers(self.controller)++ # Route based on callback data+ if callback_data.startswith("toggle_msg_"):+ # Toggle message type visibility+ msg_type = callback_data.replace("toggle_msg_", "")+ await settings_handler.handle_toggle_message_type(context, msg_type)+ elif callback_data.startswith("toggle_"):+ # Legacy toggle handler (if any)+ setting_type = callback_data.replace("toggle_", "")+ if hasattr(settings_handler, 'handle_toggle_setting'):+ await settings_handler.handle_toggle_setting(context, setting_type)++ elif callback_data == "info_msg_types":+ logger.info(f"Handling info_msg_types callback for user {context.user_id}")+ await settings_handler.handle_info_message_types(context)++ elif callback_data == "info_how_it_works":+ await settings_handler.handle_info_how_it_works(context)++ elif callback_data == "cmd_cwd":+ await command_handlers.handle_cwd(context)++ elif callback_data == "cmd_change_cwd":+ await command_handlers.handle_change_cwd_modal(context)++ elif callback_data == "cmd_clear":+ await command_handlers.handle_clear(context)++ elif callback_data == "cmd_settings":+ await settings_handler.handle_settings(context)++ elif callback_data.startswith("info_") and callback_data != "info_msg_types":+ # Generic info handler+ info_type = callback_data.replace("info_", "")+ info_text = self.formatter.format_info_message(+ title=f"Info: {info_type}",+ emoji="ℹ️",+ footer="This feature is coming soon!"+ )+ await self.im_client.send_message(context, info_text)++ else:+ logger.warning(f"Unknown callback data: {callback_data}")+ await self.im_client.send_message(+ context,+ self.formatter.format_warning(f"Unknown action: {callback_data}")+ )++ except Exception as e:+ logger.error(f"Error handling callback query: {e}", exc_info=True)+ await self.im_client.send_message(+ context,+ self.formatter.format_error(f"Error processing action: {str(e)}")+ )\ No newline at end of filediff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pynew file mode 100644index 000000000..61d024516--- /dev/null+++ b/core/handlers/session_handler.py@@ -0,0 +1,207 @@+"""Session management handlers for Claude SDK sessions"""++import os+import logging+from typing import Optional, Dict, Any, Tuple+from modules.im import MessageContext+from claude_code_sdk import ClaudeSDKClient, ClaudeCodeOptions++logger = logging.getLogger(__name__)+++class SessionHandler:+ """Handles all session-related operations"""++ def __init__(self, controller):+ """Initialize with reference to main controller"""+ self.controller = controller+ self.config = controller.config+ self.im_client = controller.im_client+ self.session_manager = controller.session_manager+ self.settings_manager = controller.settings_manager+ self.formatter = controller.im_client.formatter+ self.claude_sessions = controller.claude_sessions+ self.receiver_tasks = controller.receiver_tasks+ self.stored_session_mappings = controller.stored_session_mappings++ def get_base_session_id(self, context: MessageContext) -> str:+ """Get base session ID based on platform and context (without path)"""+ if self.config.platform == "telegram":+ # For Telegram, use channel/chat ID+ return f"telegram_{context.channel_id}"+ elif self.config.platform == "slack":+ # For Slack, use thread ID if available, otherwise channel ID+ if context.thread_id:+ return f"slack_{context.thread_id}"+ else:+ return f"slack_{context.channel_id}"+ else:+ # Default to user ID+ return f"{self.config.platform}_{context.user_id}"++ def get_working_path(self) -> str:+ """Get normalized working directory path"""+ working_dir = self.config.claude.cwd+ if working_dir:+ return os.path.abspath(os.path.expanduser(working_dir))+ return os.getcwd()++ def get_session_info(self, context: MessageContext) -> Tuple[str, str, str]:+ """Get session info: base_session_id, working_path, and composite_key"""+ base_session_id = self.get_base_session_id(context)+ working_path = self.get_working_path()+ # Create composite key for internal storage+ composite_key = f"{base_session_id}:{working_path}"+ return base_session_id, working_path, composite_key++ async def get_or_create_claude_session(self, context: MessageContext) -> ClaudeSDKClient:+ """Get existing Claude session or create a new one"""+ base_session_id, working_path, composite_key = self.get_session_info(context)++ if composite_key in self.claude_sessions:+ logger.info(f"Using existing Claude SDK client for {base_session_id} at {working_path}")+ return self.claude_sessions[composite_key]++ # Check if we have a stored session mapping+ stored_claude_session_id = self.settings_manager.get_claude_session_id(+ context.user_id, base_session_id, working_path+ )++ # Ensure working directory exists+ if not os.path.exists(working_path):+ try:+ os.makedirs(working_path, exist_ok=True)+ logger.info(f"Created working directory: {working_path}")+ except Exception as e:+ logger.error(f"Failed to create working directory {working_path}: {e}")+ working_path = os.getcwd()++ # Create options for Claude client+ options = ClaudeCodeOptions(+ permission_mode=self.config.claude.permission_mode,+ cwd=working_path,+ system_prompt=self.config.claude.system_prompt,+ resume=stored_claude_session_id if stored_claude_session_id else None+ )++ # Log session creation details+ logger.info(f"Creating Claude client for {base_session_id} at {working_path}")+ logger.info(f" Working directory: {working_path}")+ logger.info(f" Resume session ID: {stored_claude_session_id}")+ logger.info(f" Options.resume: {options.resume}")++ # Log if we're resuming a session+ if stored_claude_session_id:+ logger.info(f"Attempting to resume Claude session {stored_claude_session_id}")+ else:+ logger.info(f"Creating new Claude session")++ # Create new Claude client+ client = ClaudeSDKClient(options=options)++ # Log the actual options being used+ logger.info(f"ClaudeCodeOptions details:")+ logger.info(f" - permission_mode: {options.permission_mode}")+ logger.info(f" - cwd: {options.cwd}")+ logger.info(f" - system_prompt: {options.system_prompt}")+ logger.info(f" - resume: {options.resume}")+ logger.info(f" - continue_conversation: {options.continue_conversation}")++ # Connect the client+ await client.connect()++ self.claude_sessions[composite_key] = client+ logger.info(f"Created new Claude SDK client for {base_session_id} at {working_path}")++ return client++ async def cleanup_session(self, composite_key: str):+ """Clean up a specific session by composite key"""+ # Cancel receiver task if exists+ if composite_key in self.receiver_tasks:+ task = self.receiver_tasks[composite_key]+ if not task.done():+ task.cancel()+ try:+ await task+ except Exception:+ pass+ del self.receiver_tasks[composite_key]+ logger.info(f"Cancelled receiver task for session {composite_key}")++ # Cleanup Claude session+ if composite_key in self.claude_sessions:+ client = self.claude_sessions[composite_key]+ try:+ await client.disconnect()+ except Exception as e:+ logger.error(f"Error disconnecting Claude session {composite_key}: {e}")+ del self.claude_sessions[composite_key]+ logger.info(f"Cleaned up Claude session {composite_key}")++ async def handle_session_error(self, composite_key: str, context: MessageContext, error: Exception):+ """Handle session-related errors"""+ error_msg = str(error)++ # Check for specific error types+ if "read() called while another coroutine" in error_msg:+ logger.error(f"Session {composite_key} has concurrent read error - cleaning up")+ await self.cleanup_session(composite_key)++ # Notify user and suggest retry+ await self.im_client.send_message(+ context,+ self.formatter.format_error(+ "Session error detected. Session has been reset. Please try your message again."+ )+ )+ elif "Session is broken" in error_msg or "Connection closed" in error_msg or "Connection lost" in error_msg:+ logger.error(f"Session {composite_key} is broken - cleaning up")+ await self.cleanup_session(composite_key)++ # Notify user+ await self.im_client.send_message(+ context,+ self.formatter.format_error(+ "Connection to Claude was lost. Please try your message again."+ )+ )+ else:+ # Generic error handling+ logger.error(f"Error in session {composite_key}: {error}")+ await self.im_client.send_message(+ context,+ self.formatter.format_error(f"An error occurred: {error_msg}")+ )++ def capture_session_id(self, base_session_id: str, working_path: str, claude_session_id: str, user_id: str):+ """Capture and store Claude session ID mapping"""+ # Persist to settings with nested structure+ self.settings_manager.set_session_mapping(user_id, base_session_id, working_path, claude_session_id)++ logger.info(f"Captured Claude session_id: {claude_session_id} for {base_session_id} at {working_path}")++ def restore_session_mappings(self):+ """Restore session mappings from settings on startup"""+ logger.info("Initializing session mappings from saved settings...")++ # Get all user settings+ all_settings = self.settings_manager.settings++ restored_count = 0+ for user_id, user_settings in all_settings.items():+ if hasattr(user_settings, 'session_mappings') and user_settings.session_mappings:+ # Handle both old flat structure and new nested structure+ for key, value in user_settings.session_mappings.items():+ if isinstance(value, dict):+ # New nested structure: {base_session_id: {path: claude_session_id}}+ logger.info(f"Found {len(value)} path mappings for {key} (user {user_id})")+ for path, claude_session_id in value.items():+ logger.info(f" - {key}[{path}] -> {claude_session_id}")+ restored_count += 1+ else:+ # Old flat structure (for backward compatibility)+ logger.info(f" - {key} -> {value} (legacy format)")+ restored_count += 1++ logger.info(f"Session restoration complete. Restored {restored_count} session mappings.")\ No newline at end of filediff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.pynew file mode 100644index 000000000..be472446c--- /dev/null+++ b/core/handlers/settings_handler.py@@ -0,0 +1,209 @@+"""Settings and configuration handlers"""++import logging+from modules.im import MessageContext, InlineKeyboard, InlineButton++logger = logging.getLogger(__name__)+++class SettingsHandler:+ """Handles settings and configuration operations"""++ def __init__(self, controller):+ """Initialize with reference to main controller"""+ self.controller = controller+ self.config = controller.config+ self.im_client = controller.im_client+ self.settings_manager = controller.settings_manager+ self.formatter = controller.im_client.formatter++ def _get_settings_key(self, context: MessageContext) -> str:+ """Get settings key based on context"""+ # For Telegram groups, use channel ID+ # For everything else (DMs, Slack), use user ID+ if self.config.platform == "telegram" and context.channel_id != context.user_id:+ return context.channel_id+ return context.user_id++ async def handle_settings(self, context: MessageContext, args: str = ""):+ """Handle settings command - show settings menu"""+ try:+ # For Slack, use modal dialog+ if self.config.platform == "slack":+ await self._handle_settings_slack(context)+ else:+ # For other platforms, use inline keyboard+ await self._handle_settings_traditional(context)++ except Exception as e:+ logger.error(f"Error showing settings: {e}")+ await self.im_client.send_message(+ context,+ f"❌ Error showing settings: {str(e)}"+ )++ async def _handle_settings_traditional(self, context: MessageContext):+ """Handle settings for non-Slack platforms (Telegram, etc)"""+ # Get current settings+ settings_key = self._get_settings_key(context)+ user_settings = self.settings_manager.get_user_settings(settings_key)++ # Get available message types and display names+ message_types = self.settings_manager.get_available_message_types()+ display_names = self.settings_manager.get_message_type_display_names()++ # Create inline keyboard buttons in 2x2 layout+ buttons = []+ row = []++ for i, msg_type in enumerate(message_types):+ is_hidden = msg_type in user_settings.hidden_message_types+ checkbox = "☑️" if is_hidden else "⬜"+ display_name = display_names.get(msg_type, msg_type)+ button = InlineButton(+ text=f"{checkbox} Hide {display_name}",+ callback_data=f"toggle_msg_{msg_type}"+ )+ row.append(button)++ # Create 2x2 layout+ if len(row) == 2 or i == len(message_types) - 1:+ buttons.append(row)+ row = []++ # Add info button on its own row+ buttons.append([InlineButton("ℹ️ About Message Types", callback_data="info_msg_types")])++ keyboard = InlineKeyboard(buttons=buttons)++ # Send settings message with escaped dash+ await self.im_client.send_message_with_buttons(+ context,+ "⚙️ *Settings \\- Message Visibility*\n\nSelect which message types to hide from Claude output:",+ keyboard+ )++ async def _handle_settings_slack(self, context: MessageContext):+ """Handle settings for Slack using modal dialog"""+ # For slash commands or direct triggers, we might have trigger_id+ trigger_id = context.platform_specific.get('trigger_id') if context.platform_specific else None++ if trigger_id and hasattr(self.im_client, 'open_settings_modal'):+ # We have trigger_id, open modal directly+ settings_key = self._get_settings_key(context)+ user_settings = self.settings_manager.get_user_settings(settings_key)+ message_types = self.settings_manager.get_available_message_types()+ display_names = self.settings_manager.get_message_type_display_names()++ try:+ await self.im_client.open_settings_modal(trigger_id, user_settings, message_types, display_names, context.channel_id)+ except Exception as e:+ logger.error(f"Error opening settings modal: {e}")+ await self.im_client.send_message(context, "❌ Failed to open settings. Please try again.")+ else:+ # No trigger_id, show button to open modal+ buttons = [[+ InlineButton(+ text="🛠️ Open Settings",+ callback_data="open_settings_modal"+ )+ ]]++ keyboard = InlineKeyboard(buttons=buttons)++ await self.im_client.send_message_with_buttons(+ context,+ "⚙️ *Personalization Settings*\n\nConfigure how Claude Code messages appear in your Slack workspace.",+ keyboard+ )++ async def handle_toggle_message_type(self, context: MessageContext, msg_type: str):+ """Handle toggle for message type visibility"""+ try:+ # Toggle message type visibility+ settings_key = self._get_settings_key(context)+ is_hidden = self.settings_manager.toggle_hidden_message_type(settings_key, msg_type)++ # Update the keyboard+ user_settings = self.settings_manager.get_user_settings(settings_key)+ message_types = self.settings_manager.get_available_message_types()+ display_names = self.settings_manager.get_message_type_display_names()++ buttons = []+ row = []++ for i, mt in enumerate(message_types):+ is_hidden_now = mt in user_settings.hidden_message_types+ checkbox = "☑️" if is_hidden_now else "⬜"+ display_name = display_names.get(mt, mt)+ button = InlineButton(+ text=f"{checkbox} Hide {display_name}",+ callback_data=f"toggle_msg_{mt}"+ )+ row.append(button)++ # Create 2x2 layout+ if len(row) == 2 or i == len(message_types) - 1:+ buttons.append(row)+ row = []++ buttons.append([InlineButton("ℹ️ About Message Types", callback_data="info_msg_types")])++ keyboard = InlineKeyboard(buttons=buttons)++ # Update message+ if context.message_id:+ await self.im_client.edit_message(+ context,+ context.message_id,+ keyboard=keyboard+ )++ # Answer callback (for Telegram)+ display_name = display_names.get(msg_type, msg_type)+ action = "hidden" if is_hidden else "shown"++ # Platform-specific callback answering+ if self.config.platform == "telegram":+ # For Telegram, we need the actual callback query object+ # This is handled in the telegram bot handler+ pass+ elif self.config.platform == "slack":+ # For Slack, we might send an ephemeral message+ await self.im_client.send_message(+ context,+ f"{display_name} messages are now {action}"+ )++ except Exception as e:+ logger.error(f"Error toggling message type {msg_type}: {e}")+ await self.im_client.send_message(+ context,+ self.formatter.format_error(f"Failed to toggle setting: {str(e)}")+ )++ async def handle_info_message_types(self, context: MessageContext):+ """Show information about different message types"""+ try:+ formatter = self.im_client.formatter++ # Use the new format_info_message method for clean, platform-agnostic formatting+ info_text = formatter.format_info_message(+ title="Message Types Info:",+ emoji="📋",+ items=[+ ("System", "System initialization and status messages"),+ ("Response", "Tool execution responses and results"),+ ("Assistant", "Claude's messages and explanations"),+ ("Result", "Final execution results and summaries")+ ],+ footer="Hidden messages won't be sent to your IM platform."+ )++ # Send as new message+ await self.im_client.send_message(context, info_text)+ logger.info(f"Sent info_msg_types message to user {context.user_id}")++ except Exception as e:+ logger.error(f"Error in info_msg_types handler: {e}", exc_info=True)+ await self.im_client.send_message(context, "❌ Error showing message types info")\ No newline at end of filediff --git a/main.py b/main.pyindex 05377b4a4..e6db12680 100644--- a/main.py+++ b/main.py@@ -2,19 +2,26 @@import osimport sysimport logging+import asynciofrom dotenv import load_dotenvfrom config.settings import AppConfig-from core.controller import Controller+from core.controller_refactored import Controller# Load environment variables from .env fileload_dotenv()def setup_logging(level: str = "INFO"):- """Setup logging configuration"""+ """Setup logging configuration with file location and line numbers"""+ # Create a custom formatter with file location+ log_format = '%(asctime)s - %(name)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(funcName)s() - %(message)s'++ # For development, you can use this more detailed format:+ # log_format = '%(asctime)s - %(name)s - %(levelname)s - [%(pathname)s:%(lineno)d] - %(funcName)s() - %(message)s'+logging.basicConfig(level=getattr(logging, level.upper()),- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',+ format=log_format,handlers=[logging.StreamHandler(sys.stdout),logging.FileHandler('claude_proxy.log')diff --git a/modules/im/formatters/base_formatter.py b/modules/im/formatters/base_formatter.pyindex c52ff5dd0..cc62f35e8 100644--- a/modules/im/formatters/base_formatter.py+++ b/modules/im/formatters/base_formatter.py@@ -5,103 +5,103 @@ import jsonclass BaseMarkdownFormatter(ABC):"""Abstract base class for platform-specific markdown formatters"""-+# Common formatting methods that work across platformsdef format_code_inline(self, text: str) -> str:"""Format inline code - same for most platforms"""return f"`{text}`"-+def format_code_block(self, code: str, language: str = "") -> str:"""Format code block - same for most platforms"""return f"```{language}\n{code}\n```"-+def format_emoji(self, emoji: str) -> str:"""Format emoji - same for all platforms"""return emoji-+def format_quote(self, text: str) -> str:"""Format quoted text - commonly using >"""- lines = text.split('\n')- return '\n'.join(f"> {line}" for line in lines)-+ lines = text.split("\n")+ return "\n".join(f"> {line}" for line in lines)+def format_list_item(self, text: str, level: int = 0) -> str:"""Format list item with indentation"""indent = " " * levelreturn f"{indent}• {text}"-+def format_numbered_list_item(self, text: str, number: int, level: int = 0) -> str:"""Format numbered list item"""indent = " " * levelreturn f"{indent}{number}. {text}"-+def format_horizontal_rule(self) -> str:"""Format horizontal rule"""return "---"-+# Core text formatting methoddef format_text(self, text: str, safe: bool = False) -> str:"""Format plain text with automatic escaping-+Args:text: The text to formatsafe: If True, text is already escaped/formatted and won't be escaped again-+Returns:Formatted text with special characters escaped"""if safe:return textreturn self.escape_special_chars(text)-+def format_plain(self, text: str) -> str:"""Alias for format_text - formats plain text with escaping"""return self.format_text(text)-+# Platform-specific abstract methods@abstractmethoddef format_bold(self, text: str) -> str:"""Format bold text - platform specific"""pass-+@abstractmethoddef format_italic(self, text: str) -> str:"""Format italic text - platform specific"""pass-+@abstractmethoddef format_strikethrough(self, text: str) -> str:"""Format strikethrough text - platform specific"""pass-+@abstractmethoddef format_link(self, text: str, url: str) -> str:"""Format hyperlink - platform specific"""pass-+@abstractmethoddef escape_special_chars(self, text: str) -> str:"""Escape platform-specific special characters"""pass-+# High-level message composition methodsdef format_message(self, *lines) -> str:"""Compose a message from multiple lines-+Args:*lines: Variable number of lines to compose-+Returns:Formatted message with proper line breaks"""return "\n".join(str(line) for line in lines if line)-+def format_bullet_list(self, items: List[str], escape: bool = True) -> List[str]:"""Format a list of items as bullet points-+Args:items: List of items to formatescape: Whether to escape special characters in items-+Returns:List of formatted bullet points"""@@ -111,27 +111,29 @@ class BaseMarkdownFormatter(ABC):item = self.format_text(item)formatted.append(f"• {item}")return formatted-+def format_definition_item(self, label: str, description: str) -> str:"""Format a single definition item with label and description-+Args:label: The label/key textdescription: The description text-+Returns:Formatted definition item"""# Default implementation - subclasses can override for platform-specific needsreturn f"• {self.format_bold(label)} - {self.format_text(description)}"-- def format_definition_list(self, items: List[Tuple[str, str]], bold_key: bool = True) -> List[str]:++ def format_definition_list(+ self, items: List[Tuple[str, str]], bold_key: bool = True+ ) -> List[str]:"""Format a list of key-value pairs-+Args:items: List of (key, value) tuplesbold_key: Whether to make keys bold-+Returns:List of formatted definition items"""@@ -144,56 +146,62 @@ class BaseMarkdownFormatter(ABC):value_part = self.format_text(value)formatted.append(f"• {key_part} - {value_part}")return formatted-- def format_info_message(self, title: str, emoji: str = "", items: List[Tuple[str, str]] = None, footer: str = "") -> str:++ def format_info_message(+ self,+ title: str,+ emoji: str = "",+ items: List[Tuple[str, str]] = None,+ footer: str = "",+ ) -> str:"""Format a complete info message with title, items, and optional footer-+Args:title: Message titleemoji: Optional emoji for titleitems: Optional list of (label, description) tuplesfooter: Optional footer text-+Returns:Formatted info message"""lines = []-+# Add headerif emoji:lines.append(f"{emoji} {self.format_bold(title)}")else:lines.append(self.format_bold(title))-+# Add blank line after headerif items or footer:lines.append("")-+# Add itemsif items:for label, description in items:# Use a platform-specific separator methodlines.append(self.format_definition_item(label, description))-+# Add footerif footer:if items:lines.append("")lines.append(self.format_text(footer))-+return self.format_message(*lines)-+# Convenience methods that combine formattingdef format_tool_name(self, tool_name: str, emoji: str = "🔧") -> str:"""Format tool name with emoji and styling"""escaped_name = self.escape_special_chars(tool_name)return f"{emoji} {self.format_bold('Tool')}: {self.format_code_inline(escaped_name)}"-+def format_file_path(self, path: str, emoji: str = "📁") -> str:"""Format file path with emoji"""escaped_path = self.escape_special_chars(path)return f"{emoji} File: {self.format_code_inline(escaped_path)}"-+def format_command(self, command: str) -> str:"""Format shell command"""# For multi-line or long commands, use code block@@ -202,56 +210,64 @@ class BaseMarkdownFormatter(ABC):else:escaped_cmd = self.escape_special_chars(command)return f"💻 Command: {self.format_code_inline(escaped_cmd)}"-+def format_error(self, error_text: str) -> str:"""Format error message"""- return f"❌ {self.format_bold('Error')}: {self.escape_special_chars(error_text)}"-+ return (+ f"❌ {self.format_bold('Error')}: {self.escape_special_chars(error_text)}"+ )+def format_success(self, message: str) -> str:"""Format success message"""return f"✅ {self.escape_special_chars(message)}"-+def format_warning(self, warning_text: str) -> str:"""Format warning message"""return f"⚠️ {self.format_bold('Warning')}: {self.escape_special_chars(warning_text)}"-+def format_section_header(self, title: str, emoji: str = "") -> str:"""Format section header"""if emoji:return f"{emoji} {self.format_bold(title)}"return self.format_bold(title)-+def format_key_value(self, key: str, value: str, inline: bool = True) -> str:"""Format key-value pair"""escaped_key = self.escape_special_chars(key)escaped_value = self.escape_special_chars(value)-+if inline:return f"{self.format_bold(escaped_key)}: {escaped_value}"else:return f"{self.format_bold(escaped_key)}:\n{escaped_value}"-- def truncate_text(self, text: str, max_length: int = 50, suffix: str = "...") -> str:++ def truncate_text(+ self, text: str, max_length: int = 50, suffix: str = "..."+ ) -> str:"""Truncate text to specified length"""if len(text) <= max_length:return textreturn text[:max_length] + suffix-+# Claude message formatting methods- def format_system_message(self, cwd: str, subtype: str, session_id: Optional[str] = None) -> str:+ def format_system_message(+ self, cwd: str, subtype: str, session_id: Optional[str] = None+ ) -> str:"""Format system message"""header = self.format_section_header(f"System {subtype}", "🔧")- cwd_line = self.format_file_path(cwd, emoji="📁").replace("File:", "Working directory:")-+ cwd_line = self.format_file_path(cwd, emoji="📁").replace(+ "File:", "Working directory:"+ )+# Add session ID if availableif session_id:session_line = f"🔗 Session ID: {self.format_code_inline(session_id)}"- ready_line = f"✨ Ready to work!"+ ready_line = f"✨ {self.format_text('Ready to work!')}"return f"{header}\n{cwd_line}\n{session_line}\n{ready_line}"else:- ready_line = f"✨ Ready to work!"+ ready_line = f"✨ {self.format_text('Ready to work!')}"return f"{header}\n{cwd_line}\n{ready_line}"-+def format_assistant_message(self, content_parts: List[str]) -> str:"""Format assistant message"""header = self.format_section_header("Assistant", "🤖")@@ -259,14 +275,32 @@ class BaseMarkdownFormatter(ABC):escaped_parts = []for part in content_parts:# Only escape if it's plain text (not already formatted with tool info)- if not part.startswith(("🔧", "💻", "🔍", "📖", "✏️", "📝", "📄", "📓", "🌐", "✅", "❌", "🤖", "📂", "🔎", "🚪")):+ if not part.startswith(+ (+ "🔧",+ "💻",+ "🔍",+ "📖",+ "✏️",+ "📝",+ "📄",+ "📓",+ "🌐",+ "✅",+ "❌",+ "🤖",+ "📂",+ "🔎",+ "🚪",+ )+ ):escaped_parts.append(self.escape_special_chars(part))else:# Already formatted tool output, don't escapeescaped_parts.append(part)parts = [header] + escaped_partsreturn "\n\n".join(parts)-+def format_user_message(self, content_parts: List[str]) -> str:"""Format user/response message"""header = self.format_section_header("Response", "👤")@@ -274,93 +308,107 @@ class BaseMarkdownFormatter(ABC):escaped_parts = []for part in content_parts:# Only escape if it's plain text (not already formatted)- if not part.startswith(("🔧", "💻", "🔍", "📖", "✏️", "📝", "📄", "📓", "🌐", "✅", "❌", "🤖", "📂", "🔎", "🚪")):+ if not part.startswith(+ (+ "🔧",+ "💻",+ "🔍",+ "📖",+ "✏️",+ "📝",+ "📄",+ "📓",+ "🌐",+ "✅",+ "❌",+ "🤖",+ "📂",+ "🔎",+ "🚪",+ )+ ):escaped_parts.append(self.escape_special_chars(part))else:# Already formatted output, don't escapeescaped_parts.append(part)parts = [header] + escaped_partsreturn "\n\n".join(parts)-- def format_result_message(self, subtype: str, duration_ms: int, result: Optional[str] = None) -> str:++ def format_result_message(+ self, subtype: str, duration_ms: int, result: Optional[str] = None+ ) -> str:"""Format result message"""# Calculate durationtotal_seconds = duration_ms / 1000minutes = int(total_seconds // 60)seconds = int(total_seconds % 60)-+if minutes > 0:duration_str = f"{minutes}m {seconds}s"else:duration_str = f"{seconds}s"-+# Format result - don't include subtype in parentheses to avoid escaping issuesheader = self.format_section_header("Result", "📊")if subtype:header += f" {self.format_italic(subtype)}"duration_line = self.format_key_value("⏱️ Duration", duration_str)-+result_text = f"{header}\n{duration_line}"-+if result:result_text += f"\n\n{result}"-+return result_text-+def format_tool_result(self, is_error: bool, content: Optional[str] = None) -> str:"""Format tool result block"""emoji = "❌" if is_error else "✅"result_info = f"{emoji} {self.format_bold('Tool Result')}"-+if content:content_str = str(content)if len(content_str) > 500:content_str = content_str[:500] + "..."result_info += f"\n{self.format_code_block(content_str)}"-+return result_info-- def format_todo_item(self, status: str, priority: str, content: str, completed: bool = False) -> str:++ def format_todo_item(+ self, status: str, priority: str, content: str, completed: bool = False+ ) -> str:"""Format a todo item with status and priority"""- status_emoji = {- "pending": "⏳",- "in_progress": "🔄",- "completed": "✅"- }.get(status, "⏳")-- priority_emoji = {- "high": "🔴",- "medium": "🟡",- "low": "🟢"- }.get(priority, "🟡")-+ status_emoji = {"pending": "⏳", "in_progress": "🔄", "completed": "✅"}.get(+ status, "⏳"+ )++ priority_emoji = {"high": "🔴", "medium": "🟡", "low": "🟢"}.get(priority, "🟡")+# Truncate long contentif len(content) > 50:content = content[:50] + "..."-+# Apply strikethrough for completed itemsif completed:formatted_content = self.format_strikethrough(content)else:formatted_content = self.escape_special_chars(content)-+return f"• {status_emoji} {priority_emoji} {formatted_content}"-- def format_tool_use(self, tool_name: str, tool_input: Dict[str, Any],- get_relative_path: Optional[callable] = None) -> str:++ def format_tool_use(+ self,+ tool_name: str,+ tool_input: Dict[str, Any],+ get_relative_path: Optional[callable] = None,+ ) -> str:"""Format tool use block with inputs"""# Determine tool emoji and categoryif tool_name.startswith("mcp__"):tool_category = tool_name.split("__")[1] if "__" in tool_name else "mcp"- emoji_map = {- "devmcp": "🔧",- "db": "🗃️",- "log": "📊",- "ops": "⚡",- "human": "👤",- }- emoji = emoji_map.get(tool_category, "🔧")- tool_info = f"{emoji} {self.format_bold('MCP Tool')}: {self.format_code_inline(tool_name)}"++ emoji = "🔧"+ tool_info = f"{emoji} {tool_category} {self.format_bold('MCP Tool')}: {self.format_code_inline(tool_name)}"else:tool_emoji_map = {"Task": "🤖",@@ -381,110 +429,128 @@ class BaseMarkdownFormatter(ABC):}emoji = tool_emoji_map.get(tool_name, "🔧")tool_info = f"{emoji} {self.format_bold('Tool')}: {self.format_code_inline(tool_name)}"-+# Format tool inputsinput_info = []-+# File operationsif "file_path" in tool_input and tool_input["file_path"]:path = tool_input["file_path"]if get_relative_path:path = get_relative_path(path)input_info.append(self.format_file_path(path))-+# Path operationsif "path" in tool_input and tool_input["path"]:path = tool_input["path"]if get_relative_path:path = get_relative_path(path)input_info.append(self.format_file_path(path, emoji="📂"))-+# Command operationsif "command" in tool_input and tool_input["command"]:input_info.append(self.format_command(tool_input["command"]))-+# Descriptionif "description" in tool_input and tool_input["description"]:- input_info.append(f"📝 Description: {self.format_code_inline(tool_input['description'])}")-+ input_info.append(+ f"📝 Description: {self.format_code_inline(tool_input['description'])}"+ )+# Pattern/Queryif "pattern" in tool_input and tool_input["pattern"]:- input_info.append(f"🔍 Pattern: {self.format_code_inline(tool_input['pattern'])}")-+ input_info.append(+ f"🔍 Pattern: {self.format_code_inline(tool_input['pattern'])}"+ )+if "query" in tool_input and tool_input["query"]:query_str = str(tool_input["query"])truncated = self.truncate_text(query_str, 50)input_info.append(f"🔍 Query: {self.format_code_inline(truncated)}")-+# URLif "url" in tool_input and tool_input["url"]:- input_info.append(f"🌐 URL: {self.format_code_inline(str(tool_input['url']))}")-+ input_info.append(+ f"🌐 URL: {self.format_code_inline(str(tool_input['url']))}"+ )+# Promptif "prompt" in tool_input and tool_input["prompt"]:prompt_str = str(tool_input["prompt"])truncated = self.truncate_text(prompt_str, 100)input_info.append(f"📝 Prompt: {self.escape_special_chars(truncated)}")-+# Edit operationsif "old_string" in tool_input and tool_input["old_string"]:old_str = self.truncate_text(str(tool_input["old_string"]), 50)input_info.append(f"🔍 Old: {self.format_code_inline(old_str)}")-+if "new_string" in tool_input and tool_input["new_string"]:new_str = self.truncate_text(str(tool_input["new_string"]), 50)input_info.append(f"✏️ New: {self.format_code_inline(new_str)}")-+# MultiEditif "edits" in tool_input and tool_input["edits"]:edits_count = len(tool_input["edits"])input_info.append(f"📝 Edits: {edits_count} changes")-+# Other common parametersif "limit" in tool_input and tool_input["limit"]:input_info.append(f"🔢 Limit: {tool_input['limit']}")-+if "offset" in tool_input and tool_input["offset"]:input_info.append(f"📍 Offset: {tool_input['offset']}")-+# Task toolif "subagent_type" in tool_input and tool_input["subagent_type"]:- input_info.append(f"🤖 Agent: {self.format_code_inline(str(tool_input['subagent_type']))}")-+ input_info.append(+ f"🤖 Agent: {self.format_code_inline(str(tool_input['subagent_type']))}"+ )+if "plan" in tool_input and tool_input["plan"]:plan_str = self.truncate_text(str(tool_input["plan"]), 100)input_info.append(f"📋 Plan: {self.escape_special_chars(plan_str)}")-+# Notebook operationsif "cell_id" in tool_input and tool_input["cell_id"]:- input_info.append(f"📊 Cell ID: {self.format_code_inline(str(tool_input['cell_id']))}")-+ input_info.append(+ f"📊 Cell ID: {self.format_code_inline(str(tool_input['cell_id']))}"+ )+if "cell_type" in tool_input and tool_input["cell_type"]:- input_info.append(f"📝 Cell Type: {self.format_code_inline(str(tool_input['cell_type']))}")-+ input_info.append(+ f"📝 Cell Type: {self.format_code_inline(str(tool_input['cell_type']))}"+ )+# WebSearchif "allowed_domains" in tool_input and tool_input["allowed_domains"]:count = len(tool_input["allowed_domains"])input_info.append(f"✅ Allowed domains: {count}")-+if "blocked_domains" in tool_input and tool_input["blocked_domains"]:count = len(tool_input["blocked_domains"])input_info.append(f"🚫 Blocked domains: {count}")-+# Grep specificif "glob" in tool_input and tool_input["glob"]:- input_info.append(f"🎯 Glob: {self.format_code_inline(str(tool_input['glob']))}")-+ input_info.append(+ f"🎯 Glob: {self.format_code_inline(str(tool_input['glob']))}"+ )+if "type" in tool_input and tool_input["type"]:- input_info.append(f"📄 Type: {self.format_code_inline(str(tool_input['type']))}")-+ input_info.append(+ f"📄 Type: {self.format_code_inline(str(tool_input['type']))}"+ )+if "output_mode" in tool_input and tool_input["output_mode"]:- input_info.append(f"📊 Output mode: {self.format_code_inline(str(tool_input['output_mode']))}")-+ input_info.append(+ f"📊 Output mode: {self.format_code_inline(str(tool_input['output_mode']))}"+ )+# Combine tool info with inputsif input_info:tool_info += "\n" + "\n".join(input_info)-+# Handle special tool content formattingif tool_name == "TodoWrite" and "todos" in tool_input:todos = tool_input["todos"]@@ -496,26 +562,37 @@ class BaseMarkdownFormatter(ABC):completed = status == "completed"todo_line = self.format_todo_item(status, priority, content, completed)tool_info += f"\n{todo_line}"-+elif tool_name in ["Write", "Edit", "MultiEdit"] and "content" in tool_input:content = str(tool_input["content"])if len(content) > 300:content = content[:300] + "..."tool_info += f"\n{self.format_code_block(content)}"-+elif self._should_show_json(tool_name, tool_input):try:input_json = json.dumps(tool_input, indent=2, ensure_ascii=False)tool_info += f"\n{self.format_code_block(input_json, 'json')}"except:tool_info += f"\n{self.format_code_block(str(tool_input))}"-+return tool_info-+def _should_show_json(self, tool_name: str, tool_input: Dict[str, Any]) -> bool:"""Determine if JSON should be shown for tool input"""no_json_tools = [- "Bash", "Read", "Write", "Edit", "MultiEdit",- "LS", "Glob", "Grep", "WebFetch", "WebSearch", "TodoWrite"+ "Bash",+ "Read",+ "Write",+ "Edit",+ "MultiEdit",+ "LS",+ "Glob",+ "Grep",+ "WebFetch",+ "WebSearch",+ "TodoWrite",]- return tool_name not in no_json_tools and tool_input and len(str(tool_input)) < 200\ No newline at end of file+ return (+ tool_name not in no_json_tools and tool_input and len(str(tool_input)) < 200+ )diff --git a/modules/im/formatters/telegram_formatter.py b/modules/im/formatters/telegram_formatter.pyindex 974c42d1f..6fbf0e760 100644--- a/modules/im/formatters/telegram_formatter.py+++ b/modules/im/formatters/telegram_formatter.py@@ -1,100 +1,53 @@-from telegram.helpers import escape_markdownfrom .base_formatter import BaseMarkdownFormatterclass TelegramFormatter(BaseMarkdownFormatter):- """Telegram MarkdownV2 formatter+ """Telegram formatter that outputs standard markdown- Telegram uses MarkdownV2 which requires extensive escaping of special characters.- Reference: https://core.telegram.org/bots/api#markdownv2-style+ This formatter outputs clean markdown that will be converted to HTML+ before sending to Telegram, avoiding MarkdownV2 escaping issues entirely."""+ # Tool output emoji prefixes that indicate pre-formatted content+ TOOL_EMOJI_PREFIXES = ("🔧", "💻", "🔍", "📖", "✏️", "📝", "📄", "📓", "🌐", "✅", "❌", "🤖", "📂", "🔎", "🚪")++ # ============================================================================+ # Core abstract method implementations - Standard Markdown+ # ============================================================================+def format_bold(self, text: str) -> str:- """Format bold text using double asterisks"""- # In MarkdownV2, text inside bold still needs escaping- escaped_text = self.escape_special_chars(text)- return f"*{escaped_text}*"+ """Format bold text in standard markdown"""+ return f"**{text}**"def format_italic(self, text: str) -> str:- """Format italic text using underscores"""- # In MarkdownV2, text inside italic still needs escaping- escaped_text = self.escape_special_chars(text)- return f"_{escaped_text}_"+ """Format italic text in standard markdown"""+ return f"*{text}*"def format_strikethrough(self, text: str) -> str:- """Format strikethrough text using tildes"""- # In MarkdownV2, text inside strikethrough still needs escaping- escaped_text = self.escape_special_chars(text)- return f"~{escaped_text}~"+ """Format strikethrough text in standard markdown"""+ return f"~~{text}~~"def format_link(self, text: str, url: str) -> str:- """Format hyperlink in Telegram style"""- escaped_text = self.escape_special_chars(text)- # URL should not be escaped in links- return f"[{escaped_text}]({url})"+ """Format hyperlink in standard markdown"""+ return f"[{text}]({url})"def escape_special_chars(self, text: str) -> str:- """Escape Telegram MarkdownV2 special characters-- Telegram MarkdownV2 requires escaping these characters:- '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!'- """- # Use Telegram's built-in escape function- return escape_markdown(text, version=2)-- def format_code_inline(self, text: str) -> str:- """Format inline code - override to handle escaping properly"""- # Code content should not be escaped inside backticks- return f"`{text}`"-- def format_code_block(self, code: str, language: str = "") -> str:- """Format code block - override to handle escaping properly"""- # Code content should not be escaped inside code blocks- return f"```{language}\n{code}\n```"+ """No escaping needed for HTML conversion - return text as-is"""+ return text- # Override some convenience methods to handle Telegram-specific formatting- def format_tool_name(self, tool_name: str, emoji: str = "🔧") -> str:- """Format tool name with emoji and styling"""- # Don't escape tool_name here as format_code_inline handles it- return f"{emoji} {self.format_bold('Tool')}: {self.format_code_inline(tool_name)}"-- def format_file_path(self, path: str, emoji: str = "📁") -> str:- """Format file path with emoji"""- # Don't escape path here as format_code_inline handles it- return f"{emoji} File: {self.format_code_inline(path)}"-- def format_command(self, command: str) -> str:- """Format shell command"""- # For multi-line or long commands, use code block- if "\n" in command or len(command) > 80:- return f"💻 Command:\n{self.format_code_block(command, 'bash')}"- else:- # Don't escape command here as format_code_inline handles it- return f"💻 Command: {self.format_code_inline(command)}"-- def format_section_header(self, title: str, emoji: str = "") -> str:- """Format section header - Telegram specific"""- if emoji:- return f"{emoji} {self.format_bold(title)}"- return self.format_bold(title)-- def format_definition_item(self, label: str, description: str) -> str:- """Format a definition item with proper escaping for MarkdownV2-- The dash separator needs to be escaped in Telegram MarkdownV2- """- bold_label = self.format_bold(label)- escaped_separator = " \\- " # Escape the dash for MarkdownV2- escaped_description = self.escape_special_chars(description)- return f"• {bold_label}{escaped_separator}{escaped_description}"+ # ============================================================================+ # Override message formatting methods to handle Claude content appropriately+ # ============================================================================- def format_key_value(self, key: str, value: str, inline: bool = True) -> str:- """Format key-value pair"""- # Key is bolded and escaped properly- bold_key = self.format_bold(key)- escaped_value = self.escape_special_chars(value)+ def format_assistant_message(self, content_parts: list[str]) -> str:+ """Format assistant message with clean markdown"""+ header = self.format_section_header("Assistant", "🤖")- if inline:- return f"{bold_key}: {escaped_value}"- else:- return f"{bold_key}:\n{escaped_value}"\ No newline at end of file+ # For HTML conversion, we don't need to escape tool output differently+ # Just join all parts cleanly+ parts = [header] + content_parts+ return "\n\n".join(parts)++ def _is_tool_output(self, text: str) -> bool:+ """Check if text is already formatted tool output"""+ return text.startswith(self.TOOL_EMOJI_PREFIXES)\ No newline at end of filediff --git a/modules/im/telegram.py b/modules/im/telegram.pyindex d8036ac38..2a3d1e842 100644--- a/modules/im/telegram.py+++ b/modules/im/telegram.py@@ -1,6 +1,7 @@import asyncioimport loggingfrom typing import Callable, Optional, Dict, Any+from telegramify_markdown import markdownifyfrom telegram import (Update,Bot,@@ -15,7 +16,6 @@ from telegram.ext import (ContextTypes,CallbackQueryHandler,)-from telegram.helpers import escape_markdownfrom telegram.error import TelegramErrorfrom config.settings import TelegramConfigfrom .base import BaseIMClient, MessageContext, InlineKeyboard, InlineButton@@ -36,8 +36,24 @@ class TelegramBot(BaseIMClient):# Store callback queries for answeringself._callback_queries: Dict[str, Any] = {}+ def _convert_to_markdownv2(self, text: str) -> str:+ """Convert markdown text to Telegram MarkdownV2 format"""+ try:+ # Use telegramify_markdown to convert to MarkdownV2+ return markdownify(text)+ except Exception as e:+ logger.warning(f"Error converting to MarkdownV2: {e}, sending as plain text")+ # Fallback: escape basic special characters+ import re+ # Escape special characters for MarkdownV2+ escape_chars = r'_*[]()~`>#+-=|{}.!'+ for char in escape_chars:+ text = text.replace(char, f'\\{char}')+ return text++def get_default_parse_mode(self) -> str:- """Get the default parse mode for Telegram"""+ """Get the default parse mode for Telegram - uses MarkdownV2"""return "MarkdownV2"def should_use_thread_for_reply(self) -> bool:@@ -197,69 +213,6 @@ class TelegramBot(BaseIMClient):reply_markup=reply_markup,)- async def send_message_smart(- self, chat_id: int, text: str, message_type: str = None- ):- """Send message with smart format fallback for different message types"""- bot = self.application.bot-- # Split long messages- if len(text) > 4000:- for i in range(0, len(text), 4000):- await self.send_message_smart(chat_id, text[i : i + 4000], message_type)- await asyncio.sleep(0.1)- return-- # For result messages, try to preserve formatting- if message_type == "result":- # Try original Markdown first- try:- await bot.send_message(- chat_id=chat_id, text=text, parse_mode="Markdown"- )- return- except TelegramError:- pass-- # Try HTML as fallback- try:- # Simple Markdown to HTML conversion- html_text = self._markdown_to_html(text)- await bot.send_message(- chat_id=chat_id, text=html_text, parse_mode="HTML"- )- return- except TelegramError:- pass-- # Default to escaped MarkdownV2 for all other cases- try:- await bot.send_message(chat_id=chat_id, text=text, parse_mode="MarkdownV2")- except TelegramError:- # Last resort: send as plain text- await bot.send_message(chat_id=chat_id, text=text)-- def _markdown_to_html(self, text: str) -> str:- """Simple Markdown to HTML conversion for common patterns"""- import re-- # First escape HTML entities- text = text.replace("&", "&")- text = text.replace("<", "<")- text = text.replace(">", ">")-- # Convert code blocks (must be done before inline code)- text = re.sub(r"```([^`]+)```", r"<pre>\1</pre>", text, flags=re.DOTALL)- text = re.sub(r"`([^`]+)`", r"<code>\1</code>", text)-- # Convert bold and italic- text = re.sub(r"\*\*([^*]+)\*\*", r"<b>\1</b>", text)- text = re.sub(r"\*([^*]+)\*", r"<i>\1</i>", text)-- # Convert links- text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r'<a href="\2">\1</a>', text)-- return textdef run(self):"""Run the bot with infinite retry mechanism"""@@ -310,22 +263,12 @@ class TelegramBot(BaseIMClient):# Convert MessageContext to Telegram chat_idchat_id = int(context.channel_id)- # Handle thread_id as reply_to_message_id in Telegram- kwargs = {"chat_id": chat_id, "text": text}-- # Default to MarkdownV2 for Telegram if not specified- if parse_mode:- # Handle different parse modes:- # 'markdown' (from Slack) -> 'Markdown' (Telegram v1)- # 'Markdown' -> keep as is (Telegram v1)- # 'MarkdownV2' -> keep as is (Telegram v2)- if parse_mode == "markdown":- kwargs["parse_mode"] = "Markdown"- else:- kwargs["parse_mode"] = parse_mode- else:- # Default to MarkdownV2 for all messages- kwargs["parse_mode"] = "MarkdownV2"+ # Convert markdown to MarkdownV2 for better compatibility+ markdownv2_text = self._convert_to_markdownv2(text)+ kwargs = {"chat_id": chat_id, "text": markdownv2_text}++ # Use MarkdownV2 parse mode+ kwargs["parse_mode"] = parse_mode or "MarkdownV2"if reply_to or context.thread_id:kwargs["reply_to_message_id"] = int(reply_to or context.thread_id)@@ -347,11 +290,8 @@ class TelegramBot(BaseIMClient):"""Send a message with inline buttons - BaseIMClient implementation"""bot = self.application.bot- # Default to MarkdownV2 if not specified- if not parse_mode:- parse_mode = "MarkdownV2"- elif parse_mode == "markdown":- parse_mode = "Markdown"+ # Convert markdown to MarkdownV2 for better compatibility+ markdownv2_text = self._convert_to_markdownv2(text)# Convert our generic keyboard to Telegram keyboardtg_keyboard = []@@ -371,8 +311,8 @@ class TelegramBot(BaseIMClient):try:message = await bot.send_message(chat_id=chat_id,- text=text,- parse_mode="Markdown" if parse_mode == "markdown" else parse_mode,+ text=markdownv2_text,+ parse_mode="MarkdownV2",reply_markup=reply_markup,)return str(message.message_id)@@ -497,12 +437,11 @@ class TelegramBot(BaseIMClient):raisedef format_markdown(self, text: str) -> str:- """Format markdown text for Telegram using TelegramFormatter-- This properly escapes special characters for MarkdownV2+ """Format markdown text for Telegram using telegramify_markdown++ Converts standard markdown to Telegram's MarkdownV2 format"""- # Use the formatter to properly escape text- return self.formatter.escape_special_chars(text)+ return self._convert_to_markdownv2(text)def _is_authorized_chat(self, chat_id: int, chat_type: str) -> bool:"""Check if a chat is authorized based on whitelist configuration"""diff --git a/modules/settings_manager.py b/modules/settings_manager.pyindex 77e57f20e..dbe4eb816 100644--- a/modules/settings_manager.py+++ b/modules/settings_manager.py@@ -14,8 +14,8 @@ class UserSettings:"""User personalization settings"""hidden_message_types: List[str] = field(default_factory=list) # Message types to hidecustom_cwd: Optional[str] = None # Custom working directory- # Map of IM session ID (chat_id/thread_id) to Claude session_id- session_mappings: Dict[str, str] = field(default_factory=dict)+ # Nested map: {base_session_id: {working_path: claude_session_id}}+ session_mappings: Dict[str, Dict[str, str]] = field(default_factory=dict)def to_dict(self) -> dict:"""Convert to dictionary for JSON serialization"""@@ -70,10 +70,38 @@ class SettingsManager:def get_user_settings(self, user_id: Union[int, str]) -> UserSettings:"""Get settings for a specific user"""- if user_id not in self.settings:- self.settings[user_id] = UserSettings()- self._save_settings()- return self.settings[user_id]+ # Normalize user_id to handle both int and string forms+ normalized_id = user_id++ # For Telegram, try to find by both int and string forms+ if isinstance(user_id, str) and user_id.isdigit():+ # Try as int first+ int_id = int(user_id)+ if int_id in self.settings:+ return self.settings[int_id]+ # Also check string form+ if user_id in self.settings:+ return self.settings[user_id]+ # Use int form for Telegram+ normalized_id = int_id+ elif isinstance(user_id, int):+ # Check if exists as int+ if user_id in self.settings:+ return self.settings[user_id]+ # Also check string form+ str_id = str(user_id)+ if str_id in self.settings:+ return self.settings[str_id]+ normalized_id = user_id+ else:+ # For Slack and other platforms, keep as string+ if user_id in self.settings:+ return self.settings[user_id]++ # Create new settings if not found+ self.settings[normalized_id] = UserSettings()+ self._save_settings()+ return self.settings[normalized_id]def update_user_settings(self, user_id: Union[int, str], settings: UserSettings):"""Update settings for a specific user"""@@ -132,22 +160,33 @@ class SettingsManager:"result": "Result"}- def set_session_mapping(self, user_id: Union[int, str], im_session_id: str, claude_session_id: str):- """Store mapping between IM session ID and Claude session ID"""+ def set_session_mapping(self, user_id: Union[int, str], base_session_id: str, working_path: str, claude_session_id: str):+ """Store mapping between base session ID, working path, and Claude session ID"""settings = self.get_user_settings(user_id)- settings.session_mappings[im_session_id] = claude_session_id+ if base_session_id not in settings.session_mappings:+ settings.session_mappings[base_session_id] = {}+ settings.session_mappings[base_session_id][working_path] = claude_session_idself.update_user_settings(user_id, settings)- logger.info(f"Stored session mapping for user {user_id}: {im_session_id} -> {claude_session_id}")+ logger.info(f"Stored session mapping for user {user_id}: {base_session_id}[{working_path}] -> {claude_session_id}")- def get_claude_session_id(self, user_id: Union[int, str], im_session_id: str) -> Optional[str]:- """Get Claude session ID for given IM session ID"""+ def get_claude_session_id(self, user_id: Union[int, str], base_session_id: str, working_path: str) -> Optional[str]:+ """Get Claude session ID for given base session ID and working path"""settings = self.get_user_settings(user_id)- return settings.session_mappings.get(im_session_id)+ if base_session_id in settings.session_mappings:+ return settings.session_mappings[base_session_id].get(working_path)+ return None- def clear_session_mapping(self, user_id: Union[int, str], im_session_id: str):- """Clear session mapping for given IM session ID"""+ def clear_session_mapping(self, user_id: Union[int, str], base_session_id: str, working_path: Optional[str] = None):+ """Clear session mapping for given base session ID and optionally working path"""settings = self.get_user_settings(user_id)- if im_session_id in settings.session_mappings:- del settings.session_mappings[im_session_id]- self.update_user_settings(user_id, settings)- logger.info(f"Cleared session mapping for user {user_id}: {im_session_id}")\ No newline at end of file+ if base_session_id in settings.session_mappings:+ if working_path:+ # Clear specific path mapping+ if working_path in settings.session_mappings[base_session_id]:+ del settings.session_mappings[base_session_id][working_path]+ logger.info(f"Cleared session mapping for user {user_id}: {base_session_id}[{working_path}]")+ else:+ # Clear all mappings for this base session+ del settings.session_mappings[base_session_id]+ logger.info(f"Cleared all session mappings for user {user_id}: {base_session_id}")+ self.update_user_settings(user_id, settings)\ No newline at end of filediff --git a/requirements.txt b/requirements.txtindex 790b95f51..57018b688 100644--- a/requirements.txt+++ b/requirements.txt@@ -3,4 +3,5 @@ python-telegram-bot>=20.0python-dotenv>=1.0.0anyio>=4.0.0slack-sdk>=3.26.0-aiohttp>=3.8.0\ No newline at end of file+aiohttp>=3.8.0+telegramify-markdown>=0.5.0\ No newline at end of file