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(slack): add file and image attachment support

yh c23c68914b516
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 1b76bed54..cca1c0296 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -1,10 +1,11 @@
"""Message routing and Agent communication handlers"""
import logging
-from typing import Optional
+from typing import Optional, List
from modules.agents import AgentRequest
from modules.im import MessageContext
+from modules.im.base import FileAttachment
logger = logging.getLogger(__name__)
@@ -63,9 +64,7 @@ class MessageHandler:
message_ts = context.message_id
thread_ts = context.thread_id or context.message_id
if message_ts and thread_ts:
- if self.settings_manager.is_message_already_processed(
- context.channel_id, thread_ts, message_ts
- ):
+ if self.settings_manager.is_message_already_processed(context.channel_id, thread_ts, message_ts):
logger.info(
f"Skipping already processed message: channel={context.channel_id}, "
f"thread={thread_ts}, message={message_ts}"
@@ -73,9 +72,7 @@ class MessageHandler:
return
# Record this message as processed immediately to prevent duplicates
# even if processing fails (we don't want to retry failed messages forever)
- self.settings_manager.record_processed_message(
- context.channel_id, thread_ts, message_ts
- )
+ self.settings_manager.record_processed_message(context.channel_id, thread_ts, message_ts)
# Skip automatic cleanup; receiver tasks are retained until shutdown
@@ -87,9 +84,7 @@ class MessageHandler:
if not self.session_handler:
raise RuntimeError("Session handler not initialized")
- base_session_id, working_path, composite_key = (
- self.session_handler.get_session_info(context)
- )
+ base_session_id, working_path, composite_key = self.session_handler.get_session_info(context)
settings_key = self._get_settings_key(context)
# Update thread's current message_id so log messages follow this user message
@@ -122,17 +117,11 @@ class MessageHandler:
normalized = normalize_subagent_name(parsed.name)
if agent_name == "opencode":
try:
- opencode_agent = self.controller.agent_service.agents.get(
- "opencode"
- )
- if opencode_agent and hasattr(
- opencode_agent, "_get_server"
- ):
+ opencode_agent = self.controller.agent_service.agents.get("opencode")
+ if opencode_agent and hasattr(opencode_agent, "_get_server"):
server = await opencode_agent._get_server()
await server.ensure_running()
- opencode_agents = await server.get_available_agents(
- self.controller.get_cwd(context)
- )
+ opencode_agents = await server.get_available_agents(self.controller.get_cwd(context))
name_map = {
normalize_subagent_name(a.get("name", "")): a
for a in opencode_agents
@@ -142,9 +131,7 @@ class MessageHandler:
if match:
subagent_name = match.get("name")
except Exception as err:
- logger.warning(
- f"Failed to resolve OpenCode subagent: {err}"
- )
+ logger.warning(f"Failed to resolve OpenCode subagent: {err}")
else:
try:
from pathlib import Path
@@ -155,9 +142,7 @@ class MessageHandler:
if subagent_def:
subagent_name = subagent_def.name
subagent_model = subagent_def.model
- subagent_reasoning_effort = (
- subagent_def.reasoning_effort
- )
+ subagent_reasoning_effort = subagent_def.reasoning_effort
except Exception as err:
logger.warning(f"Failed to resolve Claude subagent: {err}")
@@ -184,9 +169,7 @@ class MessageHandler:
ack_context = self._get_target_context(context)
ack_text = self._get_ack_text(agent_name)
try:
- ack_message_id = await self.im_client.send_message(
- ack_context, ack_text
- )
+ ack_message_id = await self.im_client.send_message(ack_context, ack_text)
except Exception as ack_err:
logger.debug(f"Failed to send ack message: {ack_err}")
else:
@@ -195,13 +178,9 @@ class MessageHandler:
if context.message_id:
ack_reaction_message_id = context.message_id
ack_reaction_emoji = ":eyes:"
- ok = await self.im_client.add_reaction(
- context, ack_reaction_message_id, ack_reaction_emoji
- )
+ ok = await self.im_client.add_reaction(context, ack_reaction_message_id, ack_reaction_emoji)
if not ok:
- logger.info(
- "Ack reaction not applied (platform returned False)"
- )
+ logger.info("Ack reaction not applied (platform returned False)")
except Exception as ack_err:
logger.debug(f"Failed to add reaction ack: {ack_err}")
@@ -217,13 +196,16 @@ class MessageHandler:
logger.debug(f"Failed to add subagent reaction: {err}")
if ack_reaction_message_id and ack_reaction_emoji:
try:
- await self.im_client.remove_reaction(
- context, ack_reaction_message_id, ack_reaction_emoji
- )
+ await self.im_client.remove_reaction(context, ack_reaction_message_id, ack_reaction_emoji)
except Exception as err:
- logger.debug(
- f"Failed to remove reaction ack for subagent: {err}"
- )
+ logger.debug(f"Failed to remove reaction ack for subagent: {err}")
+
+ # Process file attachments if present
+ processed_files = None
+ if context.files:
+ processed_files = await self._process_file_attachments(context, working_path)
+ if processed_files:
+ logger.info(f"Processed {len(processed_files)} file attachments for message")
request = AgentRequest(
context=context,
@@ -238,10 +220,9 @@ class MessageHandler:
subagent_model=subagent_model,
subagent_reasoning_effort=subagent_reasoning_effort,
# Pass reaction info for agents to remove when result is sent
- ack_reaction_message_id=ack_reaction_message_id
- if not subagent_name
- else None,
+ ack_reaction_message_id=ack_reaction_message_id if not subagent_name else None,
ack_reaction_emoji=ack_reaction_emoji if not subagent_name else None,
+ files=processed_files,
)
try:
await self.controller.agent_service.handle_message(agent_name, request)
@@ -268,21 +249,15 @@ class MessageHandler:
and ack_reaction_emoji # type: ignore[possibly-undefined]
and not subagent_name # type: ignore[possibly-undefined]
):
- await self.im_client.remove_reaction(
- context, ack_reaction_message_id, ack_reaction_emoji
- )
+ await self.im_client.remove_reaction(context, ack_reaction_message_id, ack_reaction_emoji)
except Exception as cleanup_err:
logger.debug(f"Failed to clean up reaction on error: {cleanup_err}")
- await self.im_client.send_message(
- context, self.formatter.format_error(f"Error: {str(e)}")
- )
+ await self.im_client.send_message(context, self.formatter.format_error(f"Error: {str(e)}"))
async def handle_callback_query(self, context: MessageContext, callback_data: str):
"""Route callback queries to appropriate handlers"""
try:
- logger.info(
- f"handle_callback_query called with data: {callback_data} for user {context.user_id}"
- )
+ logger.info(f"handle_callback_query called with data: {callback_data} for user {context.user_id}")
# Import handlers to avoid circular dependency
from .settings_handler import SettingsHandler
@@ -304,9 +279,7 @@ class MessageHandler:
await handler(context, setting_type)
elif callback_data == "info_msg_types":
- logger.info(
- f"Handling info_msg_types callback for user {context.user_id}"
- )
+ logger.info(f"Handling info_msg_types callback for user {context.user_id}")
await settings_handler.handle_info_message_types(context)
elif callback_data == "info_how_it_works":
@@ -327,9 +300,7 @@ class MessageHandler:
elif callback_data == "cmd_routing":
await settings_handler.handle_routing(context)
- elif (
- callback_data.startswith("info_") and callback_data != "info_msg_types"
- ):
+ elif callback_data.startswith("info_") and callback_data != "info_msg_types":
# Generic info handler
info_type = callback_data.replace("info_", "")
info_text = self.formatter.format_info_message(
@@ -343,9 +314,7 @@ class MessageHandler:
if not self.session_handler:
raise RuntimeError("Session handler not initialized")
- base_session_id, working_path, composite_key = (
- self.session_handler.get_session_info(context)
- )
+ base_session_id, working_path, composite_key = self.session_handler.get_session_info(context)
settings_key = self._get_settings_key(context)
request = AgentRequest(
context=context,
@@ -395,9 +364,7 @@ class MessageHandler:
if not self.session_handler:
raise RuntimeError("Session handler not initialized")
- base_session_id, working_path, composite_key = (
- self.session_handler.get_session_info(context)
- )
+ base_session_id, working_path, composite_key = self.session_handler.get_session_info(context)
settings_key = self._get_settings_key(context)
agent_name = self.controller.resolve_agent_for_context(context)
request = AgentRequest(
@@ -409,16 +376,12 @@ class MessageHandler:
settings_key=settings_key,
)
try:
- handled = await self.controller.agent_service.handle_stop(
- agent_name, request
- )
+ handled = await self.controller.agent_service.handle_stop(agent_name, request)
except KeyError:
await self._handle_missing_agent(context, agent_name)
return False
if not handled:
- await self.im_client.send_message(
- context, "ℹ️ No active session to stop."
- )
+ await self.im_client.send_message(context, "ℹ️ No active session to stop.")
return handled
except Exception as e:
logger.error(f"Error handling inline stop: {e}", exc_info=True)
@@ -444,9 +407,7 @@ class MessageHandler:
finally:
request.ack_message_id = None
- async def _remove_ack_reaction(
- self, context: MessageContext, request: AgentRequest
- ):
+ async def _remove_ack_reaction(self, context: MessageContext, request: AgentRequest):
"""Remove acknowledgement reaction if it still exists."""
if request.ack_reaction_message_id and request.ack_reaction_emoji:
try:
@@ -465,3 +426,100 @@ class MessageHandler:
"""Unified acknowledgement text before agent processing."""
label = agent_name or self.controller.agent_service.default_agent
return f"📨 {label.capitalize()} received, processing..."
+
+ async def _process_file_attachments(self, context: MessageContext, working_path: str) -> Optional[list]:
+ """Download and process file attachments from the message.
+
+ All files (including images) are saved to the working directory.
+ The agent can then use Read tools to access them.
+
+ Args:
+ context: Message context with file attachments
+ working_path: Working directory path for saving files
+
+ Returns:
+ List of processed FileAttachment objects with local_path set
+ """
+ import os
+ from modules.im.base import FileAttachment
+
+ if not context.files:
+ return None
+
+ processed = []
+ for attachment in context.files:
+ if not isinstance(attachment, FileAttachment):
+ continue
+
+ try:
+ # Download the file content
+ if hasattr(self.im_client, "download_file") and attachment.url:
+ # Create a dict for Slack's download_file method
+ file_info = {
+ "url_private_download": attachment.url,
+ "name": attachment.name,
+ }
+ content = await self.im_client.download_file(file_info)
+ if content:
+ # Save all files (including images) to working directory
+ # Create attachments subdirectory
+ attachments_dir = os.path.join(working_path, "_attachments")
+ os.makedirs(attachments_dir, exist_ok=True)
+
+ # Sanitize filename and save
+ safe_name = self._sanitize_filename(attachment.name)
+ local_path = os.path.join(attachments_dir, safe_name)
+
+ # Avoid overwriting: add timestamp if file exists
+ if os.path.exists(local_path):
+ import time
+
+ base, ext = os.path.splitext(safe_name)
+ safe_name = f"{base}_{int(time.time())}{ext}"
+ local_path = os.path.join(attachments_dir, safe_name)
+
+ with open(local_path, "wb") as f:
+ f.write(content)
+
+ attachment.local_path = local_path
+ attachment.size = len(content)
+
+ # Determine file type for logging
+ is_image = attachment.mimetype.startswith("image/")
+ file_type = "image" if is_image else "file"
+
+ logger.info(f"Saved {file_type} '{attachment.name}' ({len(content)} bytes) to '{local_path}'")
+
+ processed.append(attachment)
+ else:
+ logger.warning(f"Failed to download file: {attachment.name}")
+ else:
+ logger.warning(f"Cannot download file: {attachment.name} (no URL or download method)")
+
+ except Exception as e:
+ logger.error(f"Error processing file attachment {attachment.name}: {e}")
+ continue
+
+ return processed if processed else None
+
+ def _sanitize_filename(self, filename: str) -> str:
+ """Sanitize filename to be safe for filesystem.
+
+ Args:
+ filename: Original filename
+
+ Returns:
+ Sanitized filename safe for filesystem
+ """
+ import re
+
+ # Remove or replace dangerous characters
+ # Keep alphanumeric, dots, hyphens, underscores
+ safe = re.sub(r"[^\w\-.]", "_", filename)
+ # Prevent directory traversal
+ safe = safe.replace("..", "_")
+ # Limit length
+ if len(safe) > 200:
+ base, ext = safe.rsplit(".", 1) if "." in safe else (safe, "")
+ safe = base[:195] + ("." + ext if ext else "")
+ return safe or "unnamed_file"
diff --git a/modules/agents/base.py b/modules/agents/base.py
index a5370a908..7623d1c75 100644
--- a/modules/agents/base.py
+++ b/modules/agents/base.py
@@ -5,9 +5,10 @@ from __future__ import annotations
import time
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
-from typing import Any, Dict, Optional
+from typing import Any, Dict, List, Optional
from modules.im import MessageContext
+from modules.im.base import FileAttachment
@dataclass
@@ -31,6 +32,8 @@ class AgentRequest:
# Reaction ack: emoji added to user's message, to be removed when result is sent
ack_reaction_message_id: Optional[str] = None
ack_reaction_emoji: Optional[str] = None
+ # File attachments (downloaded or with URLs for download)
+ files: Optional[List[FileAttachment]] = None
@dataclass
@@ -75,9 +78,7 @@ class BaseAgent(ABC):
except Exception as err:
import logging
- logging.getLogger(__name__).debug(
- f"Failed to remove reaction ack: {err}"
- )
+ logging.getLogger(__name__).debug(f"Failed to remove reaction ack: {err}")
finally:
request.ack_reaction_message_id = None
request.ack_reaction_emoji = None
@@ -95,14 +96,10 @@ class BaseAgent(ABC):
) -> None:
if duration_ms is None:
duration_ms = self._calculate_duration_ms(started_at)
- formatted = self.im_client.formatter.format_result_message(
- subtype or "", duration_ms, result_text
- )
+ formatted = self.im_client.formatter.format_result_message(subtype or "", duration_ms, result_text)
if suffix:
formatted = f"{formatted}\n{suffix}"
- await self.controller.emit_agent_message(
- context, "result", formatted, parse_mode=parse_mode
- )
+ await self.controller.emit_agent_message(context, "result", formatted, parse_mode=parse_mode)
# Remove ack reaction after result is sent
if request:
await self._remove_ack_reaction(request)
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index ceab05196..3547ae023 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -6,6 +6,7 @@ from typing import Callable, Optional
from claude_agent_sdk import TextBlock, ToolUseBlock
from modules.agents.base import AgentRequest, BaseAgent
+
# NOTE: AskUserQuestion support is disabled because Claude Code SDK cannot
# respond to it programmatically. See: https://github.com/anthropics/claude-code/issues/10168
# Keeping the import for future use when SDK adds support.
@@ -72,10 +73,11 @@ class ClaudeAgent(BaseAgent):
(request.ack_reaction_message_id, request.ack_reaction_emoji)
)
- await client.query(request.message, session_id=request.composite_session_id)
- logger.info(
- f"Sent message to Claude for session {request.composite_session_id}"
- )
+ # Prepare message with file attachment info if present
+ message = self._prepare_message_with_files(request)
+
+ await client.query(message, session_id=request.composite_session_id)
+ logger.info(f"Sent message to Claude for session {request.composite_session_id}")
await self._delete_ack(context, request)
@@ -84,25 +86,19 @@ class ClaudeAgent(BaseAgent):
or self.receiver_tasks[request.composite_session_id].done()
):
self.receiver_tasks[request.composite_session_id] = asyncio.create_task(
- self._receive_messages(
- client, request.base_session_id, request.working_path, context
- )
+ self._receive_messages(client, request.base_session_id, request.working_path, context)
)
except Exception as e:
logger.error(f"Error processing Claude message: {e}", exc_info=True)
# Clean up the specific reaction for this request (not FIFO)
- await self._remove_specific_pending_reaction(
- request.composite_session_id, context, request
- )
- await self.session_handler.handle_session_error(
- request.composite_session_id, context, e
- )
+ await self._remove_specific_pending_reaction(request.composite_session_id, context, request)
+ await self.session_handler.handle_session_error(request.composite_session_id, context, e)
finally:
await self._delete_ack(context, request)
async def _handle_question_callback(self, request: AgentRequest) -> None:
"""Handle question-related callbacks (button clicks, modal submissions).
-
+
NOTE: This method is disabled because Claude Code SDK cannot respond to
AskUserQuestion programmatically. See: https://github.com/anthropics/claude-code/issues/10168
"""
@@ -116,9 +112,7 @@ class ClaudeAgent(BaseAgent):
async def clear_sessions(self, settings_key: str) -> int:
"""Clear Claude sessions scoped to the provided settings key."""
- agent_map = self.settings_manager.sessions_store.get_agent_map(
- settings_key, self.name
- )
+ agent_map = self.settings_manager.sessions_store.get_agent_map(settings_key, self.name)
session_bases_to_clear = set(agent_map.keys())
self.settings_manager.clear_agent_sessions(settings_key, self.name)
@@ -152,9 +146,7 @@ class ClaudeAgent(BaseAgent):
return False
client = self.claude_sessions[composite_key]
- await self.controller.emit_agent_message(
- request.context, "notify", "🛑 Interrupting Claude session..."
- )
+ await self.controller.emit_agent_message(request.context, "notify", "🛑 Interrupting Claude session...")
try:
if hasattr(client, "interrupt"):
await client.interrupt()
@@ -199,13 +191,9 @@ class ClaudeAgent(BaseAgent):
async for message in client.receive_messages():
try:
- claude_session_id = self._maybe_capture_session_id(
- message, base_session_id, settings_key
- )
+ claude_session_id = self._maybe_capture_session_id(message, base_session_id, settings_key)
if claude_session_id:
- logger.info(
- f"Captured Claude session id {claude_session_id} for {base_session_id}"
- )
+ logger.info(f"Captured Claude session id {claude_session_id} for {base_session_id}")
if self.claude_client._is_skip_message(message):
continue
@@ -231,9 +219,7 @@ class ClaudeAgent(BaseAgent):
formatter.format_toolcall(
block.name,
block.input,
- get_relative_path=lambda path: self.get_relative_path(
- path, context
- ),
+ get_relative_path=lambda path: self.get_relative_path(path, context),
)
)
elif isinstance(block, TextBlock):
@@ -245,9 +231,7 @@ class ClaudeAgent(BaseAgent):
if assistant_text:
self._last_assistant_text[composite_key] = assistant_text
- pending = self._pending_assistant_message.pop(
- composite_key, None
- )
+ pending = self._pending_assistant_message.pop(composite_key, None)
if pending:
await self.controller.emit_agent_message(
context,
@@ -265,12 +249,8 @@ class ClaudeAgent(BaseAgent):
)
if text_parts:
- formatted_assistant = formatter.format_assistant_message(
- text_parts
- )
- self._pending_assistant_message[composite_key] = (
- formatted_assistant
- )
+ formatted_assistant = formatter.format_assistant_message(text_parts)
+ self._pending_assistant_message[composite_key] = formatted_assistant
# AskUserQuestion handling disabled - SDK cannot respond programmatically
# See: https://github.com/anthropics/claude-code/issues/10168
@@ -301,9 +281,7 @@ class ClaudeAgent(BaseAgent):
if message_type == "system":
formatted_message = self.claude_client.format_message(
message,
- get_relative_path=lambda path: self.get_relative_path(
- path, context
- ),
+ get_relative_path=lambda path: self.get_relative_path(path, context),
)
if formatted_message and formatted_message.strip():
await self.controller.emit_agent_message(
@@ -315,9 +293,7 @@ class ClaudeAgent(BaseAgent):
continue
if message_type == "result":
- pending = self._pending_assistant_message.pop(
- composite_key, None
- )
+ pending = self._pending_assistant_message.pop(composite_key, None)
result_text = getattr(message, "result", None)
used_fallback = False
if not result_text:
@@ -346,21 +322,15 @@ class ClaudeAgent(BaseAgent):
await self._remove_pending_reaction(composite_key, context)
self._last_assistant_text.pop(composite_key, None)
- session = await self.session_manager.get_or_create_session(
- context.user_id, context.channel_id
- )
+ session = await self.session_manager.get_or_create_session(context.user_id, context.channel_id)
if session:
- session.session_active[
- f"{base_session_id}:{working_path}"
- ] = False
+ session.session_active[f"{base_session_id}:{working_path}"] = False
continue
# Ignore UserMessage/tool results; toolcalls are emitted from ToolUseBlock.
continue
except Exception as e:
- logger.error(
- f"Error processing message from Claude: {e}", exc_info=True
- )
+ logger.error(f"Error processing message from Claude: {e}", exc_info=True)
continue
except Exception as e:
composite_key = f"{base_session_id}:{working_path}"
@@ -387,9 +357,7 @@ class ClaudeAgent(BaseAgent):
finally:
request.ack_message_id = None
- async def _remove_pending_reaction(
- self, composite_key: str, context: MessageContext
- ) -> None:
+ async def _remove_pending_reaction(self, composite_key: str, context: MessageContext) -> None:
"""Remove the oldest stored reaction for a session after result is sent.
Uses FIFO queue to handle multiple messages in the same session.
@@ -406,9 +374,7 @@ class ClaudeAgent(BaseAgent):
except Exception as err:
logger.debug(f"Failed to remove reaction ack: {err}")
- async def _remove_ack_reaction_direct(
- self, context: MessageContext, request: AgentRequest
- ) -> None:
+ async def _remove_ack_reaction_direct(self, context: MessageContext, request: AgentRequest) -> None:
"""Remove ack reaction directly from request (for error paths before queuing)."""
if request.ack_reaction_message_id and request.ack_reaction_emoji:
try:
@@ -449,9 +415,7 @@ class ClaudeAgent(BaseAgent):
logger.debug(f"Failed to remove reaction ack: {err}")
return
- async def _clear_pending_reactions(
- self, composite_key: str, context: MessageContext
- ) -> None:
+ async def _clear_pending_reactions(self, composite_key: str, context: MessageContext) -> None:
"""Clear all pending reactions for a session (for error cleanup)."""
reactions = self._pending_reactions.pop(composite_key, None)
if reactions:
@@ -461,9 +425,7 @@ class ClaudeAgent(BaseAgent):
except Exception as err:
logger.debug(f"Failed to remove reaction ack: {err}")
- def get_relative_path(
- self, abs_path: str, context: Optional[MessageContext] = None
- ) -> str:
+ def get_relative_path(self, abs_path: str, context: Optional[MessageContext] = None) -> str:
"""Convert absolute path to relative path from working directory."""
try:
cwd = self.session_handler.get_working_path(context)
@@ -502,9 +464,7 @@ class ClaudeAgent(BaseAgent):
):
session_id = message.data.get("session_id")
if session_id:
- self.session_handler.capture_session_id(
- base_session_id, session_id, settings_key
- )
+ self.session_handler.capture_session_id(base_session_id, session_id, settings_key)
return session_id
return None
@@ -515,9 +475,7 @@ class ClaudeAgent(BaseAgent):
if isinstance(block, TextBlock):
text = block.text.strip() if block.text else ""
if text:
- parts.append(
- self.claude_client.formatter.escape_special_chars(text)
- )
+ parts.append(self.claude_client.formatter.escape_special_chars(text))
return "\n\n".join(parts).strip()
def _detect_message_type(self, message) -> Optional[str]:
@@ -532,3 +490,63 @@ class ClaudeAgent(BaseAgent):
"ResultMessage": "result",
}
return mapping.get(class_name)
+
+ def _prepare_message_with_files(self, request: AgentRequest) -> str:
+ """Prepare message with file attachment information.
+
+ If there are file attachments, prepend file info to the message
+ so Claude knows what files are available to read.
+
+ Args:
+ request: The agent request containing message and files
+
+ Returns:
+ Message string, potentially with file info prepended
+ """
+ if not request.files:
+ return request.message
+
+ # Build file info section
+ file_info_parts = []
+ images = []
+ other_files = []
+
+ for attachment in request.files:
+ if not attachment.local_path:
+ continue
+
+ is_image = attachment.mimetype.startswith("image/")
+ if is_image:
+ images.append(attachment)
+ else:
+ other_files.append(attachment)
+
+ # Format file info
+ if images:
+ if len(images) == 1:
+ img = images[0]
+ file_info_parts.append(f"[User attached an image: {img.local_path}]")
+ else:
+ paths = ", ".join(img.local_path for img in images)
+ file_info_parts.append(f"[User attached {len(images)} images: {paths}]")
+
+ if other_files:
+ if len(other_files) == 1:
+ f = other_files[0]
+ file_info_parts.append(f"[User attached a file: {f.local_path} ({f.mimetype})]")
+ else:
+ files_desc = ", ".join(f"{f.local_path} ({f.mimetype})" for f in other_files)
+ file_info_parts.append(f"[User attached {len(other_files)} files: {files_desc}]")
+
+ if not file_info_parts:
+ return request.message
+
+ # Combine file info with user message
+ file_info = "\n".join(file_info_parts)
+
+ # If there's no text message, just use file info
+ if not request.message or not request.message.strip():
+ return file_info
+
+ # Prepend file info to message
+ return f"{file_info}\n\n{request.message}"
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index e6daf7ec2..243de26f8 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -58,9 +58,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
async with lock:
pending = self._question_handler.get_pending(request.base_session_id)
- is_modal_open = (
- pending and request.message == "opencode_question:open_modal"
- )
+ is_modal_open = pending and request.message == "opencode_question:open_modal"
is_answer_submission = pending and not is_modal_open
existing_task = self._active_requests.get(request.base_session_id)
@@ -80,15 +78,11 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
"OpenCode session %s already running; cancelling before new request",
request.base_session_id,
)
- req_info = self._session_manager.get_request_session(
- request.base_session_id
- )
+ req_info = self._session_manager.get_request_session(request.base_session_id)
if req_info:
server = await self._get_server()
await server.abort_session(req_info[0], req_info[1])
- await self._session_manager.wait_for_session_idle(
- server, req_info[0], req_info[1]
- )
+ await self._session_manager.wait_for_session_idle(server, req_info[0], req_info[1])
existing_task.cancel()
try:
@@ -159,9 +153,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
await self._delete_ack(request)
await self._session_manager.ensure_working_dir(request.working_path)
- session_id = await self._session_manager.get_or_create_session_id(
- request, server
- )
+ session_id = await self._session_manager.get_or_create_session_id(request, server)
if not session_id:
await self.controller.emit_agent_message(
request.context,
@@ -179,9 +171,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
)
if self._session_manager.mark_initialized(session_id):
- system_text = self.im_client.formatter.format_system_message(
- request.working_path, "init", session_id
- )
+ system_text = self.im_client.formatter.format_system_message(request.working_path, "init", session_id)
await self.controller.emit_agent_message(
request.context,
"system",
@@ -190,9 +180,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
)
try:
- override_agent, override_model, override_reasoning = (
- self.controller.get_opencode_overrides(request.context)
- )
+ override_agent, override_model, override_reasoning = self.controller.get_opencode_overrides(request.context)
override_agent = request.subagent_name or override_agent
if request.subagent_name:
@@ -200,13 +188,9 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
override_reasoning = request.subagent_reasoning_effort
if request.subagent_name and not override_model:
- override_model = server.get_agent_model_from_config(
- request.subagent_name
- )
+ override_model = server.get_agent_model_from_config(request.subagent_name)
if request.subagent_name and not override_reasoning:
- override_reasoning = server.get_agent_reasoning_effort_from_config(
- request.subagent_name
- )
+ override_reasoning = server.get_agent_reasoning_effort_from_config(request.subagent_name)
agent_to_use = override_agent
if not agent_to_use:
@@ -223,9 +207,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
reasoning_effort = override_reasoning
if not reasoning_effort:
- reasoning_effort = server.get_agent_reasoning_effort_from_config(
- agent_to_use
- )
+ reasoning_effort = server.get_agent_reasoning_effort_from_config(agent_to_use)
baseline_message_ids: set[str] = set()
try:
@@ -238,14 +220,15 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
if message_id:
baseline_message_ids.add(message_id)
except Exception as err:
- logger.debug(
- f"Failed to snapshot OpenCode messages before prompt: {err}"
- )
+ logger.debug(f"Failed to snapshot OpenCode messages before prompt: {err}")
+
+ # Prepare message with file attachment info if present
+ prompt_text = self._prepare_message_with_files(request)
await server.prompt_async(
session_id=session_id,
directory=request.working_path,
- text=request.message,
+ text=prompt_text,
agent=agent_to_use,
model=model_dict,
reasoning_effort=reasoning_effort,
@@ -317,17 +300,13 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
except Exception as e:
error_name = type(e).__name__
error_details = str(e).strip()
- error_text = (
- f"{error_name}: {error_details}" if error_details else error_name
- )
+ error_text = f"{error_name}: {error_details}" if error_details else error_name
logger.error(f"OpenCode request failed: {error_text}", exc_info=True)
try:
await server.abort_session(session_id, request.working_path)
except Exception as abort_err:
- logger.warning(
- f"Failed to abort OpenCode session after error: {abort_err}"
- )
+ logger.warning(f"Failed to abort OpenCode session after error: {abort_err}")
# Clean up answer reaction on error
await self._question_handler.clear(request.base_session_id)
@@ -365,9 +344,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
if opencode_session_id:
self.settings_manager.remove_active_poll(opencode_session_id)
- await self.controller.emit_agent_message(
- request.context, "notify", "Terminated OpenCode execution."
- )
+ await self.controller.emit_agent_message(request.context, "notify", "Terminated OpenCode execution.")
logger.info(f"OpenCode session {request.base_session_id} terminated via /stop")
return True
@@ -437,9 +414,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
directory=poll_info.working_path,
)
except Exception as err:
- logger.warning(
- f"Failed to verify OpenCode session {session_id} for restoration: {err}"
- )
+ logger.warning(f"Failed to verify OpenCode session {session_id} for restoration: {err}")
stale_poll_ids.append(session_id)
continue
@@ -455,13 +430,9 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
break
last_assistant_finish = info.get("finish")
- session_still_active = (
- has_in_progress or last_assistant_finish == "tool-calls"
- )
+ session_still_active = has_in_progress or last_assistant_finish == "tool-calls"
if not session_still_active:
- logger.info(
- f"OpenCode session {session_id} has completed, removing from active polls"
- )
+ logger.info(f"OpenCode session {session_id} has completed, removing from active polls")
stale_poll_ids.append(session_id)
continue
@@ -470,9 +441,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
f"(thread={poll_info.base_session_id}, cwd={poll_info.working_path})"
)
- task = asyncio.create_task(
- self._poll_loop.run_restored_poll_loop(poll_info)
- )
+ task = asyncio.create_task(self._poll_loop.run_restored_poll_loop(poll_info))
self._active_requests[poll_info.base_session_id] = task
self._session_manager.set_request_session(
poll_info.base_session_id,
@@ -491,3 +460,63 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
logger.info(f"Removed {len(stale_poll_ids)} stale active poll(s)")
return restored_count
+
+ def _prepare_message_with_files(self, request: AgentRequest) -> str:
+ """Prepare message with file attachment information.
+
+ If there are file attachments, prepend file info to the message
+ so the agent knows what files are available to read.
+
+ Args:
+ request: The agent request containing message and files
+
+ Returns:
+ Message string, potentially with file info prepended
+ """
+ if not request.files:
+ return request.message
+
+ # Build file info section
+ file_info_parts = []
+ images = []
+ other_files = []
+
+ for attachment in request.files:
+ if not attachment.local_path:
+ continue
+
+ is_image = attachment.mimetype.startswith("image/")
+ if is_image:
+ images.append(attachment)
+ else:
+ other_files.append(attachment)
+
+ # Format file info
+ if images:
+ if len(images) == 1:
+ img = images[0]
+ file_info_parts.append(f"[User attached an image: {img.local_path}]")
+ else:
+ paths = ", ".join(img.local_path for img in images)
+ file_info_parts.append(f"[User attached {len(images)} images: {paths}]")
+
+ if other_files:
+ if len(other_files) == 1:
+ f = other_files[0]
+ file_info_parts.append(f"[User attached a file: {f.local_path} ({f.mimetype})]")
+ else:
+ files_desc = ", ".join(f"{f.local_path} ({f.mimetype})" for f in other_files)
+ file_info_parts.append(f"[User attached {len(other_files)} files: {files_desc}]")
+
+ if not file_info_parts:
+ return request.message
+
+ # Combine file info with user message
+ file_info = "\n".join(file_info_parts)
+
+ # If there's no text message, just use file info
+ if not request.message or not request.message.strip():
+ return file_info
+
+ # Prepend file info to message
+ return f"{file_info}\n\n{request.message}"
diff --git a/modules/im/base.py b/modules/im/base.py
index 9568def67..4ddb76d81 100644
--- a/modules/im/base.py
+++ b/modules/im/base.py
@@ -9,19 +9,34 @@ logger = logging.getLogger(__name__)
# Data structures for platform-agnostic messaging
+@dataclass
+class FileAttachment:
+ """Platform-agnostic file attachment"""
+
+ name: str # File name
+ mimetype: str # MIME type (e.g., "image/png", "application/pdf")
+ url: Optional[str] = None # URL to download the file (platform-specific)
+ content: Optional[bytes] = None # Downloaded file content
+ local_path: Optional[str] = None # Local path after download
+ size: Optional[int] = None # File size in bytes
+
+
@dataclass
class MessageContext:
"""Platform-agnostic message context"""
+
user_id: str
channel_id: str
thread_id: Optional[str] = None
message_id: Optional[str] = None
platform_specific: Optional[Dict[str, Any]] = None
+ files: Optional[list] = None # List of FileAttachment objects
@dataclass
class InlineButton:
"""Platform-agnostic inline button"""
+
text: str
callback_data: str
@@ -29,6 +44,7 @@ class InlineButton:
@dataclass
class InlineKeyboard:
"""Platform-agnostic inline keyboard"""
+
buttons: list[list[InlineButton]] # 2D array for row/column layout
@@ -36,7 +52,7 @@ class InlineKeyboard:
@dataclass
class BaseIMConfig(ABC):
"""Abstract base class for IM platform configurations"""
-
+
@abstractmethod
def validate(self) -> None:
"""Validate the configuration
@@ -46,30 +62,29 @@ class BaseIMConfig(ABC):
"""
pass
-
def validate_required_string(self, value: Optional[str], field_name: str) -> None:
"""Helper method to validate required string fields
-
+
Args:
value: The value to validate
field_name: Name of the field for error messages
-
+
Raises:
ValueError: If value is None or empty
"""
if not value or not value.strip():
raise ValueError(f"{field_name} is required and cannot be empty")
-
+
def validate_optional_int(self, value: Optional[str], field_name: str) -> Optional[int]:
"""Helper method to validate and convert optional integer fields
-
+
Args:
value: String value to convert
field_name: Name of the field for error messages
-
+
Returns:
Converted integer or None
-
+
Raises:
ValueError: If value is not a valid integer
"""
@@ -85,7 +100,7 @@ class BaseIMConfig(ABC):
# IM Client base class
class BaseIMClient(ABC):
"""Abstract base class for IM platform clients"""
-
+
def __init__(self, config: BaseIMConfig):
self.config = config
# Initialize callback storage
@@ -94,54 +109,54 @@ class BaseIMClient(ABC):
self.on_callback_query_callback: Optional[Callable] = None
# Platform-specific formatter will be set by subclasses
self.formatter: Optional[Any] = None
-
+
def get_default_parse_mode(self) -> Optional[str]:
"""Get the default parse mode for this platform
-
+
Returns:
Default parse mode string for the platform
"""
# Default implementation - subclasses should override
return None
-
+
def should_use_thread_for_reply(self) -> bool:
"""Check if this platform uses threads for replies
-
+
Returns:
True if platform uses threads (like Slack), False otherwise
"""
# Default implementation - subclasses should override
return False
-
+
@abstractmethod
- 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
-
+
Args:
context: Message context (channel, thread, etc)
text: Message text
parse_mode: Optional formatting mode (markdown, html, etc)
reply_to: Optional message ID to reply to
-
+
Returns:
Message ID of sent message
"""
pass
-
+
@abstractmethod
- 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
-
+
Args:
context: Message context
text: Message text
keyboard: Inline keyboard configuration
parse_mode: Optional formatting mode
-
+
Returns:
Message ID of sent message
"""
@@ -156,7 +171,7 @@ class BaseIMClient(ABC):
) -> str:
"""Upload markdown content as a file (optional per platform)."""
raise NotImplementedError
-
+
@abstractmethod
async def edit_message(
self,
@@ -197,27 +212,26 @@ class BaseIMClient(ABC):
keyboard=None,
parse_mode=parse_mode,
)
-
+
@abstractmethod
- 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 from inline button
-
+
Args:
callback_id: Callback query ID
text: Optional notification text
show_alert: Show as alert popup
-
+
Returns:
Success status
"""
pass
-
+
@abstractmethod
def register_handlers(self):
"""Register platform-specific message and command handlers"""
pass
-
+
@abstractmethod
def run(self):
"""Start the bot/client"""
@@ -226,38 +240,40 @@ class BaseIMClient(ABC):
async def shutdown(self) -> None:
"""Best-effort async shutdown for platform resources."""
return None
-
+
@abstractmethod
async def get_user_info(self, user_id: str) -> Dict[str, Any]:
"""Get information about a user
-
+
Args:
user_id: Platform-specific user ID
-
+
Returns:
User information dict
"""
pass
-
+
@abstractmethod
async def get_channel_info(self, channel_id: str) -> Dict[str, Any]:
"""Get information about a channel/chat
-
+
Args:
channel_id: Platform-specific channel ID
-
+
Returns:
Channel information dict
"""
pass
-
- def register_callbacks(self,
- on_message: Optional[Callable] = None,
- on_command: Optional[Dict[str, Callable]] = None,
- on_callback_query: Optional[Callable] = None,
- **kwargs):
+
+ def register_callbacks(
+ self,
+ on_message: Optional[Callable] = None,
+ on_command: Optional[Dict[str, Callable]] = None,
+ on_callback_query: Optional[Callable] = None,
+ **kwargs,
+ ):
"""Register callback functions for different events
-
+
Args:
on_message: Callback for text messages
on_command: Dict of command callbacks
@@ -267,14 +283,14 @@ class BaseIMClient(ABC):
self.on_message_callback = on_message
self.on_command_callbacks = on_command or {}
self.on_callback_query_callback = on_callback_query
-
+
# Store any additional callbacks
for key, value in kwargs.items():
setattr(self, f"{key}_callback", value)
-
+
def log_error(self, message: str, exception: Optional[Exception] = None):
"""Standardized error logging
-
+
Args:
message: Error message
exception: Optional exception to log
@@ -283,41 +299,37 @@ class BaseIMClient(ABC):
logger.error(f"{message}: {exception}")
else:
logger.error(message)
-
+
def log_info(self, message: str):
"""Standardized info logging
-
+
Args:
message: Info message
"""
logger.info(message)
- async def add_reaction(
- self, context: MessageContext, message_id: str, emoji: str
- ) -> bool:
+ async def add_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
"""Add a reaction to an existing message.
Default implementation returns False (unsupported).
"""
return False
- async def remove_reaction(
- self, context: MessageContext, message_id: str, emoji: str
- ) -> bool:
+ async def remove_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
"""Remove a reaction from an existing message.
Default implementation returns False (unsupported).
"""
return False
-
+
@abstractmethod
def format_markdown(self, text: str) -> str:
"""Format markdown text for the specific platform
-
+
Args:
text: Text with common markdown formatting
-
+
Returns:
Platform-specific formatted text
"""
- pass
\ No newline at end of file
+ pass
diff --git a/modules/im/slack.py b/modules/im/slack.py
index 1caa14cc5..2fb5010d8 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -3,7 +3,8 @@ import asyncio
import hashlib
import logging
import time
-from typing import Dict, Any, Optional, Callable
+import aiohttp
+from typing import Dict, Any, Optional, Callable, List
from slack_sdk.web.async_client import AsyncWebClient
from slack_sdk.socket_mode.aiohttp import SocketModeClient
from slack_sdk.socket_mode.request import SocketModeRequest
@@ -11,7 +12,7 @@ from slack_sdk.socket_mode.response import SocketModeResponse
from slack_sdk.errors import SlackApiError
from markdown_to_mrkdwn import SlackMarkdownConverter
-from .base import BaseIMClient, MessageContext, InlineKeyboard, InlineButton
+from .base import BaseIMClient, MessageContext, InlineKeyboard, InlineButton, FileAttachment
from config.v2_config import SlackConfig
from .formatters import SlackFormatter
@@ -203,6 +204,53 @@ class SlackBot(BaseIMClient):
file_id = result.get("files", [{}])[0].get("id")
return file_id or ""
+ async def download_file(self, file_info: Dict[str, Any]) -> Optional[bytes]:
+ """Download a Slack file using the private URL.
+
+ Args:
+ file_info: Slack file object containing url_private_download and other metadata
+
+ Returns:
+ File content as bytes, or None if download fails
+ """
+ url = file_info.get("url_private_download") or file_info.get("url_private")
+ if not url:
+ logger.warning(f"No download URL for file: {file_info.get('name')}")
+ return None
+
+ try:
+ headers = {"Authorization": f"Bearer {self.config.bot_token}"}
+ async with aiohttp.ClientSession() as session:
+ async with session.get(url, headers=headers) as response:
+ if response.status == 200:
+ return await response.read()
+ else:
+ logger.error(f"Failed to download file: HTTP {response.status}")
+ return None
+ except Exception as e:
+ logger.error(f"Error downloading Slack file: {e}")
+ return None
+
+ def _extract_file_attachments(self, files: List[Dict[str, Any]]) -> List[FileAttachment]:
+ """Convert Slack file objects to FileAttachment list.
+
+ Args:
+ files: List of Slack file objects from event
+
+ Returns:
+ List of FileAttachment objects
+ """
+ attachments = []
+ for f in files:
+ attachment = FileAttachment(
+ name=f.get("name", "unknown"),
+ mimetype=f.get("mimetype", "application/octet-stream"),
+ url=f.get("url_private_download") or f.get("url_private"),
+ size=f.get("size"),
+ )
+ attachments.append(attachment)
+ return attachments
+
async def add_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
"""Add a reaction emoji to a Slack message."""
self._ensure_clients()
@@ -543,13 +591,17 @@ class SlackBot(BaseIMClient):
logger.info(f"Skipping message event with bot mention: '{text}'")
return
- # Ignore messages without user or without actual text
+ # Extract file attachments if present
+ slack_files = event.get("files", [])
+ file_attachments = self._extract_file_attachments(slack_files) if slack_files else None
+
+ # Ignore messages without user or without actual text/files
user_id = event.get("user")
if not user_id:
logger.debug("Ignoring Slack message without user id")
return
- if not text:
- logger.debug("Ignoring Slack message with empty text")
+ if not text and not file_attachments:
+ logger.debug("Ignoring Slack message with empty text and no files")
return
# Check if we require mention in channels (not DMs)
@@ -598,6 +650,7 @@ class SlackBot(BaseIMClient):
thread_id=thread_id, # Always have a thread_id
message_id=event.get("ts"),
platform_specific={"team_id": payload.get("team_id"), "event": event},
+ files=file_attachments,
)
# Handle slash commands in regular messages
@@ -628,12 +681,17 @@ class SlackBot(BaseIMClient):
# For Slack: if no thread_ts, use the message's own ts as thread_id (start of thread)
thread_id = event.get("thread_ts") or event.get("ts")
+ # Extract file attachments if present
+ slack_files = event.get("files", [])
+ file_attachments = self._extract_file_attachments(slack_files) if slack_files else None
+
context = MessageContext(
user_id=event.get("user"),
channel_id=channel_id,
thread_id=thread_id, # Always have a thread_id
message_id=event.get("ts"),
platform_specific={"team_id": payload.get("team_id"), "event": event},
+ files=file_attachments,
)
# Mark thread as active when bot is @mentioned