Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

feat: Implement persistent Claude sessions with resume capability

cyhhao98a9e813a036
diff --git a/.env.example b/.env.example
index e61c9901a..43fddddfb 100644
--- a/.env.example
+++ b/.env.example
@@ -7,10 +7,9 @@ TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
# Optional: Whitelist of allowed chat IDs (comma-separated)
# Examples:
-# Empty or []: Only accept private messages (DMs)
# null or omit: Accept all chats
# [123456789,987654321]: Only accept messages from these chat IDs
-TELEGRAM_TARGET_CHAT_ID=
+TELEGRAM_TARGET_CHAT_ID=[]
# ============== Slack Configuration ==============
# Required for Slack
@@ -24,10 +23,9 @@ SLACK_SIGNING_SECRET=your-signing-secret
# Optional: Whitelist of allowed channel IDs (comma-separated)
# Examples:
-# Empty or []: Only accept direct messages (DMs)
# null or omit: Accept all channels
# [C1234567890,C0987654321]: Only accept messages from these channel IDs
-SLACK_TARGET_CHANNEL=
+SLACK_TARGET_CHANNEL=[]
# Optional: Require @mention in channels (ignored in DMs)
# If true, bot only responds when @mentioned in channels. Default: false
@@ -36,7 +34,6 @@ SLACK_REQUIRE_MENTION=false
# Claude Configuration
CLAUDE_PERMISSION_MODE=bypassPermissions
CLAUDE_CWD=./_tmp
-CLAUDE_CONTINUE_CONVERSATION=true
# Optional: Custom system prompt
CLAUDE_SYSTEM_PROMPT=
diff --git a/CLAUDE.md b/CLAUDE.md
index adec4f025..eaa39052b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project Overview
-This is a multi-platform remote control bot for Claude Code, supporting both Telegram and Slack. Users can send messages through IM platforms to execute Claude Code commands remotely. The system provides session management, message queuing, and real-time feedback.
+This is a multi-platform remote control bot for Claude Code, supporting both Telegram and Slack. Users can send messages through IM platforms to execute Claude Code commands remotely. The system provides persistent sessions, real-time feedback, and maintains conversation context.
## Development Commands
@@ -60,9 +60,9 @@ The system uses an abstract factory pattern with platform-agnostic interfaces:
### Key Components
- **Configuration System** (`config/settings.py`): Environment-based config with platform-specific validation
-- **Session Management** (`modules/session_manager.py`): Per-user message queues and execution state
-- **Claude Integration** (`modules/claude_client.py`): Wrapper around Claude Code SDK
-- **Settings Management** (`modules/settings_manager.py`): User preferences and message type visibility
+- **Session Management** (`modules/session_manager.py`): Manages ClaudeSDKClient instances for persistent conversations
+- **Claude Integration** (`modules/claude_client.py`): Message formatting and platform-specific rendering
+- **Settings Management** (`modules/settings_manager.py`): User preferences, message visibility, and session ID mappings
### Platform Implementations
- **TelegramBot** (`modules/telegram_bot.py`): Telegram-specific implementation with inline keyboards
@@ -71,9 +71,9 @@ The system uses an abstract factory pattern with platform-agnostic interfaces:
### Message Flow
1. User sends message via IM platform
2. Platform-specific client converts to `MessageContext`
-3. Controller queues message per user
-4. Claude Code executes message sequentially
-5. Real-time output streamed back through same IM platform
+3. Controller immediately sends message to Claude Code via persistent session
+4. Real-time output streamed back through same IM platform
+5. Conversation context maintained for follow-up messages
## User Interface
@@ -82,21 +82,16 @@ Slack uses a simplified command structure with only one slash command:
- `/start` - Opens the main menu with interactive buttons
All functionality is accessed through buttons in the /start menu:
-- **Queue Status** - Shows current queue status and messages
-- **Execute Queue** - Manually trigger queue processing
-- **Clear Queue** - Remove all pending messages
- **Current Dir** - Display current working directory
- **Change Work Dir** - Open modal to change working directory
+- **Reset Session** - Clear conversation context and start fresh
- **Settings** - Configure message visibility preferences
- **How it Works** - Display help information
### Telegram Commands
Telegram supports traditional slash commands:
- `/start` - Show welcome message and available commands
-- `/status` - Show current queue status
-- `/queue` - Display messages in queue
-- `/execute` - Manually process queue
-- `/clear` - Clear message queue
+- `/clear` - Reset conversation and start fresh
- `/cwd` - Show current working directory
- `/set_cwd <path>` - Change working directory
- `/settings` - Open personalization settings
@@ -129,8 +124,11 @@ Reference `modules/slack_bot.py` for a complete implementation example.
### Slack Thread Handling
Slack conversations are automatically organized into threads. Each user message creates a thread, and all bot responses are posted as replies in that thread for better organization.
-### Session Isolation
-Each user has an independent message queue and execution state managed by `SessionManager`. This allows concurrent users without interference.
+### Session Management
+- **Telegram**: Each chat/group maintains its own Claude session
+- **Slack**: Each thread maintains its own Claude session
+- Sessions persist across messages for continuous conversations
+- Use `/clear` or Reset Session button to start fresh
### Callback System
The controller registers command handlers with IM clients through a callback system, allowing platform-agnostic command handling while preserving platform-specific features (inline keyboards, thread replies, etc.).
@@ -148,4 +146,87 @@ The controller registers command handlers with IM clients through a callback sys
- Comprehensive logging for debugging platform-specific issues
### Socket Mode vs Webhooks
-For Slack, Socket Mode is preferred as it doesn't require public endpoints. The system automatically uses Socket Mode if `SLACK_APP_TOKEN` is provided.
\ No newline at end of file
+For Slack, Socket Mode is preferred as it doesn't require public endpoints. The system automatically uses Socket Mode if `SLACK_APP_TOKEN` is provided.
+
+## Technical Implementation Details
+
+### ClaudeSDKClient vs query()
+The project uses `ClaudeSDKClient` for persistent bidirectional communication instead of the simpler `query()` function. This provides:
+- Persistent WebSocket-like connections per session
+- Real-time message streaming without polling
+- Proper session management with resume capability
+- Better error handling and reconnection support
+
+### Session ID Mapping
+The system captures Claude's internal `session_id` from the `SystemMessage` and maintains a mapping:
+- **Purpose**: Allows precise session restoration after bot restarts
+- **Storage**: Maps IM session IDs (chat_id/thread_id) to Claude session_ids in `user_settings.json`
+- **Usage**: Uses `resume` parameter with stored session_id instead of deprecated `continue_conversation`
+
+### Concurrent Message Handling
+Each session has:
+- A dedicated `ClaudeSDKClient` instance
+- A persistent message receiver task running in the background
+- Proper cleanup mechanisms to prevent resource leaks
+
+### Platform-Specific Markdown Formatting
+Different platforms have unique markdown requirements:
+- **Telegram**: Uses MarkdownV2 with extensive character escaping
+- **Slack**: Uses mrkdwn format with different escaping rules
+- Formatter pattern allows clean separation of concerns
+
+## Common Development Challenges
+
+### Async/Await Error: "read() called while another coroutine is already waiting"
+**Problem**: Multiple coroutines trying to read from the same ClaudeSDKClient
+**Solution**: Implement a single persistent receiver per session that handles all messages
+
+### Session Management Edge Cases
+1. **Bot Restart**: Sessions are restored using stored session_id mappings
+2. **Network Errors**: Broken sessions are cleaned up and recreated automatically
+3. **User Switching Chats**: Each chat/thread maintains independent session
+
+### Debugging Tips
+
+1. **Enable Debug Logging**:
+ ```python
+ logging.basicConfig(level=logging.DEBUG)
+ ```
+
+2. **Check Session State**:
+ - View active sessions in `user_settings.json`
+ - Monitor session creation/cleanup in logs
+ - Use `/cwd` command to verify session is active
+
+3. **Platform-Specific Issues**:
+ - **Telegram**: Check for markdown parsing errors in logs
+ - **Slack**: Verify Socket Mode connection with app-level token
+ - Both: Ensure proper environment variables are set
+
+### Testing Strategies
+
+1. **Session Persistence**:
+ - Send message → Restart bot → Send follow-up message
+ - Verify conversation context is maintained
+
+2. **Concurrent Users**:
+ - Test multiple users sending messages simultaneously
+ - Verify sessions don't interfere with each other
+
+3. **Error Recovery**:
+ - Simulate network errors by disconnecting internet
+ - Verify graceful error messages and recovery
+
+## Performance Optimizations
+
+1. **Message Batching**: Controller processes messages immediately without queuing
+2. **Resource Cleanup**: Proper session cleanup prevents memory leaks
+3. **Lazy Loading**: Claude clients created only when needed
+4. **Persistent Connections**: Reduces overhead of creating new connections
+
+## Security Considerations
+
+1. **Token Storage**: Never commit tokens to git
+2. **Session Isolation**: Each user's sessions are completely isolated
+3. **Command Validation**: All user inputs are validated before execution
+4. **File Path Security**: Working directory restrictions prevent unauthorized access
\ No newline at end of file
diff --git a/config/settings.py b/config/settings.py
index e86e24583..879375fcd 100644
--- a/config/settings.py
+++ b/config/settings.py
@@ -55,7 +55,6 @@ class TelegramConfig(BaseIMConfig):
class ClaudeConfig:
permission_mode: str
cwd: str
- continue_conversation: bool
system_prompt: Optional[str] = None
@classmethod
@@ -68,14 +67,9 @@ class ClaudeConfig:
if not cwd:
raise ValueError("CLAUDE_CWD environment variable is required")
- continue_conversation_str = os.getenv("CLAUDE_CONTINUE_CONVERSATION")
- if continue_conversation_str is None:
- raise ValueError("CLAUDE_CONTINUE_CONVERSATION environment variable is required")
-
return cls(
permission_mode=permission_mode,
cwd=cwd,
- continue_conversation=continue_conversation_str.lower() == "true",
system_prompt=os.getenv("CLAUDE_SYSTEM_PROMPT")
)
diff --git a/core/controller.py b/core/controller.py
index 09e171994..478a0b2a7 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -6,8 +6,9 @@ from config.settings import AppConfig
from modules.im import BaseIMClient, MessageContext, InlineKeyboard, InlineButton, IMFactory
from modules.im.formatters import TelegramFormatter, SlackFormatter
from modules.claude_client import ClaudeClient
-from modules.session_manager import SessionManager
+from modules.session_manager import SessionManager, UserSession
from modules.settings_manager import SettingsManager
+from claude_code_sdk import ClaudeSDKClient, ClaudeCodeOptions
logger = logging.getLogger(__name__)
@@ -44,12 +45,9 @@ class Controller:
# Create command handlers dict
self.command_handlers = {
'start': self.handle_start,
- 'execute': self.handle_execute,
- 'status': self.handle_status,
'clear': self.handle_clear,
'cwd': self.handle_cwd,
'set_cwd': self.handle_set_cwd,
- 'queue': self.handle_queue,
'settings': self.handle_settings
}
@@ -89,18 +87,17 @@ Channel/Chat ID: {context.channel_id}
Commands:
/start - Show this message
-/execute - Manually start processing queue
-/clear - Clear message queue
+/clear - Clear session and disconnect Claude
/status - Show current status
-/queue - Show messages in queue
+/queue - Show session information
/cwd - Show current working directory
/set_cwd <path> - Set working directory
/settings - Personalization settings
How it works:
-• Send any message to add it to the queue
-• Messages are automatically processed in order
-• Claude Code executes each message sequentially"""
+• Send any message and it's immediately sent to Claude Code
+• Each chat maintains its own conversation context
+• Use /clear to reset the conversation"""
await self.im_client.send_message(context, message_text)
return
@@ -110,22 +107,17 @@ How it works:
# Create interactive buttons for commands
buttons = [
- # Row 1: Queue operations
+ # Row 1: Directory management
[
- InlineButton(text="📊 Queue Status", callback_data="cmd_queue_status"),
- InlineButton(text="🚀 Execute Queue", callback_data="cmd_execute")
+ InlineButton(text="📁 Current Dir", callback_data="cmd_cwd"),
+ InlineButton(text="📂 Change Work Dir", callback_data="cmd_change_cwd")
],
- # Row 2: Queue management & Directory
+ # Row 2: Session and Settings
[
- InlineButton(text="🗑️ Clear Queue", callback_data="cmd_clear"),
- InlineButton(text="📁 Current Dir", callback_data="cmd_cwd")
- ],
- # Row 3: Configuration
- [
- InlineButton(text="📂 Change Work Dir", callback_data="cmd_change_cwd"),
+ InlineButton(text="🔄 Reset Session", callback_data="cmd_clear"),
InlineButton(text="⚙️ Settings", callback_data="cmd_settings")
],
- # Row 4: Help
+ # Row 3: Help
[
InlineButton(text="ℹ️ How it Works", callback_data="info_how_it_works")
]
@@ -140,7 +132,7 @@ How it works:
📍 Channel: **{channel_info.get('name', 'Unknown')}**
**Quick Actions:**
-Use the buttons below to manage your Claude Code sessions, or simply type any message to add it to the processing queue."""
+Use the buttons below to manage your Claude Code sessions, or simply type any message to start chatting with Claude!"""
target_context = self._get_target_context(context)
# For Telegram, send with Markdown parse mode (not MarkdownV2)
@@ -186,121 +178,196 @@ Use the buttons below to manage your Claude Code sessions, or simply type any me
parse_mode=parse_mode
)
- # Store thread context with the message (use user's message timestamp for Slack)
+ # Determine session ID based on platform
thread_id = user_message_ts if self.config.platform == "slack" and user_message_ts else None
- await self.session_manager.add_message_with_context(
- context.user_id,
- context.channel_id,
- message,
- thread_id=thread_id
- )
- logger.info(f"User {context.user_id} added message to queue with thread_id: {thread_id}")
+ if self.config.platform == "telegram":
+ # For Telegram, use chat_id as session ID
+ session_id = f"telegram_{context.channel_id}"
+ elif self.config.platform == "slack" and thread_id:
+ # For Slack, use thread_id as session ID
+ session_id = f"slack_{thread_id}"
+ else:
+ # Fallback to user-based session
+ session_id = f"{self.config.platform}_{context.user_id}"
- # Check if not already executing, then start processing
- if not await self.session_manager.is_executing(context.user_id):
- asyncio.create_task(self.process_user_queue(context))
+ # Get or create session
+ session = await self.session_manager.get_or_create_session(context.user_id, context.channel_id)
+
+ # Check if we have a client for this session
+ if session_id not in session.claude_clients:
+ # Check if we have a saved Claude session_id to resume
+ claude_session_id = self.settings_manager.get_claude_session_id(context.user_id, session_id)
+
+ # Create new Claude SDK client with resume if available
+ options = ClaudeCodeOptions(
+ permission_mode=self.config.claude.permission_mode,
+ cwd=self.config.claude.cwd,
+ system_prompt=self.config.claude.system_prompt,
+ # Use resume instead of continue_conversation
+ resume=claude_session_id if claude_session_id else None
+ )
+
+ client = ClaudeSDKClient(options=options)
+ await client.connect()
+ session.claude_clients[session_id] = client
+
+ if claude_session_id:
+ logger.info(f"Resumed Claude session {claude_session_id} for {session_id}")
+ else:
+ logger.info(f"Created new Claude SDK client for session {session_id}")
+
+ # Start persistent receiver for this session
+ receiver_task = asyncio.create_task(
+ self._session_message_receiver(session_id, client, context, thread_id)
+ )
+ session.receiver_tasks[session_id] = receiver_task
+
+ # Send message immediately to the session's client
+ await self.process_message_immediately(context, message, session_id, thread_id)
except Exception as e:
logger.error(f"Error handling message: {e}")
- await self.im_client.send_message(context, "Error adding message to queue.")
+ await self.im_client.send_message(context, "Error processing message.")
- async def process_user_queue(self, context: MessageContext):
- """Process all messages in user's queue sequentially"""
+ async def _session_message_receiver(self, session_id: str, client: ClaudeSDKClient, context: MessageContext, thread_id: Optional[str]):
+ """Persistent message receiver for a session"""
try:
- # Mark as executing
- await self.session_manager.set_executing(context.user_id, True)
-
- # Determine target context (use configured target channel/chat if available)
+ logger.info(f"Starting message receiver for session {session_id}")
target_context = self._get_target_context(context)
-
- while await self.session_manager.has_messages(context.user_id):
- # Get next message with context
- message_data = await self.session_manager.get_next_message_with_context(context.user_id)
- if not message_data:
- break
+ if thread_id:
+ target_context.thread_id = thread_id
+
+ async for message in client.receive_messages():
+ # First 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']
+ # Store the mapping
+ self.settings_manager.set_session_mapping(
+ context.user_id,
+ session_id, # Our internal session ID (e.g., telegram_12345)
+ claude_session_id # Claude's actual session ID
+ )
+ logger.info(f"Captured Claude session_id: {claude_session_id} for {session_id}")
- message = message_data['message']
- thread_id = message_data.get('thread_id')
+ if self.claude_client._is_skip_message(message):
+ continue
- # Get user's CWD from settings if available
- settings_key = self._get_settings_key(context)
- custom_cwd = self.settings_manager.get_custom_cwd(settings_key)
- original_cwd = self.claude_client.options.cwd
+ # Determine message type
+ 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"
- # Use custom CWD if set, otherwise fall back to config default
- if custom_cwd:
- self.claude_client.options.cwd = custom_cwd
- else:
- # Reset to config default in case it was changed before
- self.claude_client.options.cwd = self.config.claude.cwd
+ # Check if this message type should be hidden
+ settings_key = self._get_settings_key(context)
+ 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
- # Execute with Claude
- async def on_claude_message(claude_msg: str, message_type: str = None):
- # Check if this message type should be hidden
- settings_key = self._get_settings_key(context)
- 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)")
- return
-
- # Send Claude's formatted output
- # Use stored thread context if available
- if thread_id:
- target_context.thread_id = thread_id
-
- # Don't escape Claude messages - they already contain proper markdown
- # Use appropriate parse_mode for each platform
+ # Format and send message
+ formatted_message = self.claude_client.format_message(message)
+ if formatted_message and formatted_message.strip():
parse_mode = 'markdown' if self.config.platform == "slack" else 'Markdown'
await self.im_client.send_message(
- target_context,
- claude_msg,
+ target_context,
+ formatted_message,
parse_mode=parse_mode,
reply_to=thread_id if self.config.platform == "slack" else None
)
- try:
- await self.claude_client.stream_execute(message, on_claude_message, context.user_id)
-
- # Always restore original CWD
- self.claude_client.options.cwd = original_cwd
-
- # Check if there are more messages
- remaining = await self.session_manager.has_messages(context.user_id)
- if remaining:
- await self.im_client.send_message(
- target_context,
- "✅ Completed. Processing next message...",
- reply_to=thread_id if self.config.platform == "slack" else None
- )
- else:
- await self.im_client.send_message(
- target_context,
- "✅ All messages processed!",
- reply_to=thread_id if self.config.platform == "slack" else None
- )
-
- except Exception as e:
- logger.error(f"Error during Claude execution: {e}")
- # Always restore original CWD
- self.claude_client.options.cwd = original_cwd
+ # Check if this was a ResultMessage (query complete)
+ if message_type == "result":
await self.im_client.send_message(
target_context,
- f"❌ Error processing message: {str(e)}\nStopping queue processing.",
+ "✅ Ready for next message!",
reply_to=thread_id if self.config.platform == "slack" else None
)
- break
-
- # Small delay between messages
- await asyncio.sleep(1)
+
+ except asyncio.CancelledError:
+ logger.info(f"Message receiver for session {session_id} was cancelled")
+ raise
+ except Exception as e:
+ logger.error(f"Error in message receiver for session {session_id}: {e}")
+ # Notify user of error
+ try:
+ await self.im_client.send_message(
+ target_context,
+ f"❌ Session error: {str(e)}\nPlease use /clear to reset.",
+ reply_to=thread_id if self.config.platform == "slack" else None
+ )
+ except:
+ pass
+
+ async def process_message_immediately(self, context: MessageContext, message: str, session_id: str, thread_id: Optional[str]):
+ """Send message to Claude immediately"""
+ try:
+ # Get session
+ session = await self.session_manager.get_or_create_session(context.user_id, context.channel_id)
+ # Get user's CWD from settings if available
+ settings_key = self._get_settings_key(context)
+ custom_cwd = self.settings_manager.get_custom_cwd(settings_key)
+
+ # Update Claude options with custom CWD
+ if custom_cwd:
+ self.claude_client.options.cwd = custom_cwd
+ else:
+ self.claude_client.options.cwd = self.config.claude.cwd
+
+ # Get the client for this session
+ client = session.claude_clients[session_id]
+
+ # Send the message to Claude
+ try:
+ await client.query(message, session_id=session_id)
+ logger.info(f"Sent message to Claude for session {session_id}")
+ except Exception as e:
+ logger.error(f"Error sending message to Claude: {e}")
+
+ # Clean up broken session
+ await self._cleanup_session(session, session_id)
+
+ # Notify user
+ target_context = self._get_target_context(context)
+ await self.im_client.send_message(
+ target_context,
+ f"❌ Error: {str(e)}\nPlease try again or use /clear to reset.",
+ reply_to=thread_id if self.config.platform == "slack" else None
+ )
+
except Exception as e:
- logger.error(f"Error in process_user_queue: {e}")
+ logger.error(f"Error in process_message_immediately: {e}")
target_context = self._get_target_context(context)
await self.im_client.send_message(
target_context,
f"❌ Unexpected error: {str(e)}"
)
- finally:
- await self.session_manager.set_executing(context.user_id, False)
+
+ async def _cleanup_session(self, session: UserSession, session_id: str) -> None:
+ """Clean up a broken Claude session"""
+ # Cancel receiver task if exists
+ if session_id in session.receiver_tasks:
+ session.receiver_tasks[session_id].cancel()
+ del session.receiver_tasks[session_id]
+
+ # Disconnect and remove Claude client if exists
+ if session_id in session.claude_clients:
+ try:
+ await session.claude_clients[session_id].disconnect()
+ except Exception as e:
+ logger.error(f"Error disconnecting Claude client: {e}")
+ del session.claude_clients[session_id]
+
+ logger.info(f"Cleaned up session {session_id}")
def _get_target_context(self, context: MessageContext) -> MessageContext:
"""Get target context based on configuration"""
@@ -339,45 +406,32 @@ Use the buttons below to manage your Claude Code sessions, or simply type any me
# Fallback to user_id for backward compatibility
return int(context.user_id) if context.user_id else context.user_id
- async def handle_execute(self, context: MessageContext, args: str = ""):
- """Handle manual execute command"""
- target_context = self._get_target_context(context)
-
- if await self.session_manager.is_executing(context.user_id):
- await self.im_client.send_message(
- target_context,
- "Already processing messages. Please wait..."
- )
- return
-
- if not await self.session_manager.has_messages(context.user_id):
- await self.im_client.send_message(
- target_context,
- "No messages in queue."
- )
- return
-
- # Start processing
- asyncio.create_task(self.process_user_queue(context))
-
- async def handle_status(self, context: MessageContext, args: str = ""):
- """Handle status command"""
- try:
- status = await self.session_manager.get_status(context.user_id)
- await self.im_client.send_message(context, status)
- except Exception as e:
- logger.error(f"Error getting status: {e}")
- await self.im_client.send_message(context, "Error getting status.")
async def handle_clear(self, context: MessageContext, args: str = ""):
- """Handle clear command"""
+ """Handle clear command - now clears session and disconnects Claude client"""
try:
- response = await self.session_manager.clear_queue(context.user_id)
- logger.info(f"User {context.user_id} cleared queue")
+ # Determine session ID to clear mapping
+ if self.config.platform == "telegram":
+ session_id = f"telegram_{context.channel_id}"
+ elif self.config.platform == "slack" and context.thread_id:
+ session_id = f"slack_{context.thread_id}"
+ else:
+ session_id = f"{self.config.platform}_{context.user_id}"
+
+ # Clear session mapping
+ self.settings_manager.clear_session_mapping(context.user_id, 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
+ response += "\n🔄 Claude session has been reset."
+
await self.im_client.send_message(context, response)
except Exception as e:
- logger.error(f"Error clearing queue: {e}")
- await self.im_client.send_message(context, "Error clearing queue.")
+ logger.error(f"Error clearing session: {e}")
+ await self.im_client.send_message(context, "Error clearing session.")
async def handle_cwd(self, context: MessageContext, args: str = ""):
"""Handle cwd command - show current working directory"""
@@ -464,30 +518,7 @@ Use the buttons below to manage your Claude Code sessions, or simply type any me
logger.error(f"Error setting cwd: {e}")
await self.im_client.send_message(context, f"❌ Error setting working directory: {str(e)}")
- async def handle_queue(self, context: MessageContext, args: str = ""):
- """Handle queue command - show queue details"""
- try:
- response = await self.session_manager.get_queue_details(context.user_id)
- logger.info(f"User {context.user_id} requested queue status")
- await self.im_client.send_message(context, response)
- except Exception as e:
- logger.error(f"Error getting queue details: {e}")
- await self.im_client.send_message(context, f"Error getting queue information: {str(e)}")
- async def handle_queue_status(self, context: MessageContext):
- """Handle combined queue status - merges status and queue details"""
- try:
- # Get both status and queue details
- status = await self.session_manager.get_status(context.user_id)
- queue_details = await self.session_manager.get_queue_details(context.user_id)
-
- # Combine the information
- combined_info = f"{status}\n\n{queue_details}"
-
- await self.im_client.send_message(context, combined_info)
- except Exception as e:
- logger.error(f"Error getting queue status: {e}")
- await self.im_client.send_message(context, f"Error getting queue status: {str(e)}")
async def handle_change_cwd_modal(self, context: MessageContext):
"""Handle Change Work Dir button - open modal for Slack"""
@@ -644,10 +675,7 @@ Use the buttons below to manage your Claude Code sessions, or simply type any me
logger.info(f"Executing command via button click: {command}")
# Handle special commands
- if command == "queue_status":
- # Merge queue and status info
- await self.handle_queue_status(context)
- elif command == "change_cwd":
+ if command == "change_cwd":
# Open modal for changing work directory
await self.handle_change_cwd_modal(context)
elif command in self.command_handlers:
@@ -664,14 +692,14 @@ Use the buttons below to manage your Claude Code sessions, or simply type any me
info_text = """📚 *How Claude Code Bot Works:*
🔄 *Message Processing:*
-• Send any message to add it to your personal queue
-• Messages are processed _automatically_ in order
+• Send any message and it's immediately processed by Claude Code
+• Conversations maintain context within the same chat/thread
• Each message is sent to Claude Code for execution
-⚡ *Queue Management:*
-• Only *one message per user* is processed at a time
-• Use 🚀 Execute Queue to manually trigger processing
-• Use 🗑️ Clear Queue to remove all pending messages
+⚡ *Real-time Interaction:*
+• Messages are processed immediately as you send them
+• Claude Code maintains persistent sessions for continuous conversation
+• You can send multiple messages without waiting
📁 *Directory Control:*
• Use 📂 Change Work Dir button to set working directory
@@ -686,12 +714,6 @@ Use the buttons below to manage your Claude Code sessions, or simply type any me
elif callback_data == "info_all_commands":
info_text = """📖 *All Available Commands:*
-*📊 Status & Queue:*
-• `/status` or 📊 - Show current queue status
-• `/queue` or 📋 - Display all messages in queue
-• `/execute` or 🚀 - Manually process queue
-• `/clear` or 🗑️ - Clear all queued messages
-
*📁 Directory Management:*
• `/cwd` or 📁 - Show current working directory
• `/set_cwd <path>` - Change working directory
@@ -701,7 +723,7 @@ Use the buttons below to manage your Claude Code sessions, or simply type any me
• `/start` - Show this welcome screen
*💬 Three Ways to Use:*
-• *Direct commands*: Use slash commands like `/status`
+• *Direct commands*: Use slash commands like `/cwd`
• *Button clicks*: Click buttons in this interface
• *Natural messages*: Just type your request normally
• *Channel mentions*: Type `@BotName your message here`
diff --git a/modules/claude_client.py b/modules/claude_client.py
index fd66a1bec..158314fc0 100644
--- a/modules/claude_client.py
+++ b/modules/claude_client.py
@@ -1,8 +1,7 @@
import logging
import os
-from typing import Callable, Optional
+from typing import Optional
from claude_code_sdk import (
- query,
ClaudeCodeOptions,
SystemMessage,
AssistantMessage,
@@ -20,13 +19,16 @@ logger = logging.getLogger(__name__)
class ClaudeClient:
- def __init__(self, config: ClaudeConfig, formatter: Optional[BaseMarkdownFormatter] = None):
+ def __init__(
+ self, config: ClaudeConfig, formatter: Optional[BaseMarkdownFormatter] = None
+ ):
self.config = config
- self.formatter = formatter or TelegramFormatter() # Default to Telegram for backward compatibility
+ self.formatter = (
+ formatter or TelegramFormatter()
+ ) # Default to Telegram for backward compatibility
self.options = ClaudeCodeOptions(
permission_mode=config.permission_mode,
cwd=config.cwd,
- continue_conversation=config.continue_conversation,
system_prompt=config.system_prompt,
)
@@ -95,9 +97,7 @@ class ClaudeClient:
"""Format ToolUseBlock using formatter"""
# Use formatter's format_tool_use method
return self.formatter.format_tool_use(
- block.name,
- block.input,
- get_relative_path=self._get_relative_path
+ block.name, block.input, get_relative_path=self._get_relative_path
)
def _format_tool_result_block(self, block: ToolResultBlock) -> str:
@@ -122,9 +122,7 @@ class ClaudeClient:
def _format_result_message(self, message: ResultMessage) -> str:
"""Format ResultMessage using formatter"""
return self.formatter.format_result_message(
- message.subtype,
- message.duration_ms,
- message.result
+ message.subtype, message.duration_ms, message.result
)
def _is_skip_message(self, message) -> bool:
@@ -137,34 +135,3 @@ class ClaudeClient:
return True
return False
- async def stream_execute(
- self, prompt: str, on_message: Callable, user_id: int = None
- ):
- """Execute query with streaming output"""
- try:
- async for message in query(prompt=prompt, options=self.options):
- if self._is_skip_message(message):
- continue
-
- # Determine message type for filtering (simplified to main categories)
- 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" # This shows tool responses
- elif class_name == "AssistantMessage":
- message_type = "assistant"
- elif class_name == "ResultMessage":
- message_type = "result"
-
- formatted_message = self.format_message(message)
- if formatted_message and formatted_message.strip():
- await on_message(formatted_message, message_type)
- except Exception as e:
- logger.error(f"Error in streaming execution: {e}")
- await on_message(
- f"❌ Error: {str(e)}", "system"
- ) # Error messages go to system category
- raise
diff --git a/modules/im/slack.py b/modules/im/slack.py
index 76f7fea57..438647013 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -827,11 +827,6 @@ class SlackBot(BaseIMClient):
if target_channel is None:
return True
- # If empty list, only accept DMs
- if isinstance(target_channel, list) and len(target_channel) == 0:
- # In Slack, DMs start with 'D', group DMs with 'G'
- return channel_id.startswith(('D', 'G'))
-
# If list with IDs, check whitelist
if isinstance(target_channel, list):
return channel_id in target_channel
diff --git a/modules/im/telegram.py b/modules/im/telegram.py
index 01de50717..8eb9e71bc 100644
--- a/modules/im/telegram.py
+++ b/modules/im/telegram.py
@@ -1,8 +1,20 @@
import asyncio
import logging
from typing import Callable, Optional, Dict, Any
-from telegram import Update, Bot, InlineKeyboardMarkup as TGInlineKeyboardMarkup, InlineKeyboardButton as TGInlineKeyboardButton
-from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, CallbackQueryHandler
+from telegram import (
+ Update,
+ Bot,
+ InlineKeyboardMarkup as TGInlineKeyboardMarkup,
+ InlineKeyboardButton as TGInlineKeyboardButton,
+)
+from telegram.ext import (
+ Application,
+ CommandHandler,
+ MessageHandler,
+ filters,
+ ContextTypes,
+ CallbackQueryHandler,
+)
from telegram.helpers import escape_markdown
from telegram.error import TelegramError
from config.settings import TelegramConfig
@@ -17,101 +29,114 @@ class TelegramBot(BaseIMClient):
def __init__(self, config: TelegramConfig):
super().__init__(config)
self.application = Application.builder().token(config.bot_token).build()
-
+
# Initialize Telegram formatter
self.formatter = TelegramFormatter()
-
+
# Store callback queries for answering
self._callback_queries: Dict[str, Any] = {}
-
- async def handle_telegram_message(self, update: Update, tg_context: ContextTypes.DEFAULT_TYPE):
+
+ async def handle_telegram_message(
+ self, update: Update, tg_context: ContextTypes.DEFAULT_TYPE
+ ):
"""Handle incoming text messages from Telegram"""
chat_id = update.effective_chat.id
chat_type = update.effective_chat.type
-
+
# Check if message is authorized based on whitelist
if not self._is_authorized_chat(chat_id, chat_type):
logger.info(f"Unauthorized message from chat: {chat_id}")
await self._send_unauthorized_message(chat_id)
return
-
+
# Create MessageContext
context = MessageContext(
user_id=str(update.effective_user.id),
channel_id=str(chat_id),
message_id=str(update.message.message_id),
- platform_specific={'update': update, 'tg_context': tg_context}
+ platform_specific={"update": update, "tg_context": tg_context},
)
-
+
message_text = update.message.text
-
+
# Check if it's a command
- if message_text.startswith('/'):
+ if message_text.startswith("/"):
parts = message_text.split(maxsplit=1)
command = parts[0][1:] # Remove the /
args = parts[1] if len(parts) > 1 else ""
-
+
if command in self.on_command_callbacks:
await self.on_command_callbacks[command](context, args)
elif self.on_message_callback:
await self.on_message_callback(context, message_text)
-
- async def handle_telegram_callback(self, update: Update, tg_context: ContextTypes.DEFAULT_TYPE):
+
+ async def handle_telegram_callback(
+ self, update: Update, tg_context: ContextTypes.DEFAULT_TYPE
+ ):
"""Handle callback queries from inline keyboards"""
query = update.callback_query
chat_id = query.message.chat_id
chat_type = query.message.chat.type
-
+
# Check if callback is authorized based on whitelist
if not self._is_authorized_chat(chat_id, chat_type):
logger.info(f"Unauthorized callback from chat: {chat_id}")
# For callback queries, we can answer with an alert
- await query.answer("❌ This chat is not authorized to use bot commands.", show_alert=True)
+ await query.answer(
+ "❌ This chat is not authorized to use bot commands.", show_alert=True
+ )
return
-
+
# Store the query for later use in answer_callback
self._callback_queries[query.id] = query
-
+
# Create MessageContext
context = MessageContext(
user_id=str(query.from_user.id),
channel_id=str(chat_id),
message_id=str(query.message.message_id),
- platform_specific={'query': query, 'update': update, 'tg_context': tg_context, 'callback_id': query.id}
+ platform_specific={
+ "query": query,
+ "update": update,
+ "tg_context": tg_context,
+ "callback_id": query.id,
+ },
)
-
+
if self.on_callback_query_callback:
await self.on_callback_query_callback(context, query.data)
-
- async def _wrap_command(self, command_name: str, update: Update, tg_context: ContextTypes.DEFAULT_TYPE):
+
+ async def _wrap_command(
+ self, command_name: str, update: Update, tg_context: ContextTypes.DEFAULT_TYPE
+ ):
"""Wrap a command handler to convert Update to MessageContext"""
if command_name not in self.on_command_callbacks:
return
-
+
chat_id = update.effective_chat.id
chat_type = update.effective_chat.type
-
+
# Check if command is authorized based on whitelist
if not self._is_authorized_chat(chat_id, chat_type):
logger.info(f"Unauthorized command from chat: {chat_id}")
await self._send_unauthorized_message(chat_id)
return
-
+
# Extract args
message_text = update.message.text
parts = message_text.split(maxsplit=1)
args = parts[1] if len(parts) > 1 else ""
-
+
# Create MessageContext
context = MessageContext(
user_id=str(update.effective_user.id),
channel_id=str(update.effective_chat.id),
message_id=str(update.message.message_id),
- platform_specific={'update': update, 'tg_context': tg_context}
+ platform_specific={"update": update, "tg_context": tg_context},
)
-
+
await self.on_command_callbacks[command_name](context, args)
-
+
def setup_handlers(self):
"""Setup bot command and message handlers"""
# Register command handlers dynamically
@@ -120,208 +145,215 @@ class TelegramBot(BaseIMClient):
self._wrap_command(cmd, update, context)
)
self.application.add_handler(CommandHandler(command, handler))
-
+
# Register callback query handler
- self.application.add_handler(CallbackQueryHandler(self.handle_telegram_callback))
-
+ self.application.add_handler(
+ CallbackQueryHandler(self.handle_telegram_callback)
+ )
+
# Register message handler
self.application.add_handler(
- MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_telegram_message)
+ MessageHandler(
+ filters.TEXT & ~filters.COMMAND, self.handle_telegram_message
+ )
)
-
- async def send_settings_message(self, chat_id: int, text: str, reply_markup: TGInlineKeyboardMarkup):
+
+ async def send_settings_message(
+ self, chat_id: int, text: str, reply_markup: TGInlineKeyboardMarkup
+ ):
"""Send message with inline keyboard"""
bot = self.application.bot
await bot.send_message(
chat_id=chat_id,
text=text,
- parse_mode='MarkdownV2',
- reply_markup=reply_markup
+ parse_mode="MarkdownV2",
+ reply_markup=reply_markup,
)
-
- async def send_message_smart(self, chat_id: int, text: str, message_type: str = None):
+
+ 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 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':
+ if message_type == "result":
# Try original Markdown first
try:
await bot.send_message(
- chat_id=chat_id,
- text=text,
- parse_mode='Markdown'
+ 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'
+ 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'
- )
+ 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
- )
-
+ 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('&', '&amp;')
- text = text.replace('<', '&lt;')
- text = text.replace('>', '&gt;')
-
+ text = text.replace("&", "&amp;")
+ text = text.replace("<", "&lt;")
+ text = text.replace(">", "&gt;")
+
# 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)
-
+ 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)
-
+ 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)
-
+ text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r'<a href="\2">\1</a>', text)
+
return text
-
+
def run(self):
"""Run the bot with infinite retry mechanism"""
import time
-
+
self.setup_handlers()
-
+
retry_delay = 5 # seconds
attempt = 1
-
+
while True:
try:
logger.info(f"Starting Telegram bot (attempt {attempt})...")
self.application.run_polling()
break # If successful, break out of retry loop
-
+
except KeyboardInterrupt:
logger.info("Received keyboard interrupt, shutting down...")
break
-
+
except Exception as e:
logger.error(f"Telegram bot failed (attempt {attempt}): {e}")
logger.info(f"Retrying in {retry_delay} seconds...")
-
+
try:
time.sleep(retry_delay)
except KeyboardInterrupt:
- logger.info("Received keyboard interrupt during retry wait, shutting down...")
+ logger.info(
+ "Received keyboard interrupt during retry wait, shutting down..."
+ )
break
-
+
retry_delay = min(retry_delay * 1.5, 60) # Exponential backoff, max 60s
attempt += 1
-
+
# Implementation of BaseIMClient abstract methods
-
- async def send_message(self, context: MessageContext, text: str,
- parse_mode: Optional[str] = None,
- reply_to: Optional[str] = None) -> str:
+
+ async def send_message(
+ self,
+ context: MessageContext,
+ text: str,
+ parse_mode: Optional[str] = None,
+ reply_to: Optional[str] = None,
+ ) -> str:
"""Send a text message - BaseIMClient implementation"""
bot = self.application.bot
-
+
# Convert MessageContext to Telegram chat_id
chat_id = int(context.channel_id)
-
+
# Handle thread_id as reply_to_message_id in Telegram
- kwargs = {
- 'chat_id': chat_id,
- 'text': text
- }
-
+ kwargs = {"chat_id": chat_id, "text": text}
+
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'
+ if parse_mode == "markdown":
+ kwargs["parse_mode"] = "Markdown"
else:
- kwargs['parse_mode'] = parse_mode
-
+ kwargs["parse_mode"] = parse_mode
+
if reply_to or context.thread_id:
- kwargs['reply_to_message_id'] = int(reply_to or context.thread_id)
-
+ kwargs["reply_to_message_id"] = int(reply_to or context.thread_id)
+
try:
message = await bot.send_message(**kwargs)
return str(message.message_id)
except TelegramError as e:
logger.error(f"Error sending message: {e}")
raise
-
- async def send_message_with_buttons(self, context: MessageContext, text: str,
- keyboard: InlineKeyboard,
- parse_mode: Optional[str] = None) -> str:
+
+ async def send_message_with_buttons(
+ self,
+ context: MessageContext,
+ text: str,
+ keyboard: InlineKeyboard,
+ parse_mode: Optional[str] = None,
+ ) -> str:
"""Send a message with inline buttons - BaseIMClient implementation"""
bot = self.application.bot
-
+
# Convert our generic keyboard to Telegram keyboard
tg_keyboard = []
for row in keyboard.buttons:
tg_row = []
for button in row:
tg_button = TGInlineKeyboardButton(
- text=button.text,
- callback_data=button.callback_data
+ text=button.text, callback_data=button.callback_data
)
tg_row.append(tg_button)
tg_keyboard.append(tg_row)
-
+
reply_markup = TGInlineKeyboardMarkup(tg_keyboard)
-
+
chat_id = int(context.channel_id)
-
+
try:
message = await bot.send_message(
chat_id=chat_id,
text=text,
- parse_mode='Markdown' if parse_mode == 'markdown' else parse_mode,
- reply_markup=reply_markup
+ parse_mode="Markdown" if parse_mode == "markdown" else parse_mode,
+ reply_markup=reply_markup,
)
return str(message.message_id)
except TelegramError as e:
logger.error(f"Error sending message with buttons: {e}")
raise
-
- async def edit_message(self, context: MessageContext, message_id: str,
- text: Optional[str] = None,
- keyboard: Optional[InlineKeyboard] = None) -> bool:
+
+ async def edit_message(
+ self,
+ context: MessageContext,
+ message_id: str,
+ text: Optional[str] = None,
+ keyboard: Optional[InlineKeyboard] = None,
+ ) -> bool:
"""Edit an existing message - BaseIMClient implementation"""
bot = self.application.bot
chat_id = int(context.channel_id)
-
+
try:
if text and keyboard:
# Convert keyboard
@@ -330,25 +362,22 @@ class TelegramBot(BaseIMClient):
tg_row = []
for button in row:
tg_button = TGInlineKeyboardButton(
- text=button.text,
- callback_data=button.callback_data
+ text=button.text, callback_data=button.callback_data
)
tg_row.append(tg_button)
tg_keyboard.append(tg_row)
-
+
reply_markup = TGInlineKeyboardMarkup(tg_keyboard)
-
+
await bot.edit_message_text(
chat_id=chat_id,
message_id=int(message_id),
text=text,
- reply_markup=reply_markup
+ reply_markup=reply_markup,
)
elif text:
await bot.edit_message_text(
- chat_id=chat_id,
- message_id=int(message_id),
- text=text
+ chat_id=chat_id, message_id=int(message_id), text=text
)
elif keyboard:
# Convert keyboard
@@ -357,27 +386,27 @@ class TelegramBot(BaseIMClient):
tg_row = []
for button in row:
tg_button = TGInlineKeyboardButton(
- text=button.text,
- callback_data=button.callback_data
+ text=button.text, callback_data=button.callback_data
)
tg_row.append(tg_button)
tg_keyboard.append(tg_row)
-
+
reply_markup = TGInlineKeyboardMarkup(tg_keyboard)
-
+
await bot.edit_message_reply_markup(
chat_id=chat_id,
message_id=int(message_id),
- reply_markup=reply_markup
+ reply_markup=reply_markup,
)
-
+
return True
except TelegramError as e:
logger.error(f"Error editing message: {e}")
return False
-
- async def answer_callback(self, callback_id: str, text: Optional[str] = None,
- show_alert: bool = False) -> bool:
+
+ async def answer_callback(
+ self, callback_id: str, text: Optional[str] = None, show_alert: bool = False
+ ) -> bool:
"""Answer a callback query - BaseIMClient implementation"""
# Get the stored callback query
if callback_id in self._callback_queries:
@@ -391,80 +420,76 @@ class TelegramBot(BaseIMClient):
logger.error(f"Error answering callback: {e}")
return False
return False
-
+
def register_handlers(self):
"""Register platform-specific handlers - BaseIMClient implementation"""
# This is already implemented as setup_handlers()
self.setup_handlers()
-
+
async def get_user_info(self, user_id: str) -> Dict[str, Any]:
"""Get information about a user - BaseIMClient implementation"""
bot = self.application.bot
-
+
try:
user = await bot.get_chat(int(user_id))
return {
- 'id': str(user.id),
- 'username': user.username,
- 'first_name': user.first_name,
- 'last_name': user.last_name,
- 'type': user.type
+ "id": str(user.id),
+ "username": user.username,
+ "first_name": user.first_name,
+ "last_name": user.last_name,
+ "type": user.type,
}
except TelegramError as e:
logger.error(f"Error getting user info: {e}")
raise
-
+
async def get_channel_info(self, channel_id: str) -> Dict[str, Any]:
"""Get information about a channel/chat - BaseIMClient implementation"""
bot = self.application.bot
-
+
try:
chat = await bot.get_chat(int(channel_id))
return {
- 'id': str(chat.id),
- 'title': chat.title,
- 'type': chat.type,
- 'username': chat.username
+ "id": str(chat.id),
+ "title": chat.title,
+ "type": chat.type,
+ "username": chat.username,
}
except TelegramError as e:
logger.error(f"Error getting channel info: {e}")
raise
-
+
def format_markdown(self, text: str) -> str:
"""Format markdown text for Telegram using TelegramFormatter
-
+
This properly escapes special characters for MarkdownV2
"""
# Use the formatter to properly escape text
return self.formatter.escape_special_chars(text)
-
+
def _is_authorized_chat(self, chat_id: int, chat_type: str) -> bool:
"""Check if a chat is authorized based on whitelist configuration"""
target_chat_id = self.config.target_chat_id
-
+
# If None/null, accept all chats
if target_chat_id is None:
return True
-
- # If empty list, only accept private chats (DMs)
- if isinstance(target_chat_id, list) and len(target_chat_id) == 0:
- return chat_type == 'private'
-
+
# If list with IDs, check whitelist
if isinstance(target_chat_id, list):
return chat_id in target_chat_id
-
+
# Should not reach here, but handle gracefully
logger.warning(f"Unexpected target_chat_id type: {type(target_chat_id)}")
- return True
-
+ return False
+
async def _send_unauthorized_message(self, chat_id: int):
"""Send unauthorized access message to chat"""
try:
bot = self.application.bot
await bot.send_message(
chat_id=chat_id,
- text="❌ This chat is not authorized to use bot commands."
+ text="❌ This chat is not authorized to use bot commands.",
)
except Exception as e:
- logger.error(f"Failed to send unauthorized message to {chat_id}: {e}")
\ No newline at end of file
+ logger.error(f"Failed to send unauthorized message to {chat_id}: {e}")
diff --git a/modules/session_manager.py b/modules/session_manager.py
index 8081d15ad..c44fbae1f 100644
--- a/modules/session_manager.py
+++ b/modules/session_manager.py
@@ -3,66 +3,63 @@ import logging
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Union, Any
from datetime import datetime
+from claude_code_sdk import ClaudeSDKClient
logger = logging.getLogger(__name__)
-@dataclass
-class MessageData:
- message: str
- thread_id: Optional[str] = None
@dataclass
class UserSession:
user_id: Union[int, str]
chat_id: Union[int, str]
- message_queue: List[MessageData] = field(default_factory=list)
is_executing: bool = False
created_at: datetime = field(default_factory=datetime.now)
last_activity: datetime = field(default_factory=datetime.now)
-
- def add_message(self, message: str, thread_id: Optional[str] = None):
- """Add message to queue"""
- self.message_queue.append(MessageData(message=message, thread_id=thread_id))
- self.last_activity = datetime.now()
-
-
- def get_next_message(self) -> Optional[Dict[str, Any]]:
- """Get and remove the next message from queue"""
- if self.message_queue:
- message_data = self.message_queue.pop(0)
- self.last_activity = datetime.now()
- return {
- 'message': message_data.message,
- 'thread_id': message_data.thread_id
- }
- return None
-
- def clear_queue(self):
- """Clear message queue"""
- self.message_queue.clear()
- self.last_activity = datetime.now()
+ # Map of session_id to ClaudeSDKClient instance
+ claude_clients: Dict[str, ClaudeSDKClient] = field(default_factory=dict)
+ # Map of session_id to message receiver task
+ receiver_tasks: Dict[str, asyncio.Task] = field(default_factory=dict)
+
+
+ async def cleanup_clients(self):
+ """Cleanup all Claude SDK clients and receiver tasks"""
+ # Cancel all receiver tasks first
+ for session_id, task in self.receiver_tasks.items():
+ if not task.done():
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ logger.info(f"Cancelled receiver task for session {session_id}")
+
+ # Then disconnect clients
+ for session_id, client in self.claude_clients.items():
+ try:
+ await client.disconnect()
+ logger.info(f"Disconnected Claude client for session {session_id}")
+ except Exception as e:
+ logger.error(f"Error disconnecting Claude client for session {session_id}: {e}")
+
+ self.receiver_tasks.clear()
def get_status(self) -> str:
"""Get session status summary"""
status = f"📊 Session Status\n"
status += f"━━━━━━━━━━━━━━━━\n"
status += f"User ID: {self.user_id}\n"
- status += f"Messages in queue: {len(self.message_queue)}\n"
- status += f"Status: {'🟢 Processing' if self.is_executing else '⭕ Idle'}\n"
+ status += f"Active sessions: {len(self.claude_clients)}\n"
+ status += f"Status: {'🟢 Connected' if self.claude_clients else '⭕ No active session'}\n"
status += f"Last activity: {self.last_activity.strftime('%Y-%m-%d %H:%M:%S')}"
- if self.message_queue:
- status += "\n\n📋 Queued messages:"
- for idx, msg_data in enumerate(self.message_queue, 1):
- msg = msg_data.message
- preview = msg[:50] + "..." if len(msg) > 50 else msg
- status += f"\n{idx}. {preview}"
- elif self.is_executing:
- status += "\n\n⏳ Currently processing your message..."
+ if self.claude_clients:
+ status += "\n\n🔗 Active Claude sessions:"
+ for session_id in self.claude_clients:
+ status += f"\n• {session_id}"
else:
- status += "\n\n💤 No messages in queue"
+ status += "\n\n💬 Send a message to start a conversation"
return status
@@ -81,76 +78,21 @@ class SessionManager:
return self.sessions[user_id]
- async def add_message(self, user_id: Union[int, str], chat_id: Union[int, str], message: str) -> str:
- """Add message to user's queue"""
- session = await self.get_or_create_session(user_id, chat_id)
- session.add_message(message)
-
- return f"Message added to queue. Total messages: {len(session.message_queue)}"
-
- async def add_message_with_context(self, user_id: Union[int, str], chat_id: Union[int, str],
- message: str, thread_id: Optional[str] = None) -> str:
- """Add message with thread context to user's queue"""
- session = await self.get_or_create_session(user_id, chat_id)
- session.add_message(message, thread_id=thread_id)
-
- return f"Message added to queue. Total messages: {len(session.message_queue)}"
-
- async def get_next_message(self, user_id: Union[int, str]) -> Optional[str]:
- """Get next message from user's queue (legacy method)"""
- message_data = await self.get_next_message_with_context(user_id)
- return message_data['message'] if message_data else None
-
- async def get_next_message_with_context(self, user_id: Union[int, str]) -> Optional[Dict[str, Any]]:
- """Get next message with thread context from user's queue"""
- if user_id not in self.sessions:
- return None
-
- session = self.sessions[user_id]
- return session.get_next_message()
-
- async def has_messages(self, user_id: Union[int, str]) -> bool:
- """Check if user has messages in queue"""
- if user_id not in self.sessions:
- return False
- return len(self.sessions[user_id].message_queue) > 0
-
- async def get_queue_details(self, user_id: Union[int, str]) -> str:
- """Get detailed queue information for user"""
- if user_id not in self.sessions:
- return "No active session. Send a message to start."
-
- session = self.sessions[user_id]
-
- if not session.message_queue:
- if session.is_executing:
- return "📋 Queue is empty\n⏳ Currently executing a message..."
- else:
- return "📋 Queue is empty\n💤 No messages to process"
-
- queue_info = f"📋 Message Queue ({len(session.message_queue)} messages)\n"
- queue_info += f"Status: {'🟢 Processing' if session.is_executing else '⭕ Waiting'}\n\n"
-
- for idx, msg_data in enumerate(session.message_queue, 1):
- # Show first 100 characters of each message
- msg = msg_data.message
- preview = msg[:100] + "..." if len(msg) > 100 else msg
- # Replace newlines with spaces for better display
- preview = preview.replace('\n', ' ').replace('\r', ' ')
- queue_info += f"{idx}. {preview}\n"
-
- return queue_info
- async def clear_queue(self, user_id: Union[int, str]) -> str:
- """Clear user's message queue"""
+ async def clear_session(self, user_id: Union[int, str]) -> str:
+ """Clear user's session and disconnect all Claude clients"""
if user_id not in self.sessions:
return "No active session found."
session = self.sessions[user_id]
- message_count = len(session.message_queue)
- session.clear_queue()
- return f"Cleared {message_count} messages from queue."
+ # Cleanup all Claude SDK clients and receiver tasks
+ client_count = len(session.claude_clients)
+ await session.cleanup_clients()
+ session.claude_clients.clear()
+ session.receiver_tasks.clear()
+
+ return f"Cleared {client_count} active Claude session(s)."
async def get_status(self, user_id: Union[int, str]) -> str:
"""Get user's session status"""
@@ -185,6 +127,9 @@ class SessionManager:
to_remove.append(user_id)
for user_id in to_remove:
+ session = self.sessions[user_id]
+ # Cleanup Claude SDK clients before removing session
+ await session.cleanup_clients()
del self.sessions[user_id]
logger.info(f"Cleaned up inactive session for user {user_id}")
diff --git a/modules/settings_manager.py b/modules/settings_manager.py
index bd6b99ee0..77e57f20e 100644
--- a/modules/settings_manager.py
+++ b/modules/settings_manager.py
@@ -14,6 +14,8 @@ class UserSettings:
"""User personalization settings"""
hidden_message_types: List[str] = field(default_factory=list) # Message types to hide
custom_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)
def to_dict(self) -> dict:
"""Convert to dictionary for JSON serialization"""
@@ -128,4 +130,24 @@ class SettingsManager:
"user": "Response", # Renamed from 'user' for clarity
"assistant": "Assistant",
"result": "Result"
- }
\ No newline at end of file
+ }
+
+ 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"""
+ settings = self.get_user_settings(user_id)
+ settings.session_mappings[im_session_id] = claude_session_id
+ self.update_user_settings(user_id, settings)
+ logger.info(f"Stored session mapping for user {user_id}: {im_session_id} -> {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"""
+ settings = self.get_user_settings(user_id)
+ return settings.session_mappings.get(im_session_id)
+
+ def clear_session_mapping(self, user_id: Union[int, str], im_session_id: str):
+ """Clear session mapping for given IM session ID"""
+ 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