add images support

This commit is contained in:
timka123 committed 2026-11-23 18:19:24 +03:00
1 parent 2b3518f873
commit d972f4b314
14 files changed
+2157 -51

No files matched your search

+62 -4
View File
@@ -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},
],
)
+602
View File
@@ -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
+4
View File
@@ -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
+49 -6
View File
@@ -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()
+141
View File
@@ -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(
{
+104 -3
View File
@@ -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):
+145 -32
View File
@@ -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()
+16 -6
View File
@@ -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:
+240
View File
@@ -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)
+3
View File
@@ -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 "📅 Проверяю расписание на сегодня..."
+10
View File
@@ -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`. "
+44
View File
@@ -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,