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.

refactor: Complete formatter pattern implementation in ClaudeClient

cyhhao808ba75eb4d2
diff --git a/modules/claude_client.py b/modules/claude_client.py
index cc273875e..fd66a1bec 100644
--- a/modules/claude_client.py
+++ b/modules/claude_client.py
@@ -1,4 +1,5 @@
import logging
+import os
from typing import Callable, Optional
from claude_code_sdk import (
query,
@@ -68,8 +69,6 @@ class ClaudeClient:
def _get_relative_path(self, full_path: str) -> str:
"""Convert absolute path to relative path based on ClaudeCode cwd"""
- import os
-
# Get ClaudeCode's current working directory
cwd = self.options.cwd or os.getcwd()
@@ -93,308 +92,40 @@ class ClaudeClient:
return full_path
def _format_tool_use_block(self, block: ToolUseBlock) -> str:
- """Format ToolUseBlock with specific adaptations for different tools"""
- escaped_name = self.formatter.escape_special_chars(block.name)
-
- # Get tool emoji and format based on tool type
- if block.name.startswith("mcp__"):
- # MCP tools - unified handling
- tool_category = block.name.split("__")[1] if "__" in block.name else "mcp"
- emoji_map = {
- "devmcp": "🔧",
- "db": "🗃️",
- "log": "📊",
- "ops": "⚡",
- "human": "👤",
- }
- emoji = emoji_map.get(tool_category, "🔧")
- 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 = {
- "Task": "🤖",
- "Bash": "💻",
- "Glob": "🔍",
- "Grep": "🔎",
- "LS": "📂",
- "Read": "📖",
- "Edit": "✏️",
- "MultiEdit": "📝",
- "Write": "📄",
- "NotebookRead": "📓",
- "NotebookEdit": "📓",
- "WebFetch": "🌐",
- "WebSearch": "🔍",
- "TodoWrite": "✅",
- "ExitPlanMode": "🚪",
- }
- emoji = tool_emoji_map.get(block.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 = []
-
- # File operations
- if "file_path" in block.input and block.input["file_path"]:
- relative_path = self._get_relative_path(block.input["file_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"])
- 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"]
- 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: {self.formatter.format_code_inline(desc)}")
-
- # Pattern/Query operations
- if "pattern" in block.input and block.input["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"])
- 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"])
- 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"])
- 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"])
- 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"])
- 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"]:
- edits_count = len(block.input["edits"])
- input_info.append(f"📝 Edits: {edits_count} changes")
-
- # Other tool-specific parameters
- if "limit" in block.input and block.input["limit"]:
- input_info.append(f"🔢 Limit: {block.input['limit']}")
-
- if "offset" in block.input and block.input["offset"]:
- input_info.append(f"📍 Offset: {block.input['offset']}")
-
- # Task tool parameters
- if "subagent_type" in block.input and block.input["subagent_type"]:
- 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"])
- 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"]:
- 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"]:
- 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"]:
- domains_count = len(block.input["allowed_domains"])
- input_info.append(f"✅ Allowed domains: {domains_count}")
-
- if "blocked_domains" in block.input and block.input["blocked_domains"]:
- domains_count = len(block.input["blocked_domains"])
- input_info.append(f"🚫 Blocked domains: {domains_count}")
-
- # Grep parameters
- if "glob" in block.input and block.input["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"]:
- 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"]:
- 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)
-
- # Handle content specifically based on tool type
- # Tools that already show all their parameters don't need JSON
- show_json = True
- no_json_tools = [
- "Bash",
- "Read",
- "Write",
- "Edit",
- "MultiEdit",
- "LS",
- "Glob",
- "Grep",
- "WebFetch",
- "WebSearch",
- ]
-
- if block.name in no_json_tools:
- show_json = False
-
- if block.name == "TodoWrite":
- # TodoWrite has complex todos array - show as markdown list
- if "todos" in block.input and block.input["todos"]:
- todos = block.input["todos"]
- todos_count = len(todos)
- tool_info += f"\n📋 {todos_count} todo items:"
-
- for todo in todos: # Show all todos, don't limit to 5
- status = todo.get("status", "pending")
- status_emoji = {
- "pending": "⏳",
- "in_progress": "🔄",
- "completed": "✅",
- }.get(status, "⏳")
- priority_emoji = {"high": "🔴", "medium": "🟡", "low": "🟢"}.get(
- todo.get("priority", "medium"), "🟡"
- )
- content = todo.get("content", "No content")[
- :50
- ] # Truncate long content
- if len(todo.get("content", "")) > 50:
- content += "..."
-
- # Add strikethrough for completed items
- if status == "completed":
- # Use formatter's strikethrough method
- formatted_content = self.formatter.format_strikethrough(content)
- tool_info += (
- f"\n• {status_emoji} {priority_emoji} {formatted_content}"
- )
- else:
- escaped_content = self.formatter.escape_special_chars(content)
- tool_info += (
- f"\n• {status_emoji} {priority_emoji} {escaped_content}"
- )
- elif (
- "content" in block.input
- and block.input["content"]
- and block.name in ["Write", "Edit", "MultiEdit"]
- ):
- # Show content in code block for file write operations
- content = str(block.input["content"])
- if len(content) > 300:
- content = content[:300] + "..."
- 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{self.formatter.format_code_block(input_json, 'json')}"
- except:
- # Fallback for non-serializable input
- tool_info += f"\n{self.formatter.format_code_block(str(block.input))}"
-
- return tool_info
-
- def _format_tool_result_block(self, block: ToolResultBlock) -> str:
- """Format ToolResultBlock"""
- if block.is_error:
- emoji = "❌"
- status = "Error"
- else:
- emoji = "✅"
- status = "Success"
-
- # Get tool use ID (shortened)
- tool_id = (
- block.tool_use_id[:8] + "..."
- if len(block.tool_use_id) > 8
- else block.tool_use_id
+ """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
)
- result_info = f"{emoji} {self.formatter.format_bold('Tool Result')}"
-
- # Format content in code block
- if block.content:
- content = str(block.content)
- if len(content) > 500:
- # Truncate very long content
- content = content[:500] + "..."
- result_info += f"\n{self.formatter.format_code_block(content)}"
- return result_info
+ def _format_tool_result_block(self, block: ToolResultBlock) -> str:
+ """Format ToolResultBlock using formatter"""
+ return self.formatter.format_tool_result(block.is_error, block.content)
def _format_system_message(self, message: SystemMessage) -> str:
- """Format SystemMessage"""
+ """Format SystemMessage using formatter"""
cwd = message.data.get("cwd", "Unknown")
- 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}"
+ return self.formatter.format_system_message(cwd, message.subtype)
def _format_assistant_message(self, message: AssistantMessage) -> str:
- """Format AssistantMessage"""
- header = self.formatter.format_section_header("Assistant", "🤖")
- formatted_parts = [header]
+ """Format AssistantMessage using formatter"""
content_parts = self._process_content_blocks(message.content)
- formatted_parts.extend(content_parts)
- return "\n\n".join(formatted_parts)
+ return self.formatter.format_assistant_message(content_parts)
def _format_user_message(self, message: UserMessage) -> str:
- """Format UserMessage"""
- header = self.formatter.format_section_header("Response", "👤")
- formatted_parts = [header]
+ """Format UserMessage using formatter"""
content_parts = self._process_content_blocks(message.content)
- formatted_parts.extend(content_parts)
- return "\n\n".join(formatted_parts)
+ return self.formatter.format_user_message(content_parts)
def _format_result_message(self, message: ResultMessage) -> str:
- """Format ResultMessage"""
- # Use total duration (duration_ms includes API time)
- total_seconds = message.duration_ms / 1000
- minutes = 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 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"
-
- return result_text
+ """Format ResultMessage using formatter"""
+ return self.formatter.format_result_message(
+ message.subtype,
+ message.duration_ms,
+ message.result
+ )
def _is_skip_message(self, message) -> bool:
"""Check if the message should be skipped"""
@@ -412,11 +143,6 @@ class ClaudeClient:
"""Execute query with streaming output"""
try:
async for message in query(prompt=prompt, options=self.options):
- # Format message according to type
-
- print(message)
- print()
-
if self._is_skip_message(message):
continue
diff --git a/modules/im/formatters/base_formatter.py b/modules/im/formatters/base_formatter.py
index e1f7143b2..c085f552c 100644
--- a/modules/im/formatters/base_formatter.py
+++ b/modules/im/formatters/base_formatter.py
@@ -1,5 +1,6 @@
from abc import ABC, abstractmethod
-from typing import Optional, List, Tuple
+from typing import Optional, List, Tuple, Any, Dict
+import json
class BaseMarkdownFormatter(ABC):
@@ -115,4 +116,261 @@ class BaseMarkdownFormatter(ABC):
"""Truncate text to specified length"""
if len(text) <= max_length:
return text
- return text[:max_length] + suffix
\ No newline at end of file
+ return text[:max_length] + suffix
+
+ # Claude message formatting methods
+ def format_system_message(self, cwd: str, subtype: str) -> str:
+ """Format system message"""
+ header = self.format_section_header(f"System {subtype}", "🔧")
+ cwd_line = self.format_file_path(cwd, emoji="📁").replace("File:", "Working directory:")
+ ready_line = f"✨ {self.escape_special_chars('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", "🤖")
+ parts = [header] + content_parts
+ return "\n\n".join(parts)
+
+ def format_user_message(self, content_parts: List[str]) -> str:
+ """Format user/response message"""
+ header = self.format_section_header("Response", "👤")
+ parts = [header] + content_parts
+ return "\n\n".join(parts)
+
+ def format_result_message(self, subtype: str, duration_ms: int, result: Optional[str] = None) -> str:
+ """Format result message"""
+ # Calculate duration
+ total_seconds = duration_ms / 1000
+ minutes = 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
+ header = self.format_section_header(f"Result ({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:
+ """Format a todo item with status and priority"""
+ status_emoji = {
+ "pending": "⏳",
+ "in_progress": "🔄",
+ "completed": "✅"
+ }.get(status, "⏳")
+
+ priority_emoji = {
+ "high": "🔴",
+ "medium": "🟡",
+ "low": "🟢"
+ }.get(priority, "🟡")
+
+ # Truncate long content
+ if len(content) > 50:
+ content = content[:50] + "..."
+
+ # Apply strikethrough for completed items
+ if 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:
+ """Format tool use block with inputs"""
+ # Determine tool emoji and category
+ if 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)}"
+ else:
+ tool_emoji_map = {
+ "Task": "🤖",
+ "Bash": "💻",
+ "Glob": "🔍",
+ "Grep": "🔎",
+ "LS": "📂",
+ "Read": "📖",
+ "Edit": "✏️",
+ "MultiEdit": "📝",
+ "Write": "📄",
+ "NotebookRead": "📓",
+ "NotebookEdit": "📓",
+ "WebFetch": "🌐",
+ "WebSearch": "🔍",
+ "TodoWrite": "✅",
+ "ExitPlanMode": "🚪",
+ }
+ emoji = tool_emoji_map.get(tool_name, "🔧")
+ tool_info = f"{emoji} {self.format_bold('Tool')}: {self.format_code_inline(tool_name)}"
+
+ # Format tool inputs
+ input_info = []
+
+ # File operations
+ if "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 operations
+ if "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 operations
+ if "command" in tool_input and tool_input["command"]:
+ input_info.append(self.format_command(tool_input["command"]))
+
+ # Description
+ if "description" in tool_input and tool_input["description"]:
+ input_info.append(f"📝 Description: {self.format_code_inline(tool_input['description'])}")
+
+ # Pattern/Query
+ if "pattern" in tool_input and 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)}")
+
+ # URL
+ if "url" in tool_input and tool_input["url"]:
+ input_info.append(f"🌐 URL: {self.format_code_inline(str(tool_input['url']))}")
+
+ # Prompt
+ if "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 operations
+ if "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)}")
+
+ # MultiEdit
+ if "edits" in tool_input and tool_input["edits"]:
+ edits_count = len(tool_input["edits"])
+ input_info.append(f"📝 Edits: {edits_count} changes")
+
+ # Other common parameters
+ if "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 tool
+ if "subagent_type" in tool_input and 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 operations
+ if "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']))}")
+
+ 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']))}")
+
+ # WebSearch
+ if "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 specific
+ if "glob" in tool_input and 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']))}")
+
+ 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']))}")
+
+ # Combine tool info with inputs
+ if input_info:
+ tool_info += "\n" + "\n".join(input_info)
+
+ # Handle special tool content formatting
+ if tool_name == "TodoWrite" and "todos" in tool_input:
+ todos = tool_input["todos"]
+ tool_info += f"\n📋 {len(todos)} todo items:"
+ for todo in todos:
+ status = todo.get("status", "pending")
+ priority = todo.get("priority", "medium")
+ content = todo.get("content", "No content")
+ 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"
+ ]
+ return tool_name not in no_json_tools and tool_input and len(str(tool_input)) < 200
\ No newline at end of file