The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(all): simplify chunker loop, suppress() for swallow blocks, table-drive AV cachers
Tekniumb9884c59d785
diff --git a/plugins/platforms/line/adapter.py b/plugins/platforms/line/adapter.pyindex 11ad1568384..8e702695c8a 100644--- a/plugins/platforms/line/adapter.py+++ b/plugins/platforms/line/adapter.py@@ -105,24 +105,18 @@ def split_for_line(text: str, max_chars: int = LINE_SAFE_BUBBLE_CHARS) -> List[sreturn [text] if text else []chunks: List[str] = []remaining = text- while remaining and len(chunks) < LINE_MAX_MESSAGES_PER_CALL:- if len(remaining) <= max_chars:- chunks.append(remaining)- remaining = ""- break- for sep in ("\n\n", "\n", " "): # prefer paragraph, then line, then word breaks- cut = remaining.rfind(sep, 0, max_chars)- if cut >= int(max_chars * 0.5):- break+ while remaining and len(chunks) < LINE_MAX_MESSAGES_PER_CALL and len(remaining) > max_chars:+ # Prefer paragraph, then line, then word breaks past the half-way mark; else a hard cut.+ cuts = [remaining.rfind(sep, 0, max_chars) for sep in ("\n\n", "\n", " ")]+ cut = next((c for c in cuts if c >= int(max_chars * 0.5)), cuts[-1])if cut <= 0:cut = max_charschunks.append(remaining[:cut].rstrip())remaining = remaining[cut:].lstrip()- if remaining: # budget exhausted → ellipsis on the last bubble- tail = chunks[-1]- if len(tail) > max_chars - 1:- tail = tail[: max_chars - 1]- chunks[-1] = tail.rstrip() + "…"+ if remaining and len(chunks) < LINE_MAX_MESSAGES_PER_CALL:+ chunks.append(remaining)+ elif remaining: # budget exhausted → ellipsis on the last bubble+ chunks[-1] = chunks[-1][: max_chars - 1].rstrip() + "…"return chunks@@ -349,6 +343,7 @@ _OUTBOUND_MEDIA = {# Inbound media kinds → cached file extension._INBOUND_MEDIA_EXT = {"image": ".jpg", "audio": ".m4a", "video": ".mp4", "file": ".bin"}+_INBOUND_AV_CACHERS = {"audio": cache_audio_from_bytes, "video": cache_video_from_bytes}_LIFECYCLE_EVENTS = frozenset({"follow", "unfollow", "join", "leave"})@@ -610,9 +605,8 @@ class LineAdapter(BasePlatformAdapter):try:if msg_type == "image":return cache_image_from_bytes(data, ext=ext), "image/jpeg"- if msg_type in ("audio", "video"):- cache_fn = cache_audio_from_bytes if msg_type == "audio" else cache_video_from_bytes- return cache_fn(data, ext=ext), mimetypes.guess_type(f"{msg_type}{ext}")[0] or f"{msg_type}/mp4"+ if msg_type in _INBOUND_AV_CACHERS:+ return _INBOUND_AV_CACHERS[msg_type](data, ext=ext), mimetypes.guess_type(f"{msg_type}{ext}")[0] or f"{msg_type}/mp4"document_name = filename or f"line_file{ext}"mime = mimetypes.guess_type(document_name)[0] or "application/octet-stream"return cache_document_from_bytes(data, document_name), mimediff --git a/plugins/platforms/simplex/adapter.py b/plugins/platforms/simplex/adapter.pyindex 55a17eb604b..2e14f7de32b 100644--- a/plugins/platforms/simplex/adapter.py+++ b/plugins/platforms/simplex/adapter.py@@ -11,6 +11,7 @@ HERMES_SIMPLEX_TEXT_BATCH_DELAY (quiet seconds, default 0.8, merging rapid-fireimport asyncioimport base64+import contextlibimport jsonimport loggingimport os@@ -39,6 +40,7 @@ _IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".webp"}_AUDIO_EXTS = {".mp3", ".wav", ".ogg", ".m4a", ".aac", ".opus"}_VOICE_TAG_EXTS = {".ogg", ".mp3", ".wav", ".m4a", ".opus"} # MEDIA: tags sent as voice notes_TEXT_BEARING_TYPES = ("text", "file", "image", "voice", "link", "video")+_THUMB_URI_PREFIX = "data:image/jpg;base64,"_MEDIA_KIND_PRECEDENCE = (("audio/", MessageType.VOICE), ("image/", MessageType.PHOTO)) # first match wins@@ -84,10 +86,8 @@ def _send_cmd(chat_id: str, items: list) -> str:async def _cancel_task(task: Optional[asyncio.Task]) -> None:if task:task.cancel()- try:+ with contextlib.suppress(asyncio.CancelledError):await task- except asyncio.CancelledError:- passclass SimplexAdapter(BasePlatformAdapter):@@ -155,10 +155,8 @@ class SimplexAdapter(BasePlatformAdapter):await _cancel_task(self._ws_task)await _cancel_task(self._health_task)if self._ws:- try:+ with contextlib.suppress(Exception):await self._ws.close()- except Exception:- passself._ws = Nonefor pending in (self._pending_text_batch_tasks.values(), self._pending_responses.values()):for item in list(pending):@@ -503,25 +501,23 @@ class SimplexAdapter(BasePlatformAdapter):import subprocessimport tempfilep = Path(file_path)- png_path = file_path- thumb_uri = ""needs_png = p.suffix.lower() not in (".png", ".jpg", ".jpeg")+ png_path = str(p.with_suffix(".png")) if needs_png else file_path+ thumb_uri = ""try:from PIL import Imageimport ioimg = Image.open(file_path)if needs_png:- png_path = str(p.with_suffix(".png"))img.save(png_path, "PNG")thumb = img.copy()thumb.thumbnail((128, 128))buf = io.BytesIO()thumb.save(buf, "JPEG", quality=70)- thumb_uri = "data:image/jpg;base64," + base64.b64encode(buf.getvalue()).decode()+ thumb_uri = _THUMB_URI_PREFIX + base64.b64encode(buf.getvalue()).decode()except ImportError:try:if needs_png:- png_path = str(p.with_suffix(".png"))subprocess.run(["convert", file_path, png_path],check=True, capture_output=True, timeout=30, stdin=subprocess.DEVNULL)with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:@@ -529,7 +525,7 @@ class SimplexAdapter(BasePlatformAdapter):subprocess.run(["convert", file_path, "-resize", "128x128", "-quality", "70", tmp_path],check=True, capture_output=True, timeout=30)with open(tmp_path, "rb") as f:- thumb_uri = "data:image/jpg;base64," + base64.b64encode(f.read()).decode()+ thumb_uri = _THUMB_URI_PREFIX + base64.b64encode(f.read()).decode()os.remove(tmp_path)except (FileNotFoundError, subprocess.SubprocessError) as exc:logger.warning("SimpleX: image conversion unavailable: %s", exc)diff --git a/plugins/platforms/teams/adapter.py b/plugins/platforms/teams/adapter.pyindex 208f89c0a5d..c5d9dbfd338 100644--- a/plugins/platforms/teams/adapter.py+++ b/plugins/platforms/teams/adapter.py@@ -16,7 +16,7 @@ import loggingimport osimport reimport sys-from contextlib import contextmanager+from contextlib import contextmanager, suppressfrom typing import Any, Dict, Iterator, Optionalfrom urllib.parse import urlparse@@ -34,9 +34,8 @@ def _probe_teams_sdk_available() -> bool:Sibling packages share the namespace, so probe the parent first — ``find_spec`` of the childraises on 3.11+ if the parent is absent."""try:- if importlib.util.find_spec("microsoft_teams") is None:- return False- return importlib.util.find_spec("microsoft_teams.apps") is not None+ find_spec = importlib.util.find_spec+ return find_spec("microsoft_teams") is not None and find_spec("microsoft_teams.apps") is not Noneexcept (ValueError, ModuleNotFoundError, ImportError):return "microsoft_teams.apps" in sys.modules # test stubs may lack ``__spec__``@@ -490,9 +489,7 @@ class TeamsAdapter(BasePlatformAdapter):att_name = getattr(att, "name", None) or ""# Skip non-file payloads: Teams mirrors the message body as a text/html attachment,# and cards arrive as application/vnd.microsoft.card.*- if content_type in ("text/html", "text/plain") and not content_url:- return None- if content_type.startswith("application/vnd.microsoft.card"):+ if (content_type in ("text/html", "text/plain") and not content_url) or content_type.startswith("application/vnd.microsoft.card"):return Noneif content_type == "application/vnd.microsoft.teams.file.download.info":# Consent-free download: content carries a pre-authed SharePoint downloadUrl + file type.@@ -660,12 +657,9 @@ class TeamsAdapter(BasePlatformAdapter):return SendResult(success=True, message_id=last_message_id)async def send_typing(self, chat_id: str, metadata: Optional[Dict[str, Any]] = None) -> None:- if not self._app:- return- try:- await self._app.send(chat_id, TypingActivityInput())- except Exception:- pass+ if self._app:+ with suppress(Exception):+ await self._app.send(chat_id, TypingActivityInput())async def _send_media_attachment(self, chat_id: str, source: str, default_mime: str, caption: Optional[str] = None, media_label: str = "media"