From d972f4b314d0bd678cc3290bc34ea7f82254dcdd Mon Sep 17 00:00:00 2001 From: "Timur Kh." Date: Mon, 23 Nov 2026 18:19:24 +0300 Subject: [PATCH] add images support --- src/homeagent/agent/antigravity.py | 66 ++- src/homeagent/agent/attachments.py | 602 ++++++++++++++++++++++++ src/homeagent/agent/base.py | 4 + src/homeagent/agent/gemini.py | 55 ++- src/homeagent/agent/mcp_bridge.py | 141 ++++++ src/homeagent/agent/openai_agent.py | 107 ++++- src/homeagent/bot/handlers.py | 177 +++++-- src/homeagent/bot/mcp_handlers.py | 22 +- src/homeagent/bot/media.py | 240 ++++++++++ src/homeagent/bot/progress.py | 3 + src/homeagent/config.py | 10 + src/homeagent/mcp/auth.py | 44 ++ tests/test_attachments.py | 700 ++++++++++++++++++++++++++++ tests/test_mcp_connectors.py | 37 ++ 14 files changed, 2157 insertions(+), 51 deletions(-) create mode 100644 src/homeagent/agent/attachments.py create mode 100644 src/homeagent/bot/media.py create mode 100644 tests/test_attachments.py diff --git a/src/homeagent/agent/antigravity.py b/src/homeagent/agent/antigravity.py index 61241d8..2f3333b 100644 --- a/src/homeagent/agent/antigravity.py +++ b/src/homeagent/agent/antigravity.py @@ -13,6 +13,12 @@ from datetime import datetime from pathlib import Path from typing import Any, Awaitable, Callable, Optional +from homeagent.agent.attachments import ( + Attachment, + build_history_user_text, + format_inline_text_attachments, + stage_attachments_in_sandbox, +) from homeagent.agent.base import BaseAgent from homeagent.agent.conversation import ConversationManager from homeagent.agent.mcp_bridge import MCPToolBridge @@ -277,7 +283,8 @@ class AntigravityAgent(BaseAgent): "- Используй ТОЛЬКО инструменты HomeAgent (префикс `mcp_homeagent_*`), подключенные через MCP " "(календарь, Jira, Todoist, Gitea, память, заметки, веб-поиск, песочница, подагенты и подключённые внешние MCP-коннекторы).\n" "- Не пытайся запускать локальные команды или читать/редактировать файлы хоста напрямую — " - "для вычислений и кода используй инструменты песочницы HomeAgent (`code_execute`, `sandbox_*`).\n" + "для вычислений и кода используй инструменты песочницы HomeAgent (`code_execute`, `sandbox_*`), " + "а для просмотра прикреплённых пользователем изображений, PDF, аудио и видео используй инструмент `mcp_homeagent_inspect_attachment`.\n" "- Отвечай пользователю напрямую на его языке (обычно русском), красиво форматируя ответ в Markdown.\n" ) agent_file = self._workspace_dir / ".agents" / "agents" / self.AGENT_NAME / "agent.md" @@ -305,6 +312,7 @@ class AntigravityAgent(BaseAgent): user_message: str, *, prior_history: Optional[list[dict[str, Any]]] = None, + attachments: Optional[list[Attachment]] = None, ) -> str: now = datetime.now() dt_context = ( @@ -319,6 +327,43 @@ class AntigravityAgent(BaseAgent): history_block = self._format_prior_history_context(prior_history) if history_block: parts.append(history_block) + + if attachments: + inline_text, binary_attachments = format_inline_text_attachments(attachments) + if inline_text: + parts.append(inline_text) + + inspectable_lines: list[str] = [] + other_binary_lines: list[str] = [] + for att in binary_attachments: + if att.is_raster_image or att.is_pdf or att.is_audio or att.is_video: + inspectable_lines.append( + f"- ID: `{att.attachment_id}` | {att.to_summary_line()}" + ) + else: + sandbox_hint = ( + f" (доступен в песочнице по пути `{att.sandbox_path}`)" + if att.sandbox_path + else "" + ) + other_binary_lines.append( + f"- ID: `{att.attachment_id}` | {att.to_summary_line()}{sandbox_hint}" + ) + + if inspectable_lines: + parts.append( + "[ВЛОЖЕНИЯ ПОЛЬЗОВАТЕЛЯ]:\n" + + "\n".join(inspectable_lines) + + "\nОБЯЗАТЕЛЬНО вызови инструмент `mcp_homeagent_inspect_attachment(attachment_id=...)` " + "для каждого указанного ID, чтобы просмотреть/прочитать вложение перед формированием ответа!" + ) + if other_binary_lines: + parts.append( + "[БИНАРНЫЕ ФАЙЛЫ ПОЛЬЗОВАТЕЛЯ]:\n" + + "\n".join(other_binary_lines) + + "\nДля анализа или обработки этих файлов используй инструменты песочницы (`code_execute`, `sandbox_run_command`)." + ) + parts.append(user_message) return "\n\n".join(parts) @@ -488,6 +533,7 @@ class AntigravityAgent(BaseAgent): user_message: str, max_tool_iterations: int = 8, on_progress: Optional[Callable[[str], Awaitable[None]]] = None, + attachments: Optional[list[Attachment]] = None, ) -> str: """Process a user message within the topic context via Antigravity CLI.""" del max_tool_iterations # Managed internally by Antigravity CLI turn execution @@ -502,6 +548,10 @@ class AntigravityAgent(BaseAgent): lock = self._get_topic_lock(chat_id, thread_id) async with lock: + staged_attachments = stage_attachments_in_sandbox(attachments, self.settings) + if staged_attachments: + self._bridge.register_attachments(staged_attachments) + await self._bridge.ensure_started() self._prepare_workspace() @@ -518,7 +568,11 @@ class AntigravityAgent(BaseAgent): saved_cid = None prior_history = existing_history if (existing_history and not saved_cid) else None - prompt = self._build_turn_prompt(user_message, prior_history=prior_history) + prompt = self._build_turn_prompt( + user_message, + prior_history=prior_history, + attachments=staged_attachments, + ) response_text, new_cid, error_text = await self._invoke_cli( binary, @@ -536,7 +590,11 @@ class AntigravityAgent(BaseAgent): topic_key, ) self._clear_conversation_id(chat_id, thread_id) - retry_prompt = self._build_turn_prompt(user_message, prior_history=existing_history or None) + retry_prompt = self._build_turn_prompt( + user_message, + prior_history=existing_history or None, + attachments=staged_attachments, + ) response_text, new_cid, error_text = await self._invoke_cli( binary, retry_prompt, @@ -556,7 +614,7 @@ class AntigravityAgent(BaseAgent): chat_id, thread_id, [ - {"role": "user", "content": user_message}, + {"role": "user", "content": build_history_user_text(user_message, staged_attachments)}, {"role": "assistant", "content": response_text}, ], ) diff --git a/src/homeagent/agent/attachments.py b/src/homeagent/agent/attachments.py new file mode 100644 index 0000000..bf3625f --- /dev/null +++ b/src/homeagent/agent/attachments.py @@ -0,0 +1,602 @@ +"""Multimodal attachment representation, text extraction, and sandbox staging for HomeAgent.""" + +from __future__ import annotations + +import base64 +import io +import logging +import mimetypes +import re +import uuid +import xml.etree.ElementTree as ET +import zipfile +from dataclasses import dataclass, field, replace +from pathlib import Path +from typing import TYPE_CHECKING, Optional + +if TYPE_CHECKING: + from homeagent.config import Settings + +logger = logging.getLogger(__name__) + +# Raster image MIME types natively supported by multimodal LLMs (Gemini, OpenAI, Antigravity) +RASTER_IMAGE_MIMES = frozenset( + { + "image/jpeg", + "image/png", + "image/webp", + "image/gif", + "image/bmp", + "image/heic", + "image/heif", + } +) + +# OpenAI Chat Completions image_url supported MIME types +OPENAI_IMAGE_MIMES = frozenset( + { + "image/jpeg", + "image/png", + "image/webp", + "image/gif", + } +) + +TEXT_MIMES = frozenset( + { + "application/json", + "application/xml", + "application/javascript", + "application/x-javascript", + "application/typescript", + "application/x-yaml", + "application/yaml", + "application/toml", + "application/x-sh", + "application/x-shellscript", + "application/sql", + "application/x-python-code", + "application/xhtml+xml", + "application/csv", + "image/svg+xml", + } +) + +TEXT_EXTENSIONS = frozenset( + { + ".txt", + ".md", + ".markdown", + ".rst", + ".py", + ".pyi", + ".js", + ".mjs", + ".cjs", + ".ts", + ".tsx", + ".jsx", + ".json", + ".jsonl", + ".ndjson", + ".yaml", + ".yml", + ".toml", + ".ini", + ".cfg", + ".conf", + ".env", + ".csv", + ".tsv", + ".log", + ".xml", + ".html", + ".htm", + ".css", + ".scss", + ".sass", + ".less", + ".sql", + ".sh", + ".bash", + ".zsh", + ".fish", + ".ps1", + ".bat", + ".go", + ".rs", + ".java", + ".kt", + ".kts", + ".scala", + ".c", + ".h", + ".cpp", + ".hpp", + ".cc", + ".cs", + ".rb", + ".php", + ".swift", + ".m", + ".r", + ".lua", + ".pl", + ".ex", + ".exs", + ".erl", + ".hs", + ".clj", + ".dart", + ".vue", + ".svelte", + ".graphql", + ".gql", + ".proto", + ".tf", + ".hcl", + ".diff", + ".patch", + ".svg", + ".dockerfile", + ".gitignore", + ".dockerignore", + ".editorconfig", + } +) + +TEXT_FILENAMES = frozenset( + { + "dockerfile", + "makefile", + "cmakelists.txt", + "readme", + "license", + "procfile", + "gemfile", + "rakefile", + "justfile", + "vagrantfile", + } +) + +OFFICE_EXTENSIONS = frozenset({".docx", ".xlsx", ".pptx", ".odt", ".ods"}) + +OFFICE_MIMES = frozenset( + { + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "application/vnd.oasis.opendocument.text", + "application/vnd.oasis.opendocument.spreadsheet", + } +) + +_MAX_OFFICE_XML_MEMBER_BYTES = 10 * 1024 * 1024 # 10 MiB safety cap per zip member +_MAX_TEXT_HEURISTIC_BYTES = 5 * 1024 * 1024 # 5 MiB cap for unknown octet-stream sniffing + + +def sniff_mime_from_bytes(data: bytes) -> Optional[str]: + """Detect common binary MIME types from magic bytes.""" + if not data: + return None + if data.startswith(b"\x89PNG\r\n\x1a\n"): + return "image/png" + if data.startswith(b"\xff\xd8\xff"): + return "image/jpeg" + if data.startswith((b"GIF87a", b"GIF89a")): + return "image/gif" + if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP": + return "image/webp" + if data.startswith(b"BM"): + return "image/bmp" + if data.startswith(b"%PDF-"): + return "application/pdf" + if data.startswith(b"OggS"): + return "audio/ogg" + if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WAVE": + return "audio/wav" + if data.startswith(b"fLaC"): + return "audio/flac" + if data.startswith(b"ID3") or (len(data) >= 2 and data[0] == 0xFF and (data[1] & 0xE0) == 0xE0): + return "audio/mpeg" + return None + + +def normalize_mime_type( + filename: str, + mime_type: Optional[str], + *, + data: Optional[bytes] = None, + default: str = "application/octet-stream", +) -> str: + """Resolve and normalize a file's MIME type using magic bytes, header, and filename.""" + cleaned = (mime_type or "").split(";", 1)[0].strip().lower() + if cleaned == "image/jpg": + cleaned = "image/jpeg" + if cleaned == "audio/mp3": + cleaned = "audio/mpeg" + + sniffed = sniff_mime_from_bytes(data) if data else None + + # Trust definitive magic bytes when MIME is missing/generic or mismatched image subtype + if sniffed: + if not cleaned or cleaned == "application/octet-stream": + return sniffed + if cleaned.startswith("image/") and sniffed.startswith("image/"): + return sniffed + + if cleaned and cleaned != "application/octet-stream": + return cleaned + + if filename: + guessed, _ = mimetypes.guess_type(filename) + if guessed: + guessed_clean = guessed.lower() + if guessed_clean == "image/jpg": + guessed_clean = "image/jpeg" + if guessed_clean != "application/octet-stream": + return guessed_clean + + return cleaned or default + + +def format_size(num_bytes: int) -> str: + """Format byte size into a compact human-readable Russian string.""" + if num_bytes < 1024: + return f"{num_bytes} Б" + if num_bytes < 1024 * 1024: + return f"{num_bytes / 1024:.1f} КБ" + return f"{num_bytes / (1024 * 1024):.1f} МБ" + + +def _decode_text_bytes(data: bytes) -> Optional[str]: + """Decode text bytes trying UTF-8 first, then charset_normalizer if installed.""" + if b"\x00" in data[:8192]: + return None + try: + return data.decode("utf-8-sig") + except UnicodeDecodeError: + pass + try: + from charset_normalizer import from_bytes + + best = from_bytes(data).best() + if best is not None: + return str(best) + except Exception: + pass + try: + return data.decode("cp1251") + except UnicodeDecodeError: + return None + + +def _extract_docx_text(zf: zipfile.ZipFile) -> str: + if "word/document.xml" not in zf.namelist(): + return "" + info = zf.getinfo("word/document.xml") + if info.file_size > _MAX_OFFICE_XML_MEMBER_BYTES: + return "" + root = ET.fromstring(zf.read(info)) + paragraphs: list[str] = [] + for elem in root.iter(): + if elem.tag.endswith("}p"): + texts = [t.text for t in elem.iter() if t.tag.endswith("}t") and t.text] + if texts: + paragraphs.append("".join(texts)) + return "\n".join(paragraphs) + + +def _extract_xlsx_text(zf: zipfile.ZipFile, max_rows_per_sheet: int = 200) -> str: + shared_strings: list[str] = [] + if "xl/sharedStrings.xml" in zf.namelist(): + info = zf.getinfo("xl/sharedStrings.xml") + if info.file_size <= _MAX_OFFICE_XML_MEMBER_BYTES: + ss_root = ET.fromstring(zf.read(info)) + for si in ss_root.iter(): + if si.tag.endswith("}si"): + parts = [t.text for t in si.iter() if t.tag.endswith("}t") and t.text] + shared_strings.append("".join(parts)) + + sheet_names = sorted( + name for name in zf.namelist() if name.startswith("xl/worksheets/sheet") and name.endswith(".xml") + ) + sections: list[str] = [] + for sheet_path in sheet_names[:10]: + info = zf.getinfo(sheet_path) + if info.file_size > _MAX_OFFICE_XML_MEMBER_BYTES: + continue + root = ET.fromstring(zf.read(info)) + rows: list[str] = [] + for row in root.iter(): + if not row.tag.endswith("}row"): + continue + cells: list[str] = [] + for cell in row: + if not cell.tag.endswith("}c"): + continue + cell_type = cell.attrib.get("t", "") + val = "" + if cell_type == "inlineStr": + val = "".join(t.text for t in cell.iter() if t.tag.endswith("}t") and t.text) + else: + v_elem = next((ch for ch in cell if ch.tag.endswith("}v")), None) + if v_elem is not None and v_elem.text is not None: + if cell_type == "s": + try: + val = shared_strings[int(v_elem.text)] + except (ValueError, IndexError): + val = v_elem.text + else: + val = v_elem.text + cells.append(val.replace("\t", " ").replace("\n", " ")) + if any(c.strip() for c in cells): + rows.append("\t".join(cells)) + if len(rows) >= max_rows_per_sheet: + rows.append(f"... [показаны первые {max_rows_per_sheet} строк]") + break + if rows: + label = Path(sheet_path).stem + sections.append(f"### Лист {label}\n" + "\n".join(rows)) + return "\n\n".join(sections) + + +def _extract_pptx_text(zf: zipfile.ZipFile) -> str: + slide_names = sorted( + name for name in zf.namelist() if name.startswith("ppt/slides/slide") and name.endswith(".xml") + ) + slides: list[str] = [] + for idx, slide_path in enumerate(slide_names[:50], 1): + info = zf.getinfo(slide_path) + if info.file_size > _MAX_OFFICE_XML_MEMBER_BYTES: + continue + root = ET.fromstring(zf.read(info)) + texts = [t.text for t in root.iter() if t.tag.endswith("}t") and t.text] + if texts: + slides.append(f"### Слайд {idx}\n" + " ".join(texts)) + return "\n\n".join(slides) + + +def _extract_odf_text(zf: zipfile.ZipFile) -> str: + if "content.xml" not in zf.namelist(): + return "" + info = zf.getinfo("content.xml") + if info.file_size > _MAX_OFFICE_XML_MEMBER_BYTES: + return "" + root = ET.fromstring(zf.read(info)) + lines: list[str] = [] + for elem in root.iter(): + if elem.tag.endswith(("}p", "}h")): + text = "".join(elem.itertext()).strip() + if text: + lines.append(text) + return "\n".join(lines) + + +def _extract_office_text(data: bytes, ext: str, mime_type: str) -> Optional[str]: + try: + with zipfile.ZipFile(io.BytesIO(data)) as zf: + if ext == ".docx" or "wordprocessingml" in mime_type: + text = _extract_docx_text(zf) + elif ext == ".xlsx" or "spreadsheetml" in mime_type: + text = _extract_xlsx_text(zf) + elif ext == ".pptx" or "presentationml" in mime_type: + text = _extract_pptx_text(zf) + elif ext in (".odt", ".ods") or "opendocument" in mime_type: + text = _extract_odf_text(zf) + else: + return None + return text.strip() or None + except Exception as e: + logger.debug("Failed extracting Office XML text (%s): %s", ext or mime_type, e) + return None + + +@dataclass(frozen=True) +class Attachment: + """In-memory representation of a file or image attached to a Telegram message.""" + + filename: str + mime_type: str + data: bytes + kind: str = "document" # image, document, audio, voice, video, animation, sticker + source: str = "message" # message, reply + attachment_id: str = field(default_factory=lambda: uuid.uuid4().hex[:12]) + sandbox_path: Optional[str] = None + + @property + def size_bytes(self) -> int: + return len(self.data) + + @property + def human_size(self) -> str: + return format_size(self.size_bytes) + + @property + def extension(self) -> str: + return Path(self.filename).suffix.lower() + + @property + def is_raster_image(self) -> bool: + return self.mime_type.lower() in RASTER_IMAGE_MIMES + + @property + def is_pdf(self) -> bool: + return self.mime_type.lower() == "application/pdf" or self.extension == ".pdf" + + @property + def is_audio(self) -> bool: + return self.mime_type.lower().startswith("audio/") + + @property + def is_video(self) -> bool: + return self.mime_type.lower().startswith("video/") + + @property + def is_office_xml(self) -> bool: + return self.extension in OFFICE_EXTENSIONS or self.mime_type.lower() in OFFICE_MIMES + + @property + def is_text(self) -> bool: + mime = self.mime_type.lower() + if mime.startswith("text/") or mime in TEXT_MIMES: + return True + if self.extension in TEXT_EXTENSIONS: + return True + if Path(self.filename).name.lower() in TEXT_FILENAMES: + return True + if mime == "application/octet-stream" and self.size_bytes <= _MAX_TEXT_HEURISTIC_BYTES: + if sniff_mime_from_bytes(self.data) is not None: + return False + return _decode_text_bytes(self.data) is not None + return False + + def base64_data(self) -> str: + return base64.b64encode(self.data).decode("ascii") + + def extract_text(self, max_chars: int = 30000) -> Optional[str]: + """Extract UTF-8 text from plain text, code, config, or Office XML files.""" + text: Optional[str] = None + if self.is_office_xml: + text = _extract_office_text(self.data, self.extension, self.mime_type.lower()) + elif self.is_text: + text = _decode_text_bytes(self.data) + + if text is None: + return None + if max_chars > 0 and len(text) > max_chars: + omitted = len(text) - max_chars + return ( + text[:max_chars] + + f"\n\n... [Текст обрезан: показано {max_chars} из {len(text)} символов, пропущено {omitted}]" + ) + return text + + def to_summary_line(self) -> str: + parts = [f"{self.filename} ({self.mime_type}, {self.human_size})"] + if self.source == "reply": + parts.append("из цитируемого сообщения") + if self.sandbox_path: + parts.append(f"в песочнице: `{self.sandbox_path}`") + return " — ".join(parts) + + +def _sanitize_upload_filename(filename: str, attachment_id: str) -> str: + """Create a safe filesystem filename without directory traversal.""" + base = Path(filename or "file.bin").name + safe = re.sub(r"[^a-zA-Z0-9._-]+", "_", base).strip("._") + if not safe: + safe = "file.bin" + # Keep filename bounded + if len(safe) > 80: + stem = Path(safe).stem[:60] + suffix = Path(safe).suffix[:16] + safe = f"{stem}{suffix}" + return f"{attachment_id[:8]}_{safe}" + + +def stage_attachments_in_sandbox( + attachments: Optional[list[Attachment]], + settings: "Settings", +) -> list[Attachment]: + """Copy incoming attachments into sandbox_workspace/uploads so tools can process them if needed.""" + if not attachments: + return [] + if not getattr(settings, "SANDBOX_ENABLED", False): + return list(attachments) + + uploads_dir = settings.DATA_DIR / "sandbox_workspace" / "uploads" + try: + uploads_dir.mkdir(parents=True, exist_ok=True) + except Exception as e: + logger.warning("Could not create sandbox uploads dir %s: %s", uploads_dir, e) + return list(attachments) + + staged: list[Attachment] = [] + uploads_resolved = uploads_dir.resolve() + for att in attachments: + if att.sandbox_path: + staged.append(att) + continue + safe_name = _sanitize_upload_filename(att.filename, att.attachment_id) + target = (uploads_dir / safe_name).resolve() + if not str(target).startswith(str(uploads_resolved)): + staged.append(att) + continue + try: + target.write_bytes(att.data) + staged.append(replace(att, sandbox_path=f"uploads/{safe_name}")) + except Exception as e: + logger.warning("Failed staging attachment %s into sandbox: %s", att.filename, e) + staged.append(att) + return staged + + +def build_default_attachment_prompt(attachments: list[Attachment]) -> str: + """Generate a helpful default Russian user prompt when media/files are sent without caption.""" + if not attachments: + return "" + if all(a.is_raster_image for a in attachments): + if len(attachments) == 1: + return ( + "Пользователь прикрепил изображение без подписи. " + "Внимательно изучи его, опиши содержимое и ответь по существу " + "(если на изображении есть текст, задача, ошибка или вопрос — разбери их)." + ) + return ( + f"Пользователь прикрепил {len(attachments)} изображений без подписи. " + "Внимательно изучи их, опиши содержимое и ответь по существу." + ) + if all(a.is_audio or a.kind == "voice" for a in attachments): + return ( + "Пользователь отправил голосовое/аудио сообщение без подписи. " + "Прослушай его, разбери содержание и ответь по существу." + ) + if len(attachments) == 1: + return ( + f"Пользователь прикрепил файл `{attachments[0].filename}` без подписи. " + "Изучи его содержимое, сделай структурированное резюме и предложи, чем можешь помочь." + ) + return ( + f"Пользователь прикрепил {len(attachments)} вложений без подписи. " + "Изучи их содержимое, кратко резюмируй ключевую информацию и ответь по существу." + ) + + +def build_history_user_text( + user_message: str, + attachments: Optional[list[Attachment]], +) -> str: + """Build a compact text-only turn representation safe to persist in ConversationManager.""" + if not attachments: + return user_message + summary_lines = [f"- {att.to_summary_line()}" for att in attachments] + header = "[Прикреплённые вложения]:\n" + "\n".join(summary_lines) + if user_message.strip(): + return f"{header}\n\n{user_message}" + return header + + +def format_inline_text_attachments( + attachments: list[Attachment], + *, + max_chars_per_file: int = 30000, +) -> tuple[str, list[Attachment]]: + """Extract readable text/Office files into prompt blocks and return remaining binary attachments.""" + text_blocks: list[str] = [] + remaining_binary: list[Attachment] = [] + + for att in attachments: + extracted = att.extract_text(max_chars=max_chars_per_file) + if extracted is not None: + sandbox_hint = f" | путь в песочнице: `{att.sandbox_path}`" if att.sandbox_path else "" + source_hint = " (из цитируемого сообщения)" if att.source == "reply" else "" + text_blocks.append( + f"[Содержимое файла `{att.filename}` ({att.mime_type}, {att.human_size}){source_hint}{sandbox_hint}]:\n" + f"```\n{extracted}\n```" + ) + else: + remaining_binary.append(att) + + return "\n\n".join(text_blocks), remaining_binary diff --git a/src/homeagent/agent/base.py b/src/homeagent/agent/base.py index 4abc332..0feb5a4 100644 --- a/src/homeagent/agent/base.py +++ b/src/homeagent/agent/base.py @@ -3,6 +3,8 @@ from abc import ABC, abstractmethod from typing import Any, Awaitable, Callable, Optional +from homeagent.agent.attachments import Attachment + class BaseAgent(ABC): """Abstract base class for all LLM agents.""" @@ -15,6 +17,7 @@ class BaseAgent(ABC): user_message: str, max_tool_iterations: int = 8, on_progress: Optional[Callable[[str], Awaitable[None]]] = None, + attachments: Optional[list[Attachment]] = None, ) -> str: """Process user message within chat topic and execute tools as needed. @@ -24,6 +27,7 @@ class BaseAgent(ABC): user_message: Incoming user prompt max_tool_iterations: Safety cap on consecutive tool call loops on_progress: Optional async callback for reporting status updates to the user + attachments: Optional list of downloaded Telegram images/files attached to the turn Returns: Final markdown response text for the user diff --git a/src/homeagent/agent/gemini.py b/src/homeagent/agent/gemini.py index d71a6fb..f2591e2 100644 --- a/src/homeagent/agent/gemini.py +++ b/src/homeagent/agent/gemini.py @@ -7,6 +7,12 @@ from typing import Any, Awaitable, Callable, Optional from google import genai from google.genai import types +from homeagent.agent.attachments import ( + Attachment, + build_history_user_text, + format_inline_text_attachments, + stage_attachments_in_sandbox, +) from homeagent.agent.base import BaseAgent from homeagent.agent.conversation import ConversationManager from homeagent.config import Settings, get_settings @@ -63,6 +69,7 @@ class GeminiAgent(BaseAgent): user_message: str, max_tool_iterations: int = 8, on_progress: Optional[Callable[[str], Awaitable[None]]] = None, + attachments: Optional[list[Attachment]] = None, ) -> str: """Process a user message within the topic context, running tools as requested by Gemini.""" if not self._client: @@ -75,14 +82,50 @@ class GeminiAgent(BaseAgent): # 1. Fetch current conversation history history = list(self.conversation_manager.get_history(chat_id, thread_id)) - # 2. Add current user message - user_content = types.Content( - role="user", - parts=[types.Part.from_text(text=user_message)], - ) + # 2. Stage and build multimodal user message + staged_attachments = stage_attachments_in_sandbox(attachments, self.settings) + user_parts: list[types.Part] = [] + + if staged_attachments: + inline_text, binary_attachments = format_inline_text_attachments(staged_attachments) + text_sections: list[str] = [] + if inline_text: + text_sections.append(inline_text) + + binary_notes: list[str] = [] + for att in binary_attachments: + if att.is_raster_image or att.is_pdf or att.is_audio or att.is_video: + user_parts.append(types.Part.from_bytes(data=att.data, mime_type=att.mime_type)) + binary_notes.append(f"- Прикреплено вложение: {att.to_summary_line()}") + else: + sandbox_hint = ( + f" Файл сохранён в песочнице: `{att.sandbox_path}` (можно обработать через `code_execute`)." + if att.sandbox_path + else "" + ) + binary_notes.append( + f"- Бинарный файл (напрямую не отображается): {att.to_summary_line()}.{sandbox_hint}" + ) + + if binary_notes: + text_sections.append("[Вложения пользователя]:\n" + "\n".join(binary_notes)) + if user_message.strip(): + text_sections.append(user_message) + + combined_text = "\n\n".join(text_sections) or user_message + user_parts.insert(0, types.Part.from_text(text=combined_text)) + else: + user_parts.append(types.Part.from_text(text=user_message)) + + user_content = types.Content(role="user", parts=user_parts) history.append(user_content) - turn_contents: list[types.Content] = [user_content] + # Persist compact text-only turn representation (avoid storing raw base64 blobs in session JSON) + history_user_content = types.Content( + role="user", + parts=[types.Part.from_text(text=build_history_user_text(user_message, staged_attachments))], + ) + turn_contents: list[types.Content] = [history_user_content] system_instruction = self._build_system_instruction() tools_config = self._get_tools_config() diff --git a/src/homeagent/agent/mcp_bridge.py b/src/homeagent/agent/mcp_bridge.py index c8cc7a4..f692971 100644 --- a/src/homeagent/agent/mcp_bridge.py +++ b/src/homeagent/agent/mcp_bridge.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +from collections import OrderedDict import json import logging import os @@ -12,11 +13,13 @@ from typing import Any, Optional from aiohttp import web +from homeagent.agent.attachments import Attachment from homeagent.tools.registry import ToolRegistry logger = logging.getLogger(__name__) EXCLUDED_SUBAGENT_TOOLS = frozenset({"spawn_subagent", "spawn_parallel_subagents"}) +_MAX_STORED_ATTACHMENTS = 32 def normalize_mcp_schema(schema: Any) -> Any: @@ -47,6 +50,7 @@ class MCPToolBridge: SERVER_NAME = "homeagent" SERVER_VERSION = "1.0.0" + ATTACHMENT_TOOL_NAME = "inspect_attachment" def __init__(self, registry: ToolRegistry) -> None: self.registry = registry @@ -55,6 +59,126 @@ class MCPToolBridge: self._site: Optional[web.TCPSite] = None self._port: Optional[int] = None self._start_lock = asyncio.Lock() + self._attachments: OrderedDict[str, Attachment] = OrderedDict() + + def register_attachments(self, attachments: list[Attachment]) -> None: + """Store attachments in memory so Antigravity CLI can inspect them safely via MCP.""" + for att in attachments: + self._attachments[att.attachment_id] = att + self._attachments.move_to_end(att.attachment_id) + while len(self._attachments) > _MAX_STORED_ATTACHMENTS: + self._attachments.popitem(last=False) + + def get_attachment(self, attachment_id: str) -> Optional[Attachment]: + return self._attachments.get(attachment_id) + + def clear_attachments(self) -> None: + self._attachments.clear() + + def _build_attachment_tool_definition(self) -> dict[str, Any]: + return { + "name": self.ATTACHMENT_TOOL_NAME, + "description": ( + "Получить и просмотреть вложение (изображение, скриншот, PDF, аудио, видео или документ), " + "прикреплённое пользователем в Telegram, по его `attachment_id`. " + "Возвращает нативный мультимодальный контент (image/resource/text) без доступа к файловой системе хоста." + ), + "inputSchema": { + "type": "object", + "properties": { + "attachment_id": { + "type": "string", + "description": "Идентификатор вложения из блока [ВЛОЖЕНИЯ ПОЛЬЗОВАТЕЛЯ].", + }, + "max_chars": { + "type": "integer", + "description": "Максимальное число символов для текстовых файлов (по умолчанию 30000).", + }, + }, + "required": ["attachment_id"], + }, + } + + def _handle_inspect_attachment(self, arguments: dict[str, Any]) -> tuple[list[dict[str, Any]], bool]: + attachment_id = str(arguments.get("attachment_id") or "").strip() + if not attachment_id: + return ([{"type": "text", "text": "Ошибка: необходимо указать параметр `attachment_id`."}], True) + + att = self._attachments.get(attachment_id) + if att is None: + available = ", ".join(self._attachments.keys()) or "нет доступных вложений" + return ( + [ + { + "type": "text", + "text": f"Ошибка: вложение с ID '{attachment_id}' не найдено. Доступные ID: {available}.", + } + ], + True, + ) + + raw_max_chars = arguments.get("max_chars", 30000) + try: + max_chars = max(500, min(int(raw_max_chars), 100000)) + except (TypeError, ValueError): + max_chars = 30000 + + if att.is_raster_image: + return ( + [ + {"type": "text", "text": f"Изображение пользователя: {att.to_summary_line()}"}, + { + "type": "image", + "data": att.base64_data(), + "mimeType": att.mime_type, + }, + ], + False, + ) + + if att.is_pdf or att.is_audio or att.is_video: + return ( + [ + {"type": "text", "text": f"Мультимедийный/PDF файл пользователя: {att.to_summary_line()}"}, + { + "type": "resource", + "resource": { + "uri": f"attachment://{att.attachment_id}/{att.filename}", + "mimeType": att.mime_type, + "blob": att.base64_data(), + }, + }, + ], + False, + ) + + extracted = att.extract_text(max_chars=max_chars) + if extracted is not None: + return ( + [ + { + "type": "text", + "text": f"Файл пользователя: {att.to_summary_line()}\n\n{extracted}", + } + ], + False, + ) + + sandbox_hint = ( + f" Файл сохранён в изолированной песочнице по пути `{att.sandbox_path}` — " + "вы можете обработать его через `code_execute` или `sandbox_run_command`." + if att.sandbox_path + else "" + ) + return ( + [ + { + "type": "text", + "text": f"Бинарный файл пользователя: {att.to_summary_line()}.{sandbox_hint}", + } + ], + False, + ) @property def is_running(self) -> bool: @@ -124,6 +248,8 @@ class MCPToolBridge: if subagent and tool_def.name in EXCLUDED_SUBAGENT_TOOLS: continue tools_config[tool_def.name] = {"eager": True} + if not subagent and self._attachments: + tools_config[self.ATTACHMENT_TOOL_NAME] = {"eager": True} return { "mcpServers": { @@ -257,6 +383,8 @@ class MCPToolBridge: "inputSchema": schema, } ) + if not exclude_subagents and self._attachments: + tools_payload.append(self._build_attachment_tool_definition()) return web.json_response( { "jsonrpc": "2.0", @@ -303,6 +431,19 @@ class MCPToolBridge: } ) + if tool_name == self.ATTACHMENT_TOOL_NAME and not exclude_subagents: + content_blocks, is_error = self._handle_inspect_attachment(arguments) + return web.json_response( + { + "jsonrpc": "2.0", + "id": req_id, + "result": { + "content": content_blocks, + "isError": is_error, + }, + } + ) + if self.registry.get(tool_name) is None: return web.json_response( { diff --git a/src/homeagent/agent/openai_agent.py b/src/homeagent/agent/openai_agent.py index bb22084..36b7127 100644 --- a/src/homeagent/agent/openai_agent.py +++ b/src/homeagent/agent/openai_agent.py @@ -8,6 +8,13 @@ from typing import Any, Awaitable, Callable, Optional import openai from openai import AsyncOpenAI +from homeagent.agent.attachments import ( + OPENAI_IMAGE_MIMES, + Attachment, + build_history_user_text, + format_inline_text_attachments, + stage_attachments_in_sandbox, +) from homeagent.agent.base import BaseAgent from homeagent.agent.conversation import ConversationManager from homeagent.config import Settings, get_settings @@ -71,6 +78,93 @@ class OpenAIAgent(BaseAgent): return "\n\n".join(parts) + def _build_user_turn( + self, + user_message: str, + attachments: list[Attachment], + ) -> dict[str, Any]: + """Build an OpenAI/DeepSeek user message payload supporting images, PDFs, audio, and text files.""" + if not attachments: + return {"role": "user", "content": user_message} + + inline_text, binary_attachments = format_inline_text_attachments(attachments) + text_sections: list[str] = [] + if inline_text: + text_sections.append(inline_text) + + multimodal_blocks: list[dict[str, Any]] = [] + notes: list[str] = [] + + if self.provider == "deepseek": + # DeepSeek Chat Completions API is text-only; avoid sending image_url/file blocks that return HTTP 400 + for att in binary_attachments: + sandbox_hint = ( + f" Файл сохранён в песочнице: `{att.sandbox_path}` — при необходимости можно обработать его через `code_execute`." + if att.sandbox_path + else "" + ) + notes.append( + f"- Бинарное вложение {att.to_summary_line()} (активный провайдер DeepSeek текстовый и не принимает " + f"изображения/PDF/аудио напрямую; для анализа картинок переключитесь на Gemini, OpenAI или Antigravity).{sandbox_hint}" + ) + else: + for att in binary_attachments: + mime = att.mime_type.lower() + if mime in OPENAI_IMAGE_MIMES: + multimodal_blocks.append( + { + "type": "image_url", + "image_url": {"url": f"data:{mime};base64,{att.base64_data()}"}, + } + ) + notes.append(f"- Прикреплено изображение: {att.to_summary_line()}") + elif att.is_pdf: + multimodal_blocks.append( + { + "type": "file", + "file": { + "filename": att.filename, + "file_data": f"data:application/pdf;base64,{att.base64_data()}", + }, + } + ) + notes.append(f"- Прикреплён PDF-документ: {att.to_summary_line()}") + elif mime in ("audio/wav", "audio/x-wav", "audio/mpeg", "audio/mp3"): + audio_fmt = "wav" if "wav" in mime else "mp3" + multimodal_blocks.append( + { + "type": "input_audio", + "input_audio": { + "data": att.base64_data(), + "format": audio_fmt, + }, + } + ) + notes.append(f"- Прикреплено аудио: {att.to_summary_line()}") + else: + sandbox_hint = ( + f" Файл сохранён в песочнице: `{att.sandbox_path}` (можно обработать через `code_execute`)." + if att.sandbox_path + else "" + ) + notes.append( + f"- Вложение `{att.filename}` ({att.mime_type}, {att.human_size}) не поддерживается напрямую " + f"форматом OpenAI Chat Completions.{sandbox_hint}" + ) + + if notes: + text_sections.append("[Вложения пользователя]:\n" + "\n".join(notes)) + if user_message.strip(): + text_sections.append(user_message) + + combined_text = "\n\n".join(text_sections) or user_message + if multimodal_blocks: + return { + "role": "user", + "content": [{"type": "text", "text": combined_text}, *multimodal_blocks], + } + return {"role": "user", "content": combined_text} + async def chat( self, chat_id: int, @@ -78,6 +172,7 @@ class OpenAIAgent(BaseAgent): user_message: str, max_tool_iterations: int = 100, on_progress: Optional[Callable[[str], Awaitable[None]]] = None, + attachments: Optional[list[Attachment]] = None, ) -> str: """Process user message within topic context using DeepSeek / OpenAI API.""" if not self._client: @@ -107,8 +202,9 @@ class OpenAIAgent(BaseAgent): # 1. Fetch current conversation history history = list(self.conversation_manager.get_openai_messages(chat_id, thread_id)) - # 2. Add current user message - user_turn: dict[str, Any] = {"role": "user", "content": user_message} + # 2. Stage attachments and build current user message + staged_attachments = stage_attachments_in_sandbox(attachments, self.settings) + user_turn = self._build_user_turn(user_message, staged_attachments) history.append(user_turn) system_instruction = self._build_system_instruction() @@ -117,7 +213,12 @@ class OpenAIAgent(BaseAgent): *history, ] - turn_sequence: list[dict[str, Any]] = [user_turn] + # Persist compact text-only turn representation (avoid storing megabyte base64 payloads in session JSON) + history_user_turn: dict[str, Any] = { + "role": "user", + "content": build_history_user_text(user_message, staged_attachments), + } + turn_sequence: list[dict[str, Any]] = [history_user_turn] tools = self.registry.get_openai_tools() for iteration in range(max_tool_iterations): diff --git a/src/homeagent/bot/handlers.py b/src/homeagent/bot/handlers.py index c31f333..19d8ed3 100644 --- a/src/homeagent/bot/handlers.py +++ b/src/homeagent/bot/handlers.py @@ -18,8 +18,10 @@ from aiogram.types import ( Message, ) +from homeagent.agent.attachments import Attachment, build_default_attachment_prompt from homeagent.agent.base import BaseAgent from homeagent.bot.mcp_handlers import MCPBotController +from homeagent.bot.media import MediaGroupBuffer, extract_message_attachments, has_supported_media from homeagent.bot.progress import ProgressReporter from homeagent.bot.utils import split_message from homeagent.config import Settings @@ -57,6 +59,7 @@ def create_bot_router( """Create and configure the main Aiogram Router.""" router = Router(name="main_router") mcp_controller = MCPBotController(mcp_manager, _send_reply) if mcp_manager is not None else None + media_group_buffer = MediaGroupBuffer() @router.message(Command("start", "help")) async def handle_start(message: Message) -> None: @@ -89,7 +92,8 @@ def create_bot_router( f"• `/reset` — очистить контекст диалога в текущем топике\n" f"• `/help` — показать это сообщение\n\n" f"Просто напиши мне любой вопрос или команду, например:\n" - f"_«Какие у меня созвоны на сегодня?»_ или _«Сделай утренний план»_." + f"_«Какие у меня созвоны на сегодня?»_ или _«Сделай утренний план»_.\n" + f"📎 Также можно присылать **фото, скриншоты, PDF, документы (DOCX/XLSX/PPTX), код, логи и аудио/голосовые** — с подписью или без." ) await _send_reply(message, greeting) @@ -196,37 +200,99 @@ def create_bot_router( if mcp_controller is not None and await mcp_controller.handle_wizard_message(message): return - text = message.text or message.caption or "" - if not text.strip(): + grouped_messages = await media_group_buffer.collect(message) + if grouped_messages is None: + return + + text_parts = [ + (m.text or m.caption or "").strip() + for m in grouped_messages + if (m.text or m.caption or "").strip() + ] + text = "\n".join(text_parts) + + reply_msg = message.reply_to_message + has_msg_media = any(has_supported_media(m) for m in grouped_messages) + has_reply_media = bool(reply_msg and has_supported_media(reply_msg)) + has_media = has_msg_media or has_reply_media + + if not text and not has_media: return chat_id = message.chat.id thread_id = message.message_thread_id + active_bot = message.bot - # 1. Check if the message triggers a skill - matched = skill_manager.match_trigger(text) - if matched: - skill, extra_args = matched - prompt_to_run = skill.render(extra_instructions=extra_args) - logger.info("Executing skill '%s' for chat=%d, thread=%s", skill.name, chat_id, thread_id) - else: - prompt_to_run = text + max_size_bytes = max(1, int(settings.MAX_ATTACHMENT_SIZE_MB)) * 1024 * 1024 + max_count = max(1, int(settings.MAX_ATTACHMENTS_PER_MESSAGE)) - # 2. Show typing indicator and dynamic progress message while agent is working + # 1. Show typing indicator and dynamic progress message while downloading / thinking typing_task = asyncio.create_task(_keep_typing(message)) - progress = ProgressReporter(bot=message.bot, chat_id=chat_id, thread_id=thread_id) - await progress.start("⏳ Думаю...") + progress = ProgressReporter(bot=active_bot, chat_id=chat_id, thread_id=thread_id) if active_bot else None + if progress is not None: + await progress.start("📥 Загружаю вложения..." if has_media else "⏳ Думаю...") + attachments: list[Attachment] = [] + warnings: list[str] = [] try: - response_text = await agent.chat( - chat_id=chat_id, - thread_id=thread_id, - user_message=prompt_to_run, - on_progress=progress.update, - ) + if has_msg_media and active_bot is not None: + msg_atts, msg_warns = await extract_message_attachments( + active_bot, + grouped_messages, + max_size_bytes=max_size_bytes, + max_count=max_count, + source="message", + ) + attachments.extend(msg_atts) + warnings.extend(msg_warns) + + if has_reply_media and reply_msg is not None and active_bot is not None and len(attachments) < max_count: + reply_atts, reply_warns = await extract_message_attachments( + active_bot, + [reply_msg], + max_size_bytes=max_size_bytes, + max_count=max_count - len(attachments), + source="reply", + ) + attachments.extend(reply_atts) + warnings.extend(reply_warns) + + if not text and not attachments: + if warnings: + warning_text = "\n".join(f"⚠️ {w}" for w in warnings) + await _send_reply(message, warning_text) + return + + # 2. Check if the message triggers a skill + matched = skill_manager.match_trigger(text) if text else None + if matched: + skill, extra_args = matched + prompt_to_run = skill.render(extra_instructions=extra_args) + logger.info("Executing skill '%s' for chat=%d, thread=%s", skill.name, chat_id, thread_id) + elif text: + prompt_to_run = text + else: + prompt_to_run = build_default_attachment_prompt(attachments) + + if warnings: + prompt_to_run += "\n\n[Предупреждения при загрузке вложений]:\n" + "\n".join( + f"- {w}" for w in warnings + ) + + chat_kwargs: dict[str, object] = { + "chat_id": chat_id, + "thread_id": thread_id, + "user_message": prompt_to_run, + "on_progress": progress.update if progress is not None else None, + } + if attachments: + chat_kwargs["attachments"] = attachments + + response_text = await agent.chat(**chat_kwargs) # type: ignore[arg-type] finally: typing_task.cancel() - await progress.finish() + if progress is not None: + await progress.finish() # 3. Split and send chunks strictly as Rich Messages (up to 32K chars) chunks = split_message(response_text) @@ -381,19 +447,54 @@ def create_bot_router( ) return - # If empty text and no reply context - if not cleaned_text and not reply_context: + # Extract media/file attachments from the guest message and/or replied message + attachments: list[Attachment] = [] + warnings: list[str] = [] + max_size_bytes = max(1, int(settings.MAX_ATTACHMENT_SIZE_MB)) * 1024 * 1024 + max_count = max(1, int(settings.MAX_ATTACHMENTS_PER_MESSAGE)) + + if has_supported_media(message): + msg_atts, msg_warns = await extract_message_attachments( + active_bot, + [message], + max_size_bytes=max_size_bytes, + max_count=max_count, + source="message", + ) + attachments.extend(msg_atts) + warnings.extend(msg_warns) + + if ( + message.reply_to_message + and has_supported_media(message.reply_to_message) + and len(attachments) < max_count + ): + reply_atts, reply_warns = await extract_message_attachments( + active_bot, + [message.reply_to_message], + max_size_bytes=max_size_bytes, + max_count=max_count - len(attachments), + source="reply", + ) + attachments.extend(reply_atts) + warnings.extend(reply_warns) + + # If empty text, no reply context, and no attachments + if not cleaned_text and not reply_context and not attachments: + if warnings: + await _send_guest_reply(active_bot, guest_query_id, "\n".join(f"⚠️ {w}" for w in warnings)) + return bot_tag = f"@{bot_username}" if bot_username else "@bot" welcome_msg = ( f"👋 **Привет! Я персональный AI-ассистент HomeAgent (Ghost Mode).**\n\n" f"Я отвечаю в чатах без необходимости добавления в участники.\n" - f"Напишите `{bot_tag} <вопрос>` или ответьте моим тегом на любое сообщение!" + f"Напишите `{bot_tag} <вопрос>` или ответьте моим тегом на любое сообщение, фото или файл!" ) await _send_guest_reply(active_bot, guest_query_id, welcome_msg) return # 2. Check if the message triggers a skill - matched = skill_manager.match_trigger(cleaned_text) + matched = skill_manager.match_trigger(cleaned_text) if cleaned_text else None if matched: skill, extra_args = matched prompt_to_run = skill.render(extra_instructions=extra_args) @@ -402,24 +503,36 @@ def create_bot_router( if reply_context: if cleaned_text: prompt_to_run = f"{reply_context}[Запрос/вопрос пользователя]:\n{cleaned_text}" + elif attachments: + prompt_to_run = f"{reply_context}{build_default_attachment_prompt(attachments)}" else: prompt_to_run = ( f"{reply_context}\n" f"Пользователь упомянул тебя в ответ на это сообщение без дополнительного текста. " f"Пожалуйста, проанализируй это сообщение, объясни его суть или дай полезный ответ по контексту." ) - else: + elif cleaned_text: prompt_to_run = cleaned_text + else: + prompt_to_run = build_default_attachment_prompt(attachments) + + if warnings: + prompt_to_run += "\n\n[Предупреждения при загрузке вложений]:\n" + "\n".join( + f"- {w}" for w in warnings + ) # 3. Process with AI agent typing_task = asyncio.create_task(_keep_typing(message)) try: - response_text = await agent.chat( - chat_id=chat_id, - thread_id=thread_id, - user_message=prompt_to_run, - on_progress=None, - ) + guest_chat_kwargs: dict[str, object] = { + "chat_id": chat_id, + "thread_id": thread_id, + "user_message": prompt_to_run, + "on_progress": None, + } + if attachments: + guest_chat_kwargs["attachments"] = attachments + response_text = await agent.chat(**guest_chat_kwargs) # type: ignore[arg-type] finally: typing_task.cancel() diff --git a/src/homeagent/bot/mcp_handlers.py b/src/homeagent/bot/mcp_handlers.py index 0df4f89..c2229f6 100644 --- a/src/homeagent/bot/mcp_handlers.py +++ b/src/homeagent/bot/mcp_handlers.py @@ -1285,12 +1285,22 @@ class MCPBotController: val = None if rest.lower() in ("clear", "none", "off", "-") else rest saved = self.manager.set_default_client_metadata_url(val) if saved: - await self.send_reply( - message, - f"✅ Сохранён OAuth Client ID Metadata URL:\n`{saved}`\n\n" - "Теперь для всех MCP-серверов с CIMD (например Zenmoney) ссылка входа будет генерироваться автоматически!", - None, - ) + warnings = await self.manager.auth_manager.validate_cimd_url(saved) + if warnings: + warn_lines = "\n".join(f"⚠️ {w}" for w in warnings) + await self.send_reply( + message, + f"💾 URL сохранён (`{saved}`), но найдены проблемы, из-за которых OAuth-сервер может вернуть `invalid_request`:\n\n" + f"{warn_lines}", + None, + ) + else: + await self.send_reply( + message, + f"✅ Проверен и сохранён OAuth Client ID Metadata URL:\n`{saved}`\n\n" + "Теперь для всех MCP-серверов с CIMD (например Zenmoney) ссылка входа будет генерироваться автоматически!", + None, + ) else: await self.send_reply(message, "🧹 OAuth Client ID Metadata URL очищен.", None) except ValueError as e: diff --git a/src/homeagent/bot/media.py b/src/homeagent/bot/media.py new file mode 100644 index 0000000..d26c0b6 --- /dev/null +++ b/src/homeagent/bot/media.py @@ -0,0 +1,240 @@ +"""Telegram media and file extraction helpers, including album (media_group_id) batching.""" + +from __future__ import annotations + +import asyncio +import io +import logging +from dataclasses import dataclass, field +from typing import Optional + +from aiogram import Bot +from aiogram.types import Message + +from homeagent.agent.attachments import Attachment, format_size, normalize_mime_type + +logger = logging.getLogger(__name__) + + +def has_supported_media(message: Message) -> bool: + """Return True if the Telegram message carries any downloadable image, file, or media.""" + return bool( + message.photo + or message.document + or message.audio + or message.voice + or message.video + or message.video_note + or message.animation + or message.sticker + ) + + +async def _download_file_bytes(bot: Bot, file_id: str) -> bytes: + """Download a Telegram file by file_id into bytes.""" + buf = io.BytesIO() + result = await bot.download(file_id, destination=buf) + data = buf.getvalue() + if data: + return data + if result is not None: + if hasattr(result, "getvalue"): + return result.getvalue() + if hasattr(result, "read"): + return result.read() + return b"" + + +def _describe_media_item(message: Message) -> Optional[tuple[str, str, str, Optional[int], str]]: + """Inspect a Telegram message and return `(file_id, filename, mime_type, file_size, kind)` or None.""" + if message.photo: + largest = message.photo[-1] + uid = getattr(largest, "file_unique_id", None) or "img" + return (largest.file_id, f"photo_{uid}.jpg", "image/jpeg", largest.file_size, "image") + + if message.document: + doc = message.document + uid = getattr(doc, "file_unique_id", None) or "doc" + filename = doc.file_name or f"document_{uid}" + mime_type = doc.mime_type or "application/octet-stream" + kind = "image" if mime_type.lower().startswith("image/") else "document" + return (doc.file_id, filename, mime_type, doc.file_size, kind) + + if message.voice: + voice = message.voice + uid = getattr(voice, "file_unique_id", None) or "voice" + mime_type = voice.mime_type or "audio/ogg" + return (voice.file_id, f"voice_{uid}.ogg", mime_type, voice.file_size, "voice") + + if message.audio: + audio = message.audio + uid = getattr(audio, "file_unique_id", None) or "audio" + filename = audio.file_name or f"audio_{uid}.mp3" + mime_type = audio.mime_type or "audio/mpeg" + return (audio.file_id, filename, mime_type, audio.file_size, "audio") + + if message.video: + video = message.video + uid = getattr(video, "file_unique_id", None) or "video" + filename = video.file_name or f"video_{uid}.mp4" + mime_type = video.mime_type or "video/mp4" + return (video.file_id, filename, mime_type, video.file_size, "video") + + if message.video_note: + vn = message.video_note + uid = getattr(vn, "file_unique_id", None) or "vnote" + return (vn.file_id, f"video_note_{uid}.mp4", "video/mp4", vn.file_size, "video") + + if message.animation: + anim = message.animation + uid = getattr(anim, "file_unique_id", None) or "anim" + filename = anim.file_name or f"animation_{uid}.mp4" + mime_type = anim.mime_type or "video/mp4" + return (anim.file_id, filename, mime_type, anim.file_size, "animation") + + if message.sticker: + sticker = message.sticker + uid = getattr(sticker, "file_unique_id", None) or "sticker" + if getattr(sticker, "is_animated", False): + # Lottie .tgs sticker is gzipped JSON vector animation — skip cleanly via caller warning + return (sticker.file_id, f"sticker_{uid}.tgs", "application/x-tgsticker", sticker.file_size, "sticker_animated") + if getattr(sticker, "is_video", False): + return (sticker.file_id, f"sticker_{uid}.webm", "video/webm", sticker.file_size, "sticker") + return (sticker.file_id, f"sticker_{uid}.webp", "image/webp", sticker.file_size, "sticker") + + return None + + +async def extract_message_attachments( + bot: Optional[Bot], + messages: list[Message], + *, + max_size_bytes: int = 20 * 1024 * 1024, + max_count: int = 10, + source: str = "message", +) -> tuple[list[Attachment], list[str]]: + """Download supported attachments from one or more Telegram messages. + + Returns `(attachments, warnings)`. + """ + attachments: list[Attachment] = [] + warnings: list[str] = [] + + if bot is None: + return attachments, warnings + + for msg in messages: + info = _describe_media_item(msg) + if info is None: + continue + + file_id, filename, raw_mime, file_size, kind = info + if kind == "sticker_animated": + warnings.append("Анимированные стикеры (.tgs) не поддерживаются для анализа.") + continue + + if len(attachments) >= max_count: + warnings.append( + f"Достигнут лимит вложений ({max_count} файлов на сообщение): `{filename}` пропущен." + ) + continue + + if file_size is not None and file_size > max_size_bytes: + warnings.append( + f"Файл `{filename}` слишком большой ({format_size(file_size)}). " + f"Максимальный размер — {format_size(max_size_bytes)}." + ) + continue + + try: + data = await _download_file_bytes(bot, file_id) + except Exception as e: + logger.warning("Failed downloading Telegram attachment '%s' (%s): %s", filename, file_id, e) + err_msg = str(e) + if "file is too big" in err_msg.lower(): + warnings.append( + f"Файл `{filename}` превышает лимит Telegram Bot API (20 МБ) и не может быть скачан." + ) + else: + warnings.append(f"Не удалось скачать вложение `{filename}`: {err_msg}") + continue + + if not data: + warnings.append(f"Вложение `{filename}` оказалось пустым (0 байт).") + continue + + if len(data) > max_size_bytes: + warnings.append( + f"Файл `{filename}` слишком большой ({format_size(len(data))}). " + f"Максимальный размер — {format_size(max_size_bytes)}." + ) + continue + + normalized_mime = normalize_mime_type(filename, raw_mime, data=data) + resolved_kind = "image" if normalized_mime.startswith("image/") and kind == "document" else kind + attachments.append( + Attachment( + filename=filename, + mime_type=normalized_mime, + data=data, + kind=resolved_kind, + source=source, + ) + ) + + return attachments, warnings + + +@dataclass +class _MediaGroupState: + messages: list[Message] = field(default_factory=list) + last_arrival: float = 0.0 + first_arrival: float = 0.0 + + +class MediaGroupBuffer: + """Debounces Telegram album updates sharing the same `media_group_id` into one batch.""" + + def __init__(self, delay_seconds: float = 0.6, max_wait_seconds: float = 2.5) -> None: + self.delay_seconds = delay_seconds + self.max_wait_seconds = max_wait_seconds + self._groups: dict[tuple[int, Optional[int], str], _MediaGroupState] = {} + + async def collect(self, message: Message) -> Optional[list[Message]]: + """Collect messages belonging to a media group. + + - If `message.media_group_id` is None, returns `[message]` immediately. + - For a media group, the first arriving coroutine waits until arrivals settle and + returns all collected messages sorted by `message_id`. Subsequent arrivals in the + same group append to the batch and return `None`. + """ + group_id = getattr(message, "media_group_id", None) + if not group_id: + return [message] + + loop = asyncio.get_running_loop() + now = loop.time() + key = (message.chat.id, message.message_thread_id, str(group_id)) + + existing = self._groups.get(key) + if existing is not None: + existing.messages.append(message) + existing.last_arrival = now + return None + + state = _MediaGroupState(messages=[message], last_arrival=now, first_arrival=now) + self._groups[key] = state + + try: + while True: + now = loop.time() + since_last = now - state.last_arrival + since_first = now - state.first_arrival + if since_last >= self.delay_seconds or since_first >= self.max_wait_seconds: + break + sleep_for = min(self.delay_seconds - since_last, self.max_wait_seconds - since_first) + await asyncio.sleep(max(0.01, sleep_for)) + finally: + self._groups.pop(key, None) + + return sorted(state.messages, key=lambda m: m.message_id) diff --git a/src/homeagent/bot/progress.py b/src/homeagent/bot/progress.py index cdd0fcb..b79e756 100644 --- a/src/homeagent/bot/progress.py +++ b/src/homeagent/bot/progress.py @@ -43,6 +43,9 @@ def format_tool_progress(name: str, args: dict[str, Any]) -> str: if name == "sandbox_reset": return "🧹 Очищаю рабочую песочницу..." + if name == "inspect_attachment": + return "📎 Изучаю прикреплённый файл..." + if name == "calendar_today_schedule": return "📅 Проверяю расписание на сегодня..." diff --git a/src/homeagent/config.py b/src/homeagent/config.py index e7f03f3..320fdc2 100644 --- a/src/homeagent/config.py +++ b/src/homeagent/config.py @@ -26,6 +26,14 @@ class Settings(BaseSettings): default=True, description="Enable or disable Ghost/Guest Bot mode (Telegram Bot API 10.0+ guest_message). Allows responding in chats without being added as a member.", ) + MAX_ATTACHMENT_SIZE_MB: int = Field( + default=20, + description="Maximum size in MB for incoming Telegram image/file attachments (Telegram Bot API limit is 20 MB).", + ) + MAX_ATTACHMENTS_PER_MESSAGE: int = Field( + default=10, + description="Maximum number of attachments accepted in a single turn (including Telegram media groups).", + ) # LLM Provider selection: 'gemini', 'deepseek', 'openai', or 'antigravity' LLM_PROVIDER: Literal["gemini", "deepseek", "openai", "antigravity"] = Field( @@ -112,6 +120,8 @@ class Settings(BaseSettings): "искать актуальную информацию в интернете (web_search, web_fetch_page), безопасно выполнять код и вычисления в песочнице (code_execute, sandbox_run_command), " "подключать внешние MCP-серверы (mcp_connect, mcp_provide_auth, mcp_list_connectors, mcp_disconnect, mcp_remove_connector), " "помнить важные факты и выполнять специализированные скиллы. " + "Ты также умеешь анализировать прикреплённые пользователем изображения, скриншоты, PDF, голосовые/аудио, документы (DOCX/XLSX/PPTX) и текстовые/исходные файлы; " + "при необходимости сложной обработки данных из файлов используй инструменты песочницы (`code_execute`, `sandbox_run_command`) с сохранёнными путями в `uploads/`. " "ВАЖНО: если пользователь просит подключить, добавить, настроить или авторизовать MCP-сервер (даёт URL, команду или JSON), " "ВСЕГДА вызывай встроенный инструмент `mcp_connect` (и `mcp_provide_auth` для передачи токена, ключа, client_id или OAuth-ссылки), " "и НЕ пытайся открывать MCP URL через `web_fetch_page` или искать инструкцию в `web_search`. " diff --git a/src/homeagent/mcp/auth.py b/src/homeagent/mcp/auth.py index b5cd5c2..7fcbaf8 100644 --- a/src/homeagent/mcp/auth.py +++ b/src/homeagent/mcp/auth.py @@ -662,6 +662,50 @@ class MCPAuthManager: return authorize_url, pending + async def validate_cimd_url(self, client_metadata_url: str) -> list[str]: + """Validate an HTTPS OAuth Client ID Metadata Document URL and return a list of warnings (empty = valid).""" + warnings: list[str] = [] + try: + async with httpx.AsyncClient( + timeout=10.0, + follow_redirects=True, + trust_env=not is_loopback_url(client_metadata_url), + ) as client: + resp = await client.get(client_metadata_url, headers={"Accept": "application/json"}) + except Exception as e: + return [f"Не удалось загрузить `{client_metadata_url}`: {e}"] + + if resp.status_code != 200: + return [f"Сервер вернул HTTP {resp.status_code} вместо 200 OK."] + + ctype = (resp.headers.get("content-type") or "").lower() + if "application/json" not in ctype: + warnings.append( + f"Сервер отдал `Content-Type: {resp.headers.get('content-type', 'missing')}` вместо `application/json` — " + "строгие OAuth-серверы (например Zenmoney) отклоняют такой файл с `invalid_request` " + "(Gitea/GitHub `/raw/` всегда отдают `text/plain`; отдавайте файл через nginx / GitHub Pages / static host с `application/json`)." + ) + + try: + doc = resp.json() + except Exception as e: + warnings.append(f"Некорректный JSON: {e}") + return warnings + + if not isinstance(doc, dict): + warnings.append("Документ должен быть JSON-объектом.") + return warnings + + if doc.get("client_id") != client_metadata_url: + warnings.append( + f"Поле `client_id` в JSON (`{doc.get('client_id')}`) должно точно совпадать с URL (`{client_metadata_url}`)." + ) + uris = doc.get("redirect_uris") + if not isinstance(uris, list) or not uris: + warnings.append("В JSON отсутствует непустой массив `redirect_uris`.") + + return warnings + async def _resolve_cimd_redirect_uri( self, client_metadata_url: str, diff --git a/tests/test_attachments.py b/tests/test_attachments.py new file mode 100644 index 0000000..e0d34c1 --- /dev/null +++ b/tests/test_attachments.py @@ -0,0 +1,700 @@ +"""Unit tests for multimodal image and file attachments across Telegram handlers and all LLM agents.""" + +from __future__ import annotations + +import asyncio +import base64 +from datetime import datetime +import io +import json +import struct +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch +import zipfile +import zlib + +import httpx +import pytest +from aiogram import Bot, Dispatcher +from aiogram.types import Chat, Document, Message, PhotoSize, Sticker, Update, User, Voice + +from homeagent.agent.antigravity import AntigravityAgent +from homeagent.agent.attachments import ( + Attachment, + build_default_attachment_prompt, + build_history_user_text, + normalize_mime_type, + stage_attachments_in_sandbox, +) +from homeagent.agent.conversation import ConversationManager +from homeagent.agent.gemini import GeminiAgent +from homeagent.agent.mcp_bridge import MCPToolBridge +from homeagent.agent.openai_agent import OpenAIAgent +from homeagent.bot.handlers import create_bot_router +from homeagent.bot.media import MediaGroupBuffer, extract_message_attachments +from homeagent.bot.progress import format_tool_progress +from homeagent.config import Settings +from homeagent.skills.manager import SkillManager +from homeagent.tools.registry import ToolRegistry + + +def _make_png(w: int = 4, h: int = 4, rgb: tuple[int, int, int] = (255, 0, 0)) -> bytes: + raw = b"".join(b"\x00" + bytes(rgb) * w for _ in range(h)) + + def _chunk(tag: bytes, data: bytes) -> bytes: + return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF) + + return ( + b"\x89PNG\r\n\x1a\n" + + _chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + + _chunk(b"IDAT", zlib.compress(raw)) + + _chunk(b"IEND", b"") + ) + + +def _make_docx(paragraphs: list[str]) -> bytes: + buf = io.BytesIO() + body = "".join(f"{p}" for p in paragraphs) + xml = ( + '' + '' + f"{body}" + ) + with zipfile.ZipFile(buf, "w") as zf: + zf.writestr("word/document.xml", xml) + return buf.getvalue() + + +def _make_xlsx() -> bytes: + buf = io.BytesIO() + shared = ( + '' + '' + "NameScoreAlice" + "" + ) + sheet = ( + '' + '' + '01' + '299' + "" + ) + with zipfile.ZipFile(buf, "w") as zf: + zf.writestr("xl/sharedStrings.xml", shared) + zf.writestr("xl/worksheets/sheet1.xml", sheet) + return buf.getvalue() + + +# ------------------------------------------------------------------------------ +# Attachment model & extraction tests +# ------------------------------------------------------------------------------ + + +def test_attachment_mime_sniffing_and_text_extraction(): + png_bytes = _make_png() + assert normalize_mime_type("file.bin", "application/octet-stream", data=png_bytes) == "image/png" + assert normalize_mime_type("scan.bin", None, data=b"%PDF-1.7\n...") == "application/pdf" + assert normalize_mime_type("script.py", "application/octet-stream", data=b"print(1)\n") in ( + "text/x-python", + "text/plain", + "application/x-python-code", + ) + + py_att = Attachment(filename="script.py", mime_type="text/x-python", data=b"print('hello')\n") + assert py_att.is_text + assert py_att.extract_text() == "print('hello')\n" + + png_att = Attachment(filename="shot.png", mime_type="image/png", data=png_bytes) + assert png_att.is_raster_image + assert not png_att.is_text + assert png_att.extract_text() is None + + docx_att = Attachment( + filename="report.docx", + mime_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document", + data=_make_docx(["Привет мир", "Второй абзац"]), + ) + assert docx_att.is_office_xml + assert docx_att.extract_text() == "Привет мир\nВторой абзац" + + xlsx_att = Attachment( + filename="metrics.xlsx", + mime_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + data=_make_xlsx(), + ) + xlsx_text = xlsx_att.extract_text() + assert xlsx_text is not None + assert "Name\tScore" in xlsx_text + assert "Alice\t99" in xlsx_text + + +def test_stage_attachments_in_sandbox_sanitizes_paths(tmp_path): + settings = Settings(DATA_DIR=tmp_path, SANDBOX_ENABLED=True) + att = Attachment( + filename="../../etc/evil name.csv", + mime_type="text/csv", + data=b"a,b\n1,2\n", + attachment_id="abcdef123456", + ) + staged = stage_attachments_in_sandbox([att], settings) + assert len(staged) == 1 + assert staged[0].sandbox_path is not None + assert staged[0].sandbox_path.startswith("uploads/abcdef12_") + assert ".." not in staged[0].sandbox_path + written = tmp_path / "sandbox_workspace" / staged[0].sandbox_path + assert written.read_bytes() == b"a,b\n1,2\n" + + +def test_default_prompt_and_history_summary(): + img = Attachment(filename="pic.jpg", mime_type="image/jpeg", data=b"\xff\xd8\xff\xe0", kind="image") + assert "изображение" in build_default_attachment_prompt([img]) + summary = build_history_user_text("Что тут?", [img]) + assert "pic.jpg" in summary + assert "Что тут?" in summary + + +# ------------------------------------------------------------------------------ +# Telegram media extraction & MediaGroupBuffer tests +# ------------------------------------------------------------------------------ + + +@pytest.mark.asyncio +async def test_extract_message_attachments_photo_doc_oversize_and_animated_sticker(): + png_bytes = _make_png() + bot = MagicMock(spec=Bot) + + async def fake_download(file_id: str, destination=None, **kwargs): + payload = { + "photo_large": png_bytes, + "doc_txt": b"hello world", + "voice_1": b"OggS\x00\x02data", + }[file_id] + if destination is not None: + destination.write(payload) + return destination + + bot.download = AsyncMock(side_effect=fake_download) + chat = Chat(id=1, type="private") + user = User(id=1, is_bot=False, first_name="U") + + msg_photo = Message( + message_id=1, + date=datetime.now(), + chat=chat, + from_user=user, + photo=[ + PhotoSize(file_id="photo_small", file_unique_id="s1", width=90, height=90, file_size=500), + PhotoSize(file_id="photo_large", file_unique_id="l1", width=800, height=600, file_size=len(png_bytes)), + ], + ) + msg_doc = Message( + message_id=2, + date=datetime.now(), + chat=chat, + from_user=user, + document=Document(file_id="doc_txt", file_unique_id="d1", file_name="notes.txt", mime_type="text/plain", file_size=11), + ) + msg_huge = Message( + message_id=3, + date=datetime.now(), + chat=chat, + from_user=user, + document=Document(file_id="doc_huge", file_unique_id="d2", file_name="huge.zip", file_size=50 * 1024 * 1024), + ) + msg_voice = Message( + message_id=4, + date=datetime.now(), + chat=chat, + from_user=user, + voice=Voice(file_id="voice_1", file_unique_id="v1", duration=3, mime_type="audio/ogg", file_size=10), + ) + msg_tgs = Message( + message_id=5, + date=datetime.now(), + chat=chat, + from_user=user, + sticker=Sticker( + file_id="stk_1", + file_unique_id="st1", + type="regular", + width=512, + height=512, + is_animated=True, + is_video=False, + ), + ) + + atts, warns = await extract_message_attachments( + bot, + [msg_photo, msg_doc, msg_huge, msg_voice, msg_tgs], + max_size_bytes=5 * 1024 * 1024, + ) + assert len(atts) == 3 + assert atts[0].filename == "photo_l1.jpg" + assert atts[0].data == png_bytes + assert atts[1].filename == "notes.txt" + assert atts[2].kind == "voice" + assert atts[2].mime_type == "audio/ogg" + assert len(warns) == 2 + assert any("huge.zip" in w for w in warns) + assert any(".tgs" in w for w in warns) + + +@pytest.mark.asyncio +async def test_media_group_buffer_batches_album(): + buf = MediaGroupBuffer(delay_seconds=0.05, max_wait_seconds=0.5) + chat = Chat(id=10, type="private") + m1 = Message(message_id=101, date=datetime.now(), chat=chat, media_group_id="grp1", caption="Две фотки") + m2 = Message(message_id=102, date=datetime.now(), chat=chat, media_group_id="grp1") + + t1 = asyncio.create_task(buf.collect(m1)) + await asyncio.sleep(0.01) + res2 = await buf.collect(m2) + res1 = await t1 + + assert res2 is None + assert res1 is not None + assert [m.message_id for m in res1] == [101, 102] + + +# ------------------------------------------------------------------------------ +# GeminiAgent multimodal tests +# ------------------------------------------------------------------------------ + + +@pytest.mark.asyncio +async def test_gemini_agent_sends_multimodal_parts_and_persists_compact_history(tmp_path): + settings = Settings(LLM_PROVIDER="gemini", GEMINI_API_KEY="fake-key", DATA_DIR=tmp_path) + cm = ConversationManager(tmp_path) + agent = GeminiAgent(settings=settings, registry=ToolRegistry(), conversation_manager=cm) + + mock_resp = MagicMock() + mock_resp.function_calls = None + mock_resp.text = "На картинке красный квадрат, а в файле число 42." + + mock_client = MagicMock() + mock_client.aio.models.generate_content = AsyncMock(return_value=mock_resp) + agent._client = mock_client + + png_bytes = _make_png() + atts = [ + Attachment(filename="red.png", mime_type="image/png", data=png_bytes, kind="image"), + Attachment(filename="data.txt", mime_type="text/plain", data=b"answer=42", kind="document"), + ] + reply = await agent.chat(chat_id=1, thread_id=None, user_message="Разбери", attachments=atts) + assert "красный квадрат" in reply + + sent_contents = mock_client.aio.models.generate_content.await_args.kwargs["contents"] + user_parts = sent_contents[-1].parts + assert any(getattr(p, "text", None) and "answer=42" in p.text for p in user_parts) + assert any( + getattr(p, "inline_data", None) + and p.inline_data.mime_type == "image/png" + and p.inline_data.data == png_bytes + for p in user_parts + ) + + # Saved session history must NOT contain raw binary bytes, only compact summary + saved_history = cm.get_openai_messages(1, None) + assert len(saved_history) == 2 + assert "red.png" in saved_history[0]["content"] + assert "data.txt" in saved_history[0]["content"] + + +# ------------------------------------------------------------------------------ +# OpenAIAgent & DeepSeek multimodal tests +# ------------------------------------------------------------------------------ + + +@pytest.mark.asyncio +async def test_openai_agent_sends_image_pdf_and_inline_text(tmp_path): + settings = Settings(LLM_PROVIDER="openai", OPENAI_API_KEY="sk-test", OPENAI_MODEL="gpt-4o", DATA_DIR=tmp_path) + cm = ConversationManager(tmp_path) + agent = OpenAIAgent(settings=settings, registry=ToolRegistry(), conversation_manager=cm) + + mock_choice = MagicMock() + mock_choice.message.content = "Вижу фото, PDF и код." + mock_choice.message.tool_calls = None + mock_resp = MagicMock(choices=[mock_choice]) + + mock_client = MagicMock() + mock_client.chat.completions.create = AsyncMock(return_value=mock_resp) + agent._client = mock_client + + png_bytes = _make_png() + pdf_bytes = b"%PDF-1.4\n%%EOF" + atts = [ + Attachment(filename="screen.png", mime_type="image/png", data=png_bytes, kind="image"), + Attachment(filename="doc.pdf", mime_type="application/pdf", data=pdf_bytes, kind="document"), + Attachment(filename="main.py", mime_type="text/x-python", data=b"x = 123", kind="document"), + ] + reply = await agent.chat(chat_id=2, thread_id=5, user_message="Проверь вложения", attachments=atts) + assert reply == "Вижу фото, PDF и код." + + sent_messages = mock_client.chat.completions.create.await_args.kwargs["messages"] + user_content = sent_messages[-1]["content"] + assert isinstance(user_content, list) + block_types = [b["type"] for b in user_content] + assert block_types == ["text", "image_url", "file"] + assert "x = 123" in user_content[0]["text"] + assert user_content[1]["image_url"]["url"].startswith("data:image/png;base64,") + assert user_content[2]["file"]["filename"] == "doc.pdf" + assert user_content[2]["file"]["file_data"].startswith("data:application/pdf;base64,") + + # History persisted as compact string (no base64 data URI) + saved = cm.get_openai_messages(2, 5) + assert isinstance(saved[0]["content"], str) + assert "base64," not in saved[0]["content"] + assert "screen.png" in saved[0]["content"] + + +@pytest.mark.asyncio +async def test_deepseek_agent_inlines_text_and_avoids_image_url_blocks(tmp_path): + settings = Settings(LLM_PROVIDER="deepseek", DEEPSEEK_API_KEY="sk-ds", DATA_DIR=tmp_path) + cm = ConversationManager(tmp_path) + agent = OpenAIAgent(settings=settings, registry=ToolRegistry(), conversation_manager=cm) + + mock_choice = MagicMock() + mock_choice.message.content = "Прочитал текст, картинку посмотреть не могу." + mock_choice.message.tool_calls = None + mock_resp = MagicMock(choices=[mock_choice]) + + mock_client = MagicMock() + mock_client.chat.completions.create = AsyncMock(return_value=mock_resp) + agent._client = mock_client + + atts = [ + Attachment(filename="pic.png", mime_type="image/png", data=_make_png(), kind="image"), + Attachment(filename="log.txt", mime_type="text/plain", data=b"ERROR: boom", kind="document"), + ] + reply = await agent.chat(chat_id=3, thread_id=None, user_message="Что здесь?", attachments=atts) + assert "Прочитал текст" in reply + + sent_messages = mock_client.chat.completions.create.await_args.kwargs["messages"] + user_content = sent_messages[-1]["content"] + assert isinstance(user_content, str) + assert "ERROR: boom" in user_content + assert "DeepSeek текстовый" in user_content + + +# ------------------------------------------------------------------------------ +# MCPToolBridge & AntigravityAgent multimodal tests +# ------------------------------------------------------------------------------ + + +@pytest.mark.asyncio +async def test_mcp_tool_bridge_inspect_attachment_image_pdf_and_text(tmp_path): + bridge = MCPToolBridge(ToolRegistry()) + png_bytes = _make_png() + pdf_bytes = b"%PDF-1.4\n%%EOF" + img = Attachment(filename="shot.png", mime_type="image/png", data=png_bytes, attachment_id="img1") + pdf = Attachment(filename="spec.pdf", mime_type="application/pdf", data=pdf_bytes, attachment_id="pdf1") + txt = Attachment(filename="note.md", mime_type="text/markdown", data=b"# Title\nBody", attachment_id="txt1") + + bridge.register_attachments([img, pdf, txt]) + await bridge.ensure_started() + try: + url = bridge.get_endpoint_url(subagent=False) + sub_url = bridge.get_endpoint_url(subagent=True) + headers = {"Authorization": f"Bearer {bridge.token}"} + + async with httpx.AsyncClient(trust_env=False) as client: + # Main endpoint exposes inspect_attachment; subagent endpoint does not + main_tools = ( + await client.post(url, headers=headers, json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"}) + ).json()["result"]["tools"] + assert any(t["name"] == "inspect_attachment" for t in main_tools) + + sub_tools = ( + await client.post(sub_url, headers=headers, json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"}) + ).json()["result"]["tools"] + assert all(t["name"] != "inspect_attachment" for t in sub_tools) + + # 1. Image returns native MCP image block + img_res = ( + await client.post( + url, + headers=headers, + json={ + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": {"name": "inspect_attachment", "arguments": {"attachment_id": "img1"}}, + }, + ) + ).json()["result"] + assert img_res["isError"] is False + assert img_res["content"][1]["type"] == "image" + assert img_res["content"][1]["mimeType"] == "image/png" + assert base64.b64decode(img_res["content"][1]["data"]) == png_bytes + + # 2. PDF returns native MCP resource blob + pdf_res = ( + await client.post( + url, + headers=headers, + json={ + "jsonrpc": "2.0", + "id": 4, + "method": "tools/call", + "params": {"name": "inspect_attachment", "arguments": {"attachment_id": "pdf1"}}, + }, + ) + ).json()["result"] + assert pdf_res["isError"] is False + assert pdf_res["content"][1]["type"] == "resource" + assert pdf_res["content"][1]["resource"]["mimeType"] == "application/pdf" + assert base64.b64decode(pdf_res["content"][1]["resource"]["blob"]) == pdf_bytes + + # 3. Text returns text content + txt_res = ( + await client.post( + url, + headers=headers, + json={ + "jsonrpc": "2.0", + "id": 5, + "method": "tools/call", + "params": {"name": "inspect_attachment", "arguments": {"attachment_id": "txt1"}}, + }, + ) + ).json()["result"] + assert txt_res["isError"] is False + assert "# Title" in txt_res["content"][0]["text"] + + # mcp_config.json marks inspect_attachment as eager + cfg_path = bridge.write_mcp_config(tmp_path) + cfg = json.loads(cfg_path.read_text(encoding="utf-8")) + assert cfg["mcpServers"]["homeagent"]["tools"]["inspect_attachment"] == {"eager": True} + finally: + await bridge.stop() + + +@pytest.mark.asyncio +async def test_antigravity_agent_chat_with_attachments_keeps_read_file_denied(tmp_path): + settings = Settings(LLM_PROVIDER="antigravity", DATA_DIR=tmp_path) + cm = ConversationManager(tmp_path) + agent = AntigravityAgent(settings=settings, registry=ToolRegistry(), conversation_manager=cm) + + captured_cmd: list[str] = [] + + class _FakeStream: + def __init__(self, lines: list[bytes]) -> None: + self._lines = list(lines) + + async def readline(self) -> bytes: + return self._lines.pop(0) if self._lines else b"" + + async def read(self) -> bytes: + return b"".join(self._lines) + + class _FakeProc: + def __init__(self) -> None: + self.stdout = _FakeStream( + [ + ( + json.dumps( + { + "event": "result", + "result": { + "conversation_id": "conv-att-1", + "status": "SUCCESS", + "response": "На фото зелёный квадрат, конфиг корректный.", + }, + } + ) + + "\n" + ).encode("utf-8") + ] + ) + self.stderr = _FakeStream([]) + self.returncode = 0 + + async def wait(self) -> int: + return 0 + + async def fake_exec(*cmd: str, **kwargs: Any) -> _FakeProc: + captured_cmd.extend(cmd) + return _FakeProc() + + img = Attachment(filename="green.png", mime_type="image/png", data=_make_png(), attachment_id="att999") + cfg_att = Attachment(filename="app.json", mime_type="application/json", data=b'{"ok": true}', attachment_id="att888") + + try: + with ( + patch("homeagent.agent.antigravity._resolve_cli_binary", return_value="/usr/bin/agy"), + patch("asyncio.create_subprocess_exec", side_effect=fake_exec), + ): + res = await agent.chat(chat_id=50, thread_id=None, user_message="Проверь", attachments=[img, cfg_att]) + assert "зелёный квадрат" in res + prompt = captured_cmd[captured_cmd.index("-p") + 1] + assert "mcp_homeagent_inspect_attachment" in prompt + assert "att999" in prompt + assert '{"ok": true}' in prompt + + # Host read_file(*) MUST remain strictly denied + settings_arg = json.loads(captured_cmd[captured_cmd.index("--settings") + 1]) + assert "read_file(*)" in settings_arg["permissions"]["deny"] + assert agent._bridge.get_attachment("att999") is not None + finally: + await agent.close() + + +# ------------------------------------------------------------------------------ +# End-to-end Telegram handler tests (photo, reply, album, ghost mode) +# ------------------------------------------------------------------------------ + + +@pytest.mark.asyncio +async def test_handle_message_photo_without_caption_and_reply_attachment(tmp_path): + settings = Settings(ALLOWED_TELEGRAM_USER_IDS=[111], DATA_DIR=tmp_path) + agent = MagicMock() + agent.chat = AsyncMock(return_value="Это красная картинка!") + router = create_bot_router(settings, agent, SkillManager(tmp_path / "skills"), ToolRegistry()) + dp = Dispatcher() + dp.include_router(router) + + png_bytes = _make_png() + bot = MagicMock(spec=Bot) + bot.send_rich_message = AsyncMock() + bot.send_message = AsyncMock(return_value=MagicMock(edit_text=AsyncMock(), delete=AsyncMock())) + bot.send_chat_action = AsyncMock() + + async def fake_download(file_id: str, destination=None, **kwargs): + if destination is not None: + destination.write(png_bytes) + return destination + + bot.download = AsyncMock(side_effect=fake_download) + + user = User(id=111, is_bot=False, first_name="Owner") + chat = Chat(id=111, type="private") + photo_msg = Message( + message_id=10, + date=datetime.now(), + chat=chat, + from_user=user, + photo=[PhotoSize(file_id="p_1", file_unique_id="u1", width=64, height=64, file_size=len(png_bytes))], + ) + photo_msg._bot = bot + + await dp.feed_update(bot, Update(update_id=1, message=photo_msg)) + + agent.chat.assert_awaited_once() + kwargs = agent.chat.await_args.kwargs + assert "изображение без подписи" in kwargs["user_message"] + assert len(kwargs["attachments"]) == 1 + assert kwargs["attachments"][0].mime_type == "image/png" + assert kwargs["attachments"][0].data == png_bytes + bot.send_rich_message.assert_awaited_once() + + # Now test replying to a photo with a text question + agent.chat.reset_mock() + reply_msg = Message( + message_id=11, + date=datetime.now(), + chat=chat, + from_user=user, + text="Какой здесь цвет?", + reply_to_message=photo_msg, + ) + reply_msg._bot = bot + + await dp.feed_update(bot, Update(update_id=2, message=reply_msg)) + agent.chat.assert_awaited_once() + reply_kwargs = agent.chat.await_args.kwargs + assert reply_kwargs["user_message"] == "Какой здесь цвет?" + assert len(reply_kwargs["attachments"]) == 1 + assert reply_kwargs["attachments"][0].source == "reply" + + +@pytest.mark.asyncio +async def test_handle_message_oversized_document_replies_with_warning(tmp_path): + settings = Settings(ALLOWED_TELEGRAM_USER_IDS=[111], MAX_ATTACHMENT_SIZE_MB=1, DATA_DIR=tmp_path) + agent = MagicMock() + agent.chat = AsyncMock() + router = create_bot_router(settings, agent, SkillManager(tmp_path / "skills"), ToolRegistry()) + dp = Dispatcher() + dp.include_router(router) + + bot = MagicMock(spec=Bot) + bot.send_rich_message = AsyncMock() + bot.send_message = AsyncMock(return_value=MagicMock(edit_text=AsyncMock(), delete=AsyncMock())) + bot.send_chat_action = AsyncMock() + + user = User(id=111, is_bot=False, first_name="Owner") + chat = Chat(id=111, type="private") + huge_msg = Message( + message_id=20, + date=datetime.now(), + chat=chat, + from_user=user, + document=Document(file_id="big", file_unique_id="b1", file_name="video.zip", file_size=5 * 1024 * 1024), + ) + huge_msg._bot = bot + + await dp.feed_update(bot, Update(update_id=3, message=huge_msg)) + agent.chat.assert_not_awaited() + bot.send_rich_message.assert_awaited_once() + sent_md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown + assert "video.zip" in sent_md + assert "слишком большой" in sent_md + + +@pytest.mark.asyncio +async def test_guest_message_with_replied_photo(tmp_path): + settings = Settings(GHOST_MODE_ENABLED=True, ALLOWED_TELEGRAM_USER_IDS=[777], DATA_DIR=tmp_path) + agent = MagicMock() + agent.chat = AsyncMock(return_value="На скриншоте ошибка 502.") + router = create_bot_router(settings, agent, SkillManager(tmp_path / "skills"), ToolRegistry()) + dp = Dispatcher() + dp.include_router(router) + + png_bytes = _make_png() + bot = MagicMock(spec=Bot) + bot.get_me = AsyncMock(return_value=MagicMock(username="homeagent_bot")) + bot.answer_guest_query = AsyncMock() + bot.send_chat_action = AsyncMock() + + async def fake_download(file_id: str, destination=None, **kwargs): + if destination is not None: + destination.write(png_bytes) + return destination + + bot.download = AsyncMock(side_effect=fake_download) + + replied = Message( + message_id=50, + date=datetime.now(), + chat=Chat(id=-100500, type="supergroup"), + from_user=User(id=222, is_bot=False, first_name="Alice"), + photo=[PhotoSize(file_id="gp_1", file_unique_id="gu1", width=320, height=240, file_size=len(png_bytes))], + caption="Смотрите что вылезло", + ) + caller = User(id=777, is_bot=False, first_name="Owner") + guest = Message( + message_id=51, + date=datetime.now(), + chat=Chat(id=-100500, type="supergroup"), + from_user=caller, + reply_to_message=replied, + text="@homeagent_bot что это за ошибка?", + guest_query_id="gq_photo_1", + guest_bot_caller_user=caller, + ) + guest._bot = bot + + await dp.feed_update(bot, Update(update_id=4, guest_message=guest)) + + agent.chat.assert_awaited_once() + kwargs = agent.chat.await_args.kwargs + assert "Смотрите что вылезло" in kwargs["user_message"] + assert "что это за ошибка?" in kwargs["user_message"] + assert len(kwargs["attachments"]) == 1 + assert kwargs["attachments"][0].source == "reply" + bot.answer_guest_query.assert_awaited_once() + + +def test_progress_format_for_inspect_attachment(): + assert "прикреплённый файл" in format_tool_progress("inspect_attachment", {"attachment_id": "abc"}) diff --git a/tests/test_mcp_connectors.py b/tests/test_mcp_connectors.py index 9f0d867..ffa84df 100644 --- a/tests/test_mcp_connectors.py +++ b/tests/test_mcp_connectors.py @@ -779,3 +779,40 @@ async def test_config_loading_yaml_and_env_json_and_stdio_restriction(tmp_path): assert manager2.get_connector("imported") is not None await manager.close() await manager2.close() + + +@pytest.mark.asyncio +async def test_validate_cimd_url_catches_text_plain_and_mismatched_client_id(tmp_path): + async def handle_bad(request: web.Request) -> web.Response: + return web.Response( + text=json.dumps({"client_id": "https://other.example/x.json", "redirect_uris": []}), + content_type="text/plain", + ) + + async def handle_good(request: web.Request) -> web.Response: + url = str(request.url) + return web.json_response( + { + "client_id": url, + "client_name": "HomeAgent", + "redirect_uris": ["http://127.0.0.1:18765/mcp/oauth/callback"], + } + ) + + app = web.Application() + app.router.add_get("/bad.json", handle_bad) + app.router.add_get("/good.json", handle_good) + runner, base_url = await _start_aiohttp_app(app) + try: + store = OAuthTokenStore(tmp_path / "tok.json") + auth_mgr = MCPAuthManager(store) + + bad_warnings = await auth_mgr.validate_cimd_url(f"{base_url}/bad.json") + assert any("application/json" in w for w in bad_warnings) + assert any("client_id" in w for w in bad_warnings) + assert any("redirect_uris" in w for w in bad_warnings) + + good_warnings = await auth_mgr.validate_cimd_url(f"{base_url}/good.json") + assert good_warnings == [] + finally: + await runner.cleanup()