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 platform-specific markdown formatter architecture

cyhhao6af374600cd9
diff --git a/core/controller.py b/core/controller.py
index b18ef96f9..27b2572fe 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -4,6 +4,7 @@ import os
from typing import Optional, Union
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.settings_manager import SettingsManager
@@ -16,7 +17,19 @@ class Controller:
def __init__(self, config: AppConfig):
self.config = config
self.im_client: BaseIMClient = IMFactory.create_client(config)
- self.claude_client = ClaudeClient(config.claude)
+
+ # Create platform-specific formatter
+ if config.platform == "telegram":
+ formatter = TelegramFormatter()
+ elif config.platform == "slack":
+ formatter = SlackFormatter()
+ else:
+ # Default to Telegram formatter for unknown platforms
+ logger.warning(f"Unknown platform: {config.platform}, using Telegram formatter")
+ formatter = TelegramFormatter()
+
+ # Inject formatter into ClaudeClient
+ self.claude_client = ClaudeClient(config.claude, formatter)
self.session_manager = SessionManager()
self.settings_manager = SettingsManager()
diff --git a/modules/claude_client.py b/modules/claude_client.py
index 46f78707b..cc273875e 100644
--- a/modules/claude_client.py
+++ b/modules/claude_client.py
@@ -1,5 +1,5 @@
import logging
-from typing import Callable
+from typing import Callable, Optional
from claude_code_sdk import (
query,
ClaudeCodeOptions,
@@ -11,16 +11,17 @@ from claude_code_sdk import (
ToolUseBlock,
ToolResultBlock,
)
-from telegram.helpers import escape_markdown
from config import ClaudeConfig
+from modules.im.formatters import BaseMarkdownFormatter, TelegramFormatter
logger = logging.getLogger(__name__)
class ClaudeClient:
- def __init__(self, config: ClaudeConfig):
+ def __init__(self, config: ClaudeConfig, formatter: Optional[BaseMarkdownFormatter] = None):
self.config = config
+ self.formatter = formatter or TelegramFormatter() # Default to Telegram for backward compatibility
self.options = ClaudeCodeOptions(
permission_mode=config.permission_mode,
cwd=config.cwd,
@@ -40,12 +41,12 @@ class ClaudeClient:
elif isinstance(message, ResultMessage):
return self._format_result_message(message)
else:
- return escape_markdown(
- f"🤔 Unknown message type: {type(message)}", version=2
+ return self.formatter.format_warning(
+ f"Unknown message type: {type(message)}"
)
except Exception as e:
logger.error(f"Error formatting message: {e}")
- return escape_markdown(f"❌ Error formatting message: {str(e)}", version=2)
+ return self.formatter.format_error(f"Error formatting message: {str(e)}")
def _process_content_blocks(self, content_blocks) -> list:
"""Process content blocks (TextBlock, ToolUseBlock) and return formatted parts"""
@@ -53,8 +54,8 @@ class ClaudeClient:
for block in content_blocks:
if isinstance(block, TextBlock):
- # Escape text content for MarkdownV2
- escaped_text = escape_markdown(block.text, version=2)
+ # Escape text content using formatter
+ escaped_text = self.formatter.escape_special_chars(block.text)
formatted_parts.append(escaped_text)
elif isinstance(block, ToolUseBlock):
tool_info = self._format_tool_use_block(block)
@@ -93,7 +94,7 @@ class ClaudeClient:
def _format_tool_use_block(self, block: ToolUseBlock) -> str:
"""Format ToolUseBlock with specific adaptations for different tools"""
- escaped_name = escape_markdown(block.name, version=2)
+ escaped_name = self.formatter.escape_special_chars(block.name)
# Get tool emoji and format based on tool type
if block.name.startswith("mcp__"):
@@ -107,7 +108,7 @@ class ClaudeClient:
"human": "👤",
}
emoji = emoji_map.get(tool_category, "🔧")
- tool_info = f"{emoji} *MCP Tool*: `{escaped_name}`"
+ tool_info = f"{emoji} {self.formatter.format_bold('MCP Tool')}: {self.formatter.format_code_inline(block.name)}"
else:
# System tools - specific handling
tool_emoji_map = {
@@ -128,7 +129,7 @@ class ClaudeClient:
"ExitPlanMode": "🚪",
}
emoji = tool_emoji_map.get(block.name, "🔧")
- tool_info = f"{emoji} *Tool*: `{escaped_name}`"
+ tool_info = f"{emoji} {self.formatter.format_bold('Tool')}: {self.formatter.format_code_inline(block.name)}"
# Add specific input info based on tool type
input_info = []
@@ -136,75 +137,53 @@ class ClaudeClient:
# File operations
if "file_path" in block.input and block.input["file_path"]:
relative_path = self._get_relative_path(block.input["file_path"])
- escaped_path = escape_markdown(relative_path, version=2)
- input_info.append(f"📁 File: `{escaped_path}`")
+ input_info.append(self.formatter.format_file_path(relative_path))
# Path operations (for LS, Glob, etc.)
if "path" in block.input and block.input["path"]:
relative_path = self._get_relative_path(block.input["path"])
- escaped_path = escape_markdown(relative_path, version=2)
- input_info.append(f"📂 Path: `{escaped_path}`")
+ input_info.append(self.formatter.format_file_path(relative_path, emoji="📂"))
# Command operations
if "command" in block.input and block.input["command"]:
cmd = block.input["command"]
- # For multi-line commands, use code block
- if "\n" in cmd or len(cmd) > 80:
- input_info.append(f"💻 Command:\n```bash\n{cmd}\n```")
- else:
- escaped_cmd = escape_markdown(cmd, version=2)
- input_info.append(f"💻 Command: `{escaped_cmd}`")
+ input_info.append(self.formatter.format_command(cmd))
# Description (for Bash tool)
if "description" in block.input and block.input["description"]:
desc = block.input["description"]
- input_info.append(f"📝 Description: `{escape_markdown(desc, version=2)}`")
+ input_info.append(f"📝 Description: {self.formatter.format_code_inline(desc)}")
# Pattern/Query operations
if "pattern" in block.input and block.input["pattern"]:
- escaped_pattern = escape_markdown(block.input["pattern"], version=2)
- input_info.append(f"🔍 Pattern: `{escaped_pattern}`")
+ input_info.append(f"🔍 Pattern: {self.formatter.format_code_inline(block.input['pattern'])}")
if "query" in block.input and block.input["query"]:
query_str = str(block.input["query"])
- if len(query_str) > 50:
- escaped_query = escape_markdown(query_str[:50], version=2) + "\\.\\.\\."
- else:
- escaped_query = escape_markdown(query_str, version=2)
- input_info.append(f"🔍 Query: `{escaped_query}`")
+ truncated_query = self.formatter.truncate_text(query_str, 50)
+ input_info.append(f"🔍 Query: {self.formatter.format_code_inline(truncated_query)}")
# WebFetch specific parameters
if "url" in block.input and block.input["url"]:
url_str = str(block.input["url"])
- escaped_url = escape_markdown(url_str, version=2)
- input_info.append(f"🌐 URL: `{escaped_url}`")
+ input_info.append(f"🌐 URL: {self.formatter.format_code_inline(url_str)}")
if "prompt" in block.input and block.input["prompt"]:
prompt_str = str(block.input["prompt"])
- if len(prompt_str) > 100:
- escaped_prompt = (
- escape_markdown(prompt_str[:100], version=2) + "\\.\\.\\."
- )
- else:
- escaped_prompt = escape_markdown(prompt_str, version=2)
+ truncated_prompt = self.formatter.truncate_text(prompt_str, 100)
+ escaped_prompt = self.formatter.escape_special_chars(truncated_prompt)
input_info.append(f"📝 Prompt: {escaped_prompt}")
# Edit/MultiEdit specific parameters
if "old_string" in block.input and block.input["old_string"]:
old_str = str(block.input["old_string"])
- if len(old_str) > 50:
- escaped_old = escape_markdown(old_str[:50], version=2) + "\\.\\.\\."
- else:
- escaped_old = escape_markdown(old_str, version=2)
- input_info.append(f"🔍 Old: `{escaped_old}`")
+ truncated_old = self.formatter.truncate_text(old_str, 50)
+ input_info.append(f"🔍 Old: {self.formatter.format_code_inline(truncated_old)}")
if "new_string" in block.input and block.input["new_string"]:
new_str = str(block.input["new_string"])
- if len(new_str) > 50:
- escaped_new = escape_markdown(new_str[:50], version=2) + "\\.\\.\\."
- else:
- escaped_new = escape_markdown(new_str, version=2)
- input_info.append(f"✏️ New: `{escaped_new}`")
+ truncated_new = self.formatter.truncate_text(new_str, 50)
+ input_info.append(f"✏️ New: {self.formatter.format_code_inline(truncated_new)}")
# MultiEdit edits array
if "edits" in block.input and block.input["edits"]:
@@ -220,29 +199,23 @@ class ClaudeClient:
# Task tool parameters
if "subagent_type" in block.input and block.input["subagent_type"]:
- escaped_agent = escape_markdown(
- str(block.input["subagent_type"]), version=2
- )
- input_info.append(f"🤖 Agent: `{escaped_agent}`")
+ agent_type = str(block.input["subagent_type"])
+ input_info.append(f"🤖 Agent: {self.formatter.format_code_inline(agent_type)}")
if "plan" in block.input and block.input["plan"]:
plan_str = str(block.input["plan"])
- if len(plan_str) > 100:
- escaped_plan = escape_markdown(plan_str[:100], version=2) + "\\.\\.\\."
- else:
- escaped_plan = escape_markdown(plan_str, version=2)
+ truncated_plan = self.formatter.truncate_text(plan_str, 100)
+ escaped_plan = self.formatter.escape_special_chars(truncated_plan)
input_info.append(f"📋 Plan: {escaped_plan}")
# NotebookEdit parameters
if "cell_id" in block.input and block.input["cell_id"]:
- escaped_cell_id = escape_markdown(str(block.input["cell_id"]), version=2)
- input_info.append(f"📊 Cell ID: `{escaped_cell_id}`")
+ cell_id = str(block.input["cell_id"])
+ input_info.append(f"📊 Cell ID: {self.formatter.format_code_inline(cell_id)}")
if "cell_type" in block.input and block.input["cell_type"]:
- escaped_cell_type = escape_markdown(
- str(block.input["cell_type"]), version=2
- )
- input_info.append(f"📝 Cell Type: `{escaped_cell_type}`")
+ cell_type = str(block.input["cell_type"])
+ input_info.append(f"📝 Cell Type: {self.formatter.format_code_inline(cell_type)}")
# WebSearch parameters
if "allowed_domains" in block.input and block.input["allowed_domains"]:
@@ -255,16 +228,16 @@ class ClaudeClient:
# Grep parameters
if "glob" in block.input and block.input["glob"]:
- escaped_glob = escape_markdown(str(block.input["glob"]), version=2)
- input_info.append(f"🎯 Glob: `{escaped_glob}`")
+ glob_pattern = str(block.input["glob"])
+ input_info.append(f"🎯 Glob: {self.formatter.format_code_inline(glob_pattern)}")
if "type" in block.input and block.input["type"]:
- escaped_type = escape_markdown(str(block.input["type"]), version=2)
- input_info.append(f"📄 Type: `{escaped_type}`")
+ type_str = str(block.input["type"])
+ input_info.append(f"📄 Type: {self.formatter.format_code_inline(type_str)}")
if "output_mode" in block.input and block.input["output_mode"]:
- escaped_mode = escape_markdown(str(block.input["output_mode"]), version=2)
- input_info.append(f"📊 Output mode: `{escaped_mode}`")
+ mode = str(block.input["output_mode"])
+ input_info.append(f"📊 Output mode: {self.formatter.format_code_inline(mode)}")
if input_info:
tool_info += "\n" + "\n".join(input_info)
@@ -311,15 +284,15 @@ class ClaudeClient:
if len(todo.get("content", "")) > 50:
content += "..."
- # Add strikethrough for completed items using MarkdownV2 format
+ # Add strikethrough for completed items
if status == "completed":
- # Use MarkdownV2 strikethrough format: ~text~
- escaped_content = f"~{escape_markdown(content, version=2)}~"
+ # Use formatter's strikethrough method
+ formatted_content = self.formatter.format_strikethrough(content)
tool_info += (
- f"\n• {status_emoji} {priority_emoji} {escaped_content}"
+ f"\n• {status_emoji} {priority_emoji} {formatted_content}"
)
else:
- escaped_content = escape_markdown(content, version=2)
+ escaped_content = self.formatter.escape_special_chars(content)
tool_info += (
f"\n• {status_emoji} {priority_emoji} {escaped_content}"
)
@@ -332,17 +305,17 @@ class ClaudeClient:
content = str(block.input["content"])
if len(content) > 300:
content = content[:300] + "..."
- tool_info += f"\n```\n{content}\n```"
+ tool_info += f"\n{self.formatter.format_code_block(content)}"
elif show_json and block.input and len(str(block.input)) < 200:
# Show short input as JSON for tools that need it
import json
try:
input_json = json.dumps(block.input, indent=2, ensure_ascii=False)
- tool_info += f"\n```json\n{input_json}\n```"
+ tool_info += f"\n{self.formatter.format_code_block(input_json, 'json')}"
except:
# Fallback for non-serializable input
- tool_info += f"\n```\n{str(block.input)}\n```"
+ tool_info += f"\n{self.formatter.format_code_block(str(block.input))}"
return tool_info
@@ -361,9 +334,7 @@ class ClaudeClient:
if len(block.tool_use_id) > 8
else block.tool_use_id
)
- escaped_tool_id = escape_markdown(tool_id, version=2)
-
- result_info = f"{emoji} *Tool Result*"
+ result_info = f"{emoji} {self.formatter.format_bold('Tool Result')}"
# Format content in code block
if block.content:
@@ -371,27 +342,33 @@ class ClaudeClient:
if len(content) > 500:
# Truncate very long content
content = content[:500] + "..."
- result_info += f"\n```\n{content}\n```"
+ result_info += f"\n{self.formatter.format_code_block(content)}"
return result_info
def _format_system_message(self, message: SystemMessage) -> str:
"""Format SystemMessage"""
cwd = message.data.get("cwd", "Unknown")
- escaped_cwd = escape_markdown(cwd, version=2)
- escaped_subtype = escape_markdown(message.subtype, version=2)
- return f"🔧 *System {escaped_subtype}*\n📁 Working directory: `{escaped_cwd}`\n✨ Ready to work\\!"
+ subtype = message.subtype
+
+ header = self.formatter.format_section_header(f"System {subtype}", "🔧")
+ cwd_line = self.formatter.format_file_path(cwd, emoji="📁").replace("File:", "Working directory:")
+ ready_line = f"✨ {self.formatter.escape_special_chars('Ready to work!')}"
+
+ return f"{header}\n{cwd_line}\n{ready_line}"
def _format_assistant_message(self, message: AssistantMessage) -> str:
"""Format AssistantMessage"""
- formatted_parts = ["🤖 *Assistant*"]
+ header = self.formatter.format_section_header("Assistant", "🤖")
+ formatted_parts = [header]
content_parts = self._process_content_blocks(message.content)
formatted_parts.extend(content_parts)
return "\n\n".join(formatted_parts)
def _format_user_message(self, message: UserMessage) -> str:
"""Format UserMessage"""
- formatted_parts = ["👤 *Response*"]
+ header = self.formatter.format_section_header("Response", "👤")
+ formatted_parts = [header]
content_parts = self._process_content_blocks(message.content)
formatted_parts.extend(content_parts)
return "\n\n".join(formatted_parts)
@@ -408,9 +385,11 @@ class ClaudeClient:
else:
duration_str = f"{seconds}s"
- # Don't escape for Result messages - they will be handled by smart formatting
- result_text = f"📊 **Result ({message.subtype})**\n"
- result_text += f"⏱️ Duration: {duration_str}\n"
+ # Format result header
+ header = self.formatter.format_section_header(f"Result ({message.subtype})", "📊")
+ duration_line = self.formatter.format_key_value("⏱️ Duration", duration_str)
+
+ result_text = f"{header}\n{duration_line}\n"
if message.result:
result_text += f"\n{message.result}\n"
diff --git a/modules/im/formatters/__init__.py b/modules/im/formatters/__init__.py
new file mode 100644
index 000000000..646df275c
--- /dev/null
+++ b/modules/im/formatters/__init__.py
@@ -0,0 +1,5 @@
+from .base_formatter import BaseMarkdownFormatter
+from .telegram_formatter import TelegramFormatter
+from .slack_formatter import SlackFormatter
+
+__all__ = ['BaseMarkdownFormatter', 'TelegramFormatter', 'SlackFormatter']
\ No newline at end of file
diff --git a/modules/im/formatters/base_formatter.py b/modules/im/formatters/base_formatter.py
new file mode 100644
index 000000000..e1f7143b2
--- /dev/null
+++ b/modules/im/formatters/base_formatter.py
@@ -0,0 +1,118 @@
+from abc import ABC, abstractmethod
+from typing import Optional, List, Tuple
+
+
+class BaseMarkdownFormatter(ABC):
+ """Abstract base class for platform-specific markdown formatters"""
+
+ # Common formatting methods that work across platforms
+ def 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)
+
+ def format_list_item(self, text: str, level: int = 0) -> str:
+ """Format list item with indentation"""
+ indent = " " * level
+ return f"{indent}• {text}"
+
+ def format_numbered_list_item(self, text: str, number: int, level: int = 0) -> str:
+ """Format numbered list item"""
+ indent = " " * level
+ return f"{indent}{number}. {text}"
+
+ def format_horizontal_rule(self) -> str:
+ """Format horizontal rule"""
+ return "---"
+
+ # Platform-specific abstract methods
+ @abstractmethod
+ def format_bold(self, text: str) -> str:
+ """Format bold text - platform specific"""
+ pass
+
+ @abstractmethod
+ def format_italic(self, text: str) -> str:
+ """Format italic text - platform specific"""
+ pass
+
+ @abstractmethod
+ def format_strikethrough(self, text: str) -> str:
+ """Format strikethrough text - platform specific"""
+ pass
+
+ @abstractmethod
+ def format_link(self, text: str, url: str) -> str:
+ """Format hyperlink - platform specific"""
+ pass
+
+ @abstractmethod
+ def escape_special_chars(self, text: str) -> str:
+ """Escape platform-specific special characters"""
+ pass
+
+ # Convenience methods that combine formatting
+ def 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
+ if "\n" in command or len(command) > 80:
+ return f"💻 Command:\n{self.format_code_block(command, 'bash')}"
+ 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)}"
+
+ 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:
+ """Truncate text to specified length"""
+ if len(text) <= max_length:
+ return text
+ return text[:max_length] + suffix
\ No newline at end of file
diff --git a/modules/im/formatters/slack_formatter.py b/modules/im/formatters/slack_formatter.py
new file mode 100644
index 000000000..0611fc6e9
--- /dev/null
+++ b/modules/im/formatters/slack_formatter.py
@@ -0,0 +1,116 @@
+from .base_formatter import BaseMarkdownFormatter
+
+
+class SlackFormatter(BaseMarkdownFormatter):
+ """Slack mrkdwn formatter
+
+ Slack uses its own markup language called mrkdwn which is similar to Markdown
+ but with some differences.
+ Reference: https://api.slack.com/reference/surfaces/formatting
+ """
+
+ def format_bold(self, text: str) -> str:
+ """Format bold text using single asterisks"""
+ # In Slack, single asterisks make text bold
+ return f"*{text}*"
+
+ def format_italic(self, text: str) -> str:
+ """Format italic text using underscores"""
+ return f"_{text}_"
+
+ def format_strikethrough(self, text: str) -> str:
+ """Format strikethrough text using tildes"""
+ return f"~{text}~"
+
+ def format_link(self, text: str, url: str) -> str:
+ """Format hyperlink in Slack style"""
+ # Slack uses a different link format: <url|text>
+ return f"<{url}|{text}>"
+
+ def escape_special_chars(self, text: str) -> str:
+ """Escape Slack mrkdwn special characters
+
+ Slack requires escaping these characters: &, <, >
+ """
+ text = text.replace("&", "&amp;")
+ text = text.replace("<", "&lt;")
+ text = text.replace(">", "&gt;")
+ return text
+
+ def format_code_inline(self, text: str) -> str:
+ """Format inline code - same as base but with proper escaping"""
+ # In Slack, backticks work the same way
+ # But we need to ensure special chars are escaped outside of code
+ return f"`{text}`"
+
+ def format_code_block(self, code: str, language: str = "") -> str:
+ """Format code block - Slack style"""
+ # Slack also supports triple backticks for code blocks
+ # Language hint is not displayed but can be included
+ return f"```\n{code}\n```"
+
+ def format_quote(self, text: str) -> str:
+ """Format quoted text - Slack style"""
+ # Slack uses > for quotes, same as standard markdown
+ 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 - Slack style"""
+ # Slack doesn't support nested lists well, so we simplify
+ if level == 0:
+ return f"• {text}"
+ else:
+ # Use spaces for indentation
+ indent = " " * level
+ return f"{indent}◦ {text}"
+
+ def format_numbered_list_item(self, text: str, number: int, level: int = 0) -> str:
+ """Format numbered list item - Slack style"""
+ indent = " " * level
+ return f"{indent}{number}. {text}"
+
+ # Slack-specific formatting methods
+ def format_user_mention(self, user_id: str) -> str:
+ """Format user mention in Slack style"""
+ return f"<@{user_id}>"
+
+ def format_channel_mention(self, channel_id: str) -> str:
+ """Format channel mention in Slack style"""
+ return f"<#{channel_id}>"
+
+ def format_emoji(self, emoji: str, name: str = None) -> str:
+ """Format emoji - Slack supports both Unicode and :name: format"""
+ if name:
+ return f":{name}:"
+ return emoji
+
+ # Override convenience methods for Slack-specific behavior
+ def format_section_header(self, title: str, emoji: str = "") -> str:
+ """Format section header - Slack doesn't have headers, so we use bold"""
+ if emoji:
+ return f"{emoji} {self.format_bold(title)}"
+ return self.format_bold(title)
+
+ def format_horizontal_rule(self) -> str:
+ """Format horizontal rule - Slack doesn't support this well"""
+ # Use a series of dashes as a visual separator
+ return "─" * 40
+
+ def format_tool_name(self, tool_name: str, emoji: str = "🔧") -> str:
+ """Format tool name with emoji and styling"""
+ # Don't escape tool name in code blocks
+ 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 in code blocks
+ 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)}"
+ else:
+ return f"💻 Command: {self.format_code_inline(command)}"
\ No newline at end of file
diff --git a/modules/im/formatters/telegram_formatter.py b/modules/im/formatters/telegram_formatter.py
new file mode 100644
index 000000000..6c1767aad
--- /dev/null
+++ b/modules/im/formatters/telegram_formatter.py
@@ -0,0 +1,88 @@
+from telegram.helpers import escape_markdown
+from .base_formatter import BaseMarkdownFormatter
+
+
+class TelegramFormatter(BaseMarkdownFormatter):
+ """Telegram MarkdownV2 formatter
+
+ Telegram uses MarkdownV2 which requires extensive escaping of special characters.
+ Reference: https://core.telegram.org/bots/api#markdownv2-style
+ """
+
+ def format_bold(self, text: str) -> str:
+ """Format bold text using double asterisks"""
+ # Text needs to be escaped first
+ escaped_text = self.escape_special_chars(text)
+ return f"*{escaped_text}*"
+
+ def format_italic(self, text: str) -> str:
+ """Format italic text using underscores"""
+ escaped_text = self.escape_special_chars(text)
+ return f"_{escaped_text}_"
+
+ def format_strikethrough(self, text: str) -> str:
+ """Format strikethrough text using tildes"""
+ escaped_text = self.escape_special_chars(text)
+ return f"~{escaped_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})"
+
+ 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```"
+
+ # 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_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)
+
+ if inline:
+ return f"{bold_key}: {escaped_value}"
+ else:
+ return f"{bold_key}:\n{escaped_value}"
\ No newline at end of file