The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge simp/r3-30 (late tail) into hermes/simplify-codebase
Teknium8ae52dd93c4c
diff --cc plugins/platforms/telegram/adapter.pyindex 7c2cbeb47f0,f4280bf0455..13d1b6d4a3a--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@@ -177,16 -127,12 +127,12 @@@ sys.path.insert(0, str(_Path(__file__).from gateway.authz_mixin import _coerce_allow_setfrom gateway.config import Platform, PlatformConfigfrom gateway.platforms.base import (- BasePlatformAdapter, MessageEvent, MessageType, ProcessingOutcome, SendResult,- classify_send_error, cache_image_from_bytes_async, cache_audio_from_bytes_async, cache_video_from_bytes_async,- resolve_proxy_url, SUPPORTED_VIDEO_TYPES, SUPPORTED_DOCUMENT_TYPES,- SUPPORTED_IMAGE_DOCUMENT_TYPES, _TEXT_INJECT_EXTENSIONS, utf16_len,- )+ BasePlatformAdapter, MessageEvent, MessageType, ProcessingOutcome, SendResult, classify_send_error,- cache_image_from_bytes, cache_audio_from_bytes, cache_video_from_bytes, resolve_proxy_url, SUPPORTED_VIDEO_TYPES,++ cache_image_from_bytes_async, cache_audio_from_bytes_async, cache_video_from_bytes_async, resolve_proxy_url, SUPPORTED_VIDEO_TYPES,+ SUPPORTED_DOCUMENT_TYPES, SUPPORTED_IMAGE_DOCUMENT_TYPES, _TEXT_INJECT_EXTENSIONS, utf16_len)from plugins.platforms.telegram.telegram_ids import normalize_telegram_chat_idfrom plugins.platforms.telegram.telegram_network import (- SEED_FALLBACK_IPS, TelegramFallbackTransport, discover_fallback_ips, parse_fallback_ip_env,- tcp_keepalive_socket_options,- )+ SEED_FALLBACK_IPS, TelegramFallbackTransport, discover_fallback_ips, parse_fallback_ip_env, tcp_keepalive_socket_options)from utils import env_float, env_int_TELEGRAM_IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".gif"}@@@ -613,32 -454,17 +454,24 @@@ class TelegramAdapter(BasePlatformAdaptself._model_picker_state: Dict[str, dict] = {} # per-chat interactive picker stateself._choice_picker_state: Dict[str, dict] = {}self._approval_state: Dict[int, str] = {} # message_id → session_key- # confirm_id → session_key (see GatewayRunner._request_slash_confirm)- self._slash_confirm_state: Dict[str, str] = {}- # clarify_id → session_key (see GatewayRunner clarify_callback wiring)- self._clarify_state: Dict[str, str] = {}- # "important" (default): only final responses, approvals and slash confirmations- # notify; progress/streaming/status go out with disable_notification.- # "all": every message notifies (opt-in via display.platforms.telegram.notifications).+ self._slash_confirm_state: Dict[str, str] = {} # confirm_id → session_key+ self._clarify_state: Dict[str, str] = {} # clarify_id → session_key+ # "important" (default): only final responses, approvals and slash confirmations notify;+ # "all": every message notifies (display.platforms.telegram.notifications).self._notifications_mode: str = "important"- # send_or_update_status(): {(chat_id, status_key) -> message_id} so repeat calls edit- # the same bubble instead of appending.+ # send_or_update_status(): {(chat_id, status_key) -> message_id} so repeat calls edit in place.self._status_message_ids: Dict[tuple, str] = {}- # Last truncated mid-stream preview per (chat_id, message_id). Once an oversized- # stream saturates the 4096 cap every edit truncates to the SAME text; resending is a- # no-op that still burns flood budget (200s+ penalties). Entries dropped on finalize.+ # Last truncated mid-stream preview per (chat_id, message_id): past the 4096 cap every edit+ # truncates to the SAME text, and resending burns flood budget. Dropped on finalize.self._last_overflow_preview: Dict[tuple, str] = {}- # Post-connect housekeeping (command menu + DM topics) runs off the connect path so a- # slow Bot API call (set_my_commands stall) can't blow the gateway connect timeout.- self._post_connect_task: Optional[asyncio.Task] = None+ @property+ def send_path_degraded(self) -> bool:+ # True from polling-generation start until the first getUpdates+ # round-trip is proven (_record_polling_progress), and again at every+ # polling-death site. getattr: tests build adapters via object.__new__().+ return bool(getattr(self, "_send_path_degraded", False))+def _mark_connected(self) -> None:self._drop_delayed_deliveries = Falsesuper()._mark_connected()@@@ -2178,32 -1599,22 +1613,27 @@@self._background_tasks.add(self._polling_error_task)self._polling_error_task.add_done_callback(self._background_tasks.discard)- def _schedule_polling_recovery(self, error: Exception, *, reason: str) -> None:- """Schedule background polling recovery without failing gateway startup.+ def _recovery_in_flight(self) -> bool:+ return bool(self._polling_error_task and not self._polling_error_task.done())- A transient bootstrap failure (deleteWebhook / initial start_polling) degrades- only this adapter; the reconnect ladder recovers in the background.- """- if self._teardown_started:- return- if self.has_fatal_error:+ def _schedule_polling_recovery(self, error: Exception, *, reason: str) -> None:+ """Schedule background polling recovery without failing gateway startup: a transient bootstrap+ failure degrades only this adapter; the reconnect ladder recovers in the background."""+ if self._teardown_started or self.has_fatal_error:return- if self._polling_error_task and not self._polling_error_task.done():+ if self._recovery_in_flight():logger.debug(- "[%s] Telegram polling recovery already scheduled; ignoring %s: %s",- self.name, reason, _redact_telegram_error_text(error),- )+ "[%s] Telegram polling recovery already scheduled; ignoring %s: %s", self.name, reason, _redact_telegram_error_text(error))returnself._send_path_degraded = True+ # Polling died mid-session on an adapter that published "connected"+ # at connect time. Without this, gateway_state.json keeps saying+ # connected for as long as the recovery ladder runs (#101391: 11 h).+ if getattr(self, "_running", False):+ self._mark_degraded()logger.warning(- "[%s] Telegram polling degraded (%s); gateway stays alive and will retry. Error: %s",- self.name, reason, _redact_telegram_error_text(error),- )+ "[%s] Telegram polling degraded (%s); gateway stays alive and will retry. Error: %s", self.name, reason,+ _redact_telegram_error_text(error))self._spawn_polling_recovery(asyncio.get_running_loop(), self._handle_polling_network_error(error))async def _delete_webhook_best_effort(self, *, require_success: bool = False) -> bool:@@@ -7074,13 -5162,9 +5181,9 @@@_CACHED_KIND_TO_MESSAGE_TYPE = {"image": MessageType.PHOTO, "video": MessageType.VIDEO, "audio": MessageType.AUDIO}async def _download_observed_media(self, msg: Any, what: str):- """Download ``msg``'s attachment into the media cache (bounded by ``_max_doc_bytes``).-- Returns ``(status, cached)`` where status is ``"none"`` (no attachment),- ``"oversized"`` (skipped, ``cached`` is the raw file_size), ``"failed"``- (download error, logged), ``"unreadable"`` (cache rejected it) or ``"ok"``.- """+ """Download ``msg``'s attachment into the media cache (bounded by ``_max_doc_bytes``). Returns ``(status, cached)``:+ ``"none"``, ``"oversized"`` (cached = raw file_size), ``"failed"``, ``"unreadable"`` or ``"ok"``."""- from gateway.platforms.base import cache_media_bytes+ from gateway.platforms.base import cache_media_bytes_asyncsource, filename, mime, kind = self._observed_media_source(msg)if source is None:return "none", None@@@ -7564,15 -5562,11 +5581,11 @@@file_obj = await source.get_file()data = await file_obj.download_as_bytearray()if kind == "video":- if getattr(file_obj, "file_path", None):- for candidate in SUPPORTED_VIDEO_TYPES:- if file_obj.file_path.lower().endswith(candidate):- ext = candidate- break+ ext = self._ext_from_path(getattr(file_obj, "file_path", None), SUPPORTED_VIDEO_TYPES, ext)- cached_path = cache_video_from_bytes(bytes(data), ext=ext)+ cached_path = await cache_video_from_bytes_async(bytes(data), ext=ext)mime = SUPPORTED_VIDEO_TYPES.get(ext, "video/mp4")else:- cached_path = cache_audio_from_bytes(bytes(data), ext=ext)+ cached_path = await cache_audio_from_bytes_async(bytes(data), ext=ext)event.media_urls = [cached_path]event.media_types = [mime]logger.info("[Telegram] Cached user %s at %s", kind, cached_path)@@@ -7581,58 -5575,134 +5594,134 @@@await self._surface_media_cache_failure(msg, event, label, e)return False+ async def _dispatch_with_text(self, event: MessageEvent, text: str) -> bool:+ """Replace the event text with a user-facing note and dispatch it; returns True (handled)."""+ event.text = text+ await self.handle_message(event)+ return True++ @staticmethod+ def _set_cached_media(event: MessageEvent, path: str, mime: str, mtype: MessageType, log_fmt: str) -> None:+ event.media_urls = [path]+ event.media_types = [mime]+ event.message_type = mtype+ logger.info(log_fmt, path)++ async def _cache_inbound_document(self, msg, event: MessageEvent) -> bool:+ """Cache a document attachment (image → photo path, video, else generic media + text injection).+ Returns True when the event was already dispatched/routed so the caller must return."""+ doc = msg.document+ try:+ original_filename = doc.file_name or ""+ ext = os.path.splitext(original_filename)[1].lower() if original_filename else ""+ doc_mime = (doc.mime_type or "").lower() # some clients send "IMAGE/PNG"+ if not ext and doc_mime:+ ext = _TELEGRAM_IMAGE_MIME_TO_EXT.get(doc_mime, "")+ if not ext:+ ext = {v: k for k, v in SUPPORTED_DOCUMENT_TYPES.items()}.get(doc_mime, "")+ display = original_filename or doc_mime or ext or 'unknown'+ # Size check before the image branch so image documents can't bypass the limit.+ if not doc.file_size or doc.file_size > self._max_doc_bytes:+ logger.info("[Telegram] Document too large: %s bytes", doc.file_size)+ return await self._dispatch_with_text(+ event, f"The document is too large or its size could not be verified. Maximum: {self._max_doc_bytes // (1024 * 1024)} MB.")+ # Screenshots/photos sent as documents take the image cache + batching path.+ if ext in _TELEGRAM_IMAGE_EXTENSIONS or doc_mime.startswith("image/"):+ file_obj = await doc.get_file()+ image_bytes = await file_obj.download_as_bytearray()+ image_ext = ext if ext in _TELEGRAM_IMAGE_EXTENSIONS else _TELEGRAM_IMAGE_MIME_TO_EXT.get(doc_mime, ".jpg")+ try:- cached_path = cache_image_from_bytes(bytes(image_bytes), ext=image_ext)++ cached_path = await cache_image_from_bytes_async(bytes(image_bytes), ext=image_ext)+ except ValueError as e:+ logger.warning("[Telegram] Failed to cache image document: %s", _redact_telegram_error_text(e), exc_info=True)+ return await self._dispatch_with_text(event, f"Image document '{display}' could not be read as an image.")+ self._set_cached_media(+ event, cached_path, doc_mime if doc_mime.startswith(+ "image/"+ ) else _TELEGRAM_IMAGE_EXT_TO_MIME.get(image_ext, "image/jpeg"),+ MessageType.PHOTO, "[Telegram] Cached user image-document at %s")+ await self._route_photo_event(msg, event)+ return True+ if not ext and doc.mime_type:+ ext = {v: k for k, v in SUPPORTED_VIDEO_TYPES.items()}.get(doc.mime_type, "")+ if not ext and doc.mime_type:+ # .jpg and .jpeg both map to image/jpeg; keep the first ext seen.+ image_mime_to_ext: dict[str, str] = {}+ for _ext, _mime in SUPPORTED_IMAGE_DOCUMENT_TYPES.items():+ image_mime_to_ext.setdefault(_mime, _ext)+ ext = image_mime_to_ext.get(doc.mime_type, "")+ if ext in SUPPORTED_VIDEO_TYPES:+ file_obj = await doc.get_file()+ video_bytes = await file_obj.download_as_bytearray()+ self._set_cached_media(- event, cache_video_from_bytes(bytes(video_bytes), ext=ext), SUPPORTED_VIDEO_TYPES[ext], MessageType.VIDEO,++ event, await cache_video_from_bytes_async(bytes(video_bytes), ext=ext), SUPPORTED_VIDEO_TYPES[ext], MessageType.VIDEO,+ "[Telegram] Cached user video document at %s")+ await self.handle_message(event)+ return True+ # Any file type is accepted (authorization is the gate, not the extension); unknown types get+ # application/octet-stream. Image documents already returned above.+ file_obj = await doc.get_file()+ raw_bytes = bytes(await file_obj.download_as_bytearray())- from gateway.platforms.base import cache_media_bytes- cached = cache_media_bytes(raw_bytes, filename=original_filename or f"document{ext or '.bin'}", mime_type=doc_mime)++ from gateway.platforms.base import cache_media_bytes_async++ cached = await cache_media_bytes_async(raw_bytes, filename=original_filename or f"document{ext or '.bin'}", mime_type=doc_mime)+ if cached is None:+ return await self._dispatch_with_text(event, f"Document '{display}' could not be cached.")+ event.media_urls = [cached.path]+ event.media_types = [cached.media_type]+ if cached.kind == "audio":+ event.message_type = MessageType.AUDIO+ logger.info("[Telegram] Cached user %s at %s (%s)", cached.kind, cached.path, cached.media_type)+ # Inject text-readable content (≤100 KB). Gate on extension/MIME, NOT a blind UTF-8 decode:+ # PDF/zip/docx have decodable ASCII headers. Binary files are surfaced as a cached path only.+ MAX_TEXT_INJECT_BYTES = 100 * 1024+ _is_text = ext in _TEXT_INJECT_EXTENSIONS or (doc_mime or "").startswith("text/")+ if _is_text and len(raw_bytes) <= MAX_TEXT_INJECT_BYTES:+ try:+ text_content = raw_bytes.decode("utf-8")+ display_name = re.sub(r'[^\w.\- ]', '_', original_filename or f"document{ext or '.txt'}")+ injection = f"[Content of {display_name}]:\n{text_content}"+ event.text = f"{injection}\n\n{event.text}" if event.text else injection+ except UnicodeDecodeError:+ pass # binary — agent has the cached path+ except Exception as e:+ logger.warning("[Telegram] Failed to cache document: %s", _redact_telegram_error_text(e), exc_info=True)+ await self._surface_media_cache_failure(msg, event, "attachment", e, display_name=getattr(doc, "file_name", None) or None)+ return False+async def _handle_media_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:"""Handle incoming media messages, downloading images to local cache."""- if not update.message:+ msg = update.message+ if not msg:return- if not self._is_user_authorized_from_message(update.message):- logger.info(- "[Telegram] Blocked media from unauthorized user %s in chat %s",- getattr(getattr(update.message, "from_user", None), "id", None),- getattr(getattr(update.message, "chat", None), "id", None),- )+ if not self._is_user_authorized_from_message(msg):+ self._log_blocked_user(msg, level=logging.INFO, what="media from unauthorized user")return- if not self._should_process_message(update.message):- if self._should_observe_unmentioned_group_message(update.message):- _m = update.message- _observe_type = self._media_message_type(_m)- _event = self._build_message_event(_m, _observe_type, update_id=update.update_id)- if _m.caption:- _event.text = self._clean_bot_trigger_text(_m.caption)- await self._cache_observed_media(_m, _event)- self._observe_unmentioned_group_message(_m, _event.message_type, update_id=update.update_id, event=_event)+ if not self._should_process_message(msg):+ if self._should_observe_unmentioned_group_message(msg):+ _event = self._build_message_event(msg, self._media_message_type(msg), update_id=update.update_id)+ if msg.caption:+ _event.text = self._clean_bot_trigger_text(msg.caption)+ await self._cache_observed_media(msg, _event)+ self._observe_unmentioned_group_message(msg, _event.message_type, update_id=update.update_id, event=_event)return- msg = update.message- msg_type = self._media_message_type(msg)- event = self._build_message_event(msg, msg_type, update_id=update.update_id)+ event = self._build_message_event(msg, self._media_message_type(msg), update_id=update.update_id)if msg.caption:event.text = self._clean_bot_trigger_text(msg.caption)-- # Stickers: _handle_sticker overwrites event.text with its vision description, so- # observe attribution must run after it.+ # Stickers: _handle_sticker overwrites event.text with its vision description, so observe attribution must run after it.if msg.sticker:await self._handle_sticker(msg, event)- event = self._apply_telegram_group_observe_attribution(event)- await self.handle_message(event)+ await self.handle_message(self._apply_telegram_group_observe_attribution(event))returnevent = self._apply_telegram_group_observe_attribution(event)-# Cache photo locally: Telegram's file URLs expire (~1 hour) before vision may run.if msg.photo:try:- photo = msg.photo[-1] # PhotoSize list sorted by size; largest last- file_obj = await photo.get_file()+ file_obj = await msg.photo[-1].get_file() # PhotoSize list sorted by size; largest lastimage_bytes = await file_obj.download_as_bytearray()- ext = ".jpg"- if file_obj.file_path:- for candidate in [".png", ".webp", ".gif", ".jpeg", ".jpg"]:- if file_obj.file_path.lower().endswith(candidate):- ext = candidate- break- cached_path = await cache_image_from_bytes_async(bytes(image_bytes), ext=ext)- event.media_urls = [cached_path]- event.media_types = [f"image/{ext.lstrip('.')}"]- logger.info("[Telegram] Cached user photo at %s", cached_path)+ ext = self._ext_from_path(file_obj.file_path, [".png", ".webp", ".gif", ".jpeg", ".jpg"], ".jpg")+ self._set_cached_media(- event, cache_image_from_bytes(bytes(image_bytes), ext=ext), f"image/{ext.lstrip('.')}", event.message_type,++ event, await cache_image_from_bytes_async(bytes(image_bytes), ext=ext), f"image/{ext.lstrip('.')}", event.message_type,+ "[Telegram] Cached user photo at %s")await self._route_photo_event(msg, event)returnexcept Exception as e:@@@ -7826,11 -5762,10 +5781,10 @@@try:file_obj = await sticker.get_file()image_bytes = await file_obj.download_as_bytearray()- cached_path = cache_image_from_bytes(bytes(image_bytes), ext=".webp")+ cached_path = await cache_image_from_bytes_async(bytes(image_bytes), ext=".webp")logger.info("[Telegram] Analyzing sticker at %s", cached_path)from tools.vision_tools import vision_analyze_tool- result_json = await vision_analyze_tool(image_url=cached_path, user_prompt=STICKER_VISION_PROMPT)- result = json.loads(result_json)+ result = json.loads(await vision_analyze_tool(image_url=cached_path, user_prompt=STICKER_VISION_PROMPT))if result.get("success"):description = result.get("analysis", "a sticker")cache_sticker_description(sticker.file_unique_id, description, emoji, set_name)diff --cc plugins/platforms/wecom/media.pyindex 6081724763e,ba3bfb0da3e..319024559a0--- a/plugins/platforms/wecom/media.py+++ b/plugins/platforms/wecom/media.py@@@ -100,37 -89,30 +89,30 @@@ class WeComMediaMixinexcept Exception as exc:logger.debug("[%s] Failed to decode %s base64 media: %s", self.name, kind, exc)return None- if kind == "image":- ext = self._detect_image_ext(raw)- return await self._cache_image(raw, ext, self._mime_for_ext(ext, fallback="image/jpeg"), "")filename = str(media.get("filename") or media.get("name") or "wecom_file")- return await cache_document_from_bytes_async(raw, filename), mimetypes.guess_type(filename)[0] or "application/octet-stream"-- return self._store_media(kind, raw, self._detect_image_ext(raw), "", filename, mimetypes.guess_type(filename)[0] or "application/octet-stream", "")++ return await self._store_media(kind, raw, self._detect_image_ext(raw), "", filename, mimetypes.guess_type(filename)[0] or "application/octet-stream", "")url = str(media.get("url") or "").strip()if not url:return None+ aes_key = str(media.get("aeskey") or "").strip()try:+ step = "download"raw, headers = await self._download_remote_bytes(url, max_bytes=ABSOLUTE_MAX_BYTES)+ step = "decrypt"+ raw = self._decrypt_file_bytes(raw, aes_key) if aes_key else rawexcept Exception as exc:- logger.debug("[%s] Failed to download %s from %s: %s", self.name, kind, url, exc)+ logger.debug("[%s] Failed to %s %s from %s: %s", self.name, step, kind, url, exc)return None- aes_key = str(media.get("aeskey") or "").strip()- if aes_key:- try:- raw = self._decrypt_file_bytes(raw, aes_key)- except Exception as exc:- logger.debug("[%s] Failed to decrypt %s from %s: %s", self.name, kind, url, exc)- return Nonecontent_type = str(headers.get("content-type") or "").split(";", 1)[0].strip() or "application/octet-stream"- if kind == "image":- ext = self._guess_extension(url, content_type, fallback=self._detect_image_ext(raw))- return await self._cache_image(raw, ext, content_type or self._mime_for_ext(ext, fallback="image/jpeg"), f" from {url}")- filename = self._guess_filename(url, headers.get("content-disposition"), content_type)- return await cache_document_from_bytes_async(raw, filename), content_type+ ext = self._guess_extension(url, content_type, fallback=self._detect_image_ext(raw))- return self._store_media(kind, raw, ext, content_type, self._guess_filename(url, headers.get("content-disposition"), content_type), content_type, f" from {url}")++ return await self._store_media(kind, raw, ext, content_type, self._guess_filename(url, headers.get("content-disposition"), content_type), content_type, f" from {url}")- async def _cache_image(self, raw: bytes, ext: str, mime: str, origin: str) -> Optional[Tuple[str, str]]:- def _store_media(self, kind, raw, ext, image_mime, filename, doc_mime, origin) -> Optional[Tuple[str, str]]:++ async def _store_media(self, kind, raw, ext, image_mime, filename, doc_mime, origin) -> Optional[Tuple[str, str]]:+ """Cache bytes as an image (``kind == "image"``) or a document; returns (path, mime)."""+ if kind != "image":- return cache_document_from_bytes(raw, filename), doc_mime++ return await cache_document_from_bytes_async(raw, filename), doc_mimetry:- return await cache_image_from_bytes_async(raw, ext), mime- return cache_image_from_bytes(raw, ext), image_mime or self._mime_for_ext(ext, fallback="image/jpeg")++ return await cache_image_from_bytes_async(raw, ext), image_mime or self._mime_for_ext(ext, fallback="image/jpeg")except ValueError as exc:logger.warning("[%s] Rejected non-image bytes%s: %s", self.name, origin, exc)return None