The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(ntfy,homeassistant,sms,google_chat): AST-neutral layout compaction (hug/pack/closers)
Teknium4b3db0af8946
diff --git a/plugins/platforms/google_chat/cards.py b/plugins/platforms/google_chat/cards.pyindex 5a21ec0b8fe..b92b1cf58a0 100644--- a/plugins/platforms/google_chat/cards.py+++ b/plugins/platforms/google_chat/cards.py@@ -102,8 +102,7 @@ def _text_widget(widget: Dict[str, Any]) -> Dict[str, Any]:def _decorated_text_widget(widget: Dict[str, Any]) -> Dict[str, Any]:decorated: Dict[str, Any] = {"text": format_message(_required_str(widget, "text", "widget")),- "wrapText": bool(widget.get("wrap_text", True)),- }+ "wrapText": bool(widget.get("wrap_text", True))}return {"decoratedText": _copy_opt(decorated, widget, ("top_label", "topLabel"), ("bottom_label", "bottomLabel"))}@@ -123,8 +122,7 @@ def _selection_item(item: Any) -> Dict[str, Any]:return {"text": _required_str(item, "text", "selection item"),"value": _required_str(item, "value", "selection item"),- "selected": bool(item.get("selected", False)),- }+ "selected": bool(item.get("selected", False))}def _selection_widget(widget: Dict[str, Any]) -> Dict[str, Any]:@@ -135,9 +133,7 @@ def _selection_widget(widget: Dict[str, Any]) -> Dict[str, Any]:"name": name,"label": str(widget.get("label") or name),"type": str(widget.get("selection_type") or "CHECK_BOX"),- "items": [_selection_item(item) for item in raw_items],- }- }+ "items": [_selection_item(item) for item in raw_items]}}_WIDGET_RENDERERS: Dict[str, Callable[[Dict[str, Any]], Dict[str, Any]]] = {diff --git a/plugins/platforms/google_chat/oauth.py b/plugins/platforms/google_chat/oauth.pyindex 4265069a11b..35cd47bf09e 100644--- a/plugins/platforms/google_chat/oauth.py+++ b/plugins/platforms/google_chat/oauth.py@@ -278,8 +278,7 @@ def store_client_secret(path: str) -> None:if "installed" not in data and "web" not in data:_fail("ERROR: Not a Google OAuth client secret file (missing 'installed' or 'web' key).",- "Download from: https://console.cloud.google.com/apis/credentials",- )+ "Download from: https://console.cloud.google.com/apis/credentials")target = _client_secret_path()_write_private_json(target, data)print(f"OK: Client secret saved to {target}")@@ -362,12 +361,9 @@ def exchange_auth_code(code: str, email: Optional[str] = None) -> None:if scope_val:granted_scopes = scope_val.split()flow = Flow.from_client_secrets_file(- str(_client_secret_path()),- scopes=granted_scopes,- redirect_uri=pending_auth.get("redirect_uri", _REDIRECT_URI),- state=pending_auth["state"],- code_verifier=pending_auth["code_verifier"],- )+ str(_client_secret_path()), scopes=granted_scopes,+ redirect_uri=pending_auth.get("redirect_uri", _REDIRECT_URI), state=pending_auth["state"],+ code_verifier=pending_auth["code_verifier"])try:# Accept partial scopes — user may deselect items in the consent screen.os.environ["OAUTHLIB_RELAX_TOKEN_SCOPE"] = "1"@@ -407,10 +403,8 @@ def revoke(email: Optional[str] = None) -> None:urllib.request.Request(f"https://oauth2.googleapis.com/revoke?token={creds.token}",method="POST",- headers={"Content-Type": "application/x-www-form-urlencoded"},- ),- timeout=15,- )+ headers={"Content-Type": "application/x-www-form-urlencoded"}),+ timeout=15)print("Token revoked with Google.")except Exception as exc:print(f"Remote revocation failed (token may already be invalid): {exc}")@@ -432,8 +426,7 @@ def main() -> None:group.add_argument("--install-deps", action="store_true", help="Install Python dependencies")parser.add_argument("--email", metavar="EMAIL", default=None,- help="Scope operation to a specific user's token (default: legacy single-user path)",- )+ help="Scope operation to a specific user's token (default: legacy single-user path)")args = parser.parse_args()email = args.email or Noneif args.check:diff --git a/plugins/platforms/google_chat/setup_files.py b/plugins/platforms/google_chat/setup_files.pyindex 6d908847f3e..305f18e0afc 100644--- a/plugins/platforms/google_chat/setup_files.py+++ b/plugins/platforms/google_chat/setup_files.py@@ -50,12 +50,8 @@ async def _run_captured(fn: Callable[..., Any], *args: Any) -> str:async def handle_setup_files_command(- adapter: Any,- chat_id: str,- thread_id: Optional[str],- raw_text: str,- sender_email: Optional[str] = None,-) -> bool:+ adapter: Any, chat_id: str, thread_id: Optional[str], raw_text: str,+ sender_email: Optional[str] = None) -> bool:"""Run the in-chat OAuth setup flow. Returns True when the message was consumed.``sender_email`` is the per-user OAuth key; ``None`` falls back to the legacy@@ -114,8 +110,7 @@ async def handle_setup_files_command(who = sender_key or "shared (legacy)"await _reply(f"✅ Native attachment delivery is **active** for `{who}`.\n"- f"Token: `{token_path}`\nSend `/setup-files revoke` to disable."- )+ f"Token: `{token_path}`\nSend `/setup-files revoke` to disable.")elif not client_secret_present:await _reply(_NOT_CONFIGURED_TEXT)else:@@ -163,6 +158,5 @@ async def handle_setup_files_command(await _reply("⚠️ Token exchanged but the gateway couldn't load the new credentials in-memory. "f"Restart the gateway and the token at `{oauth_helper._token_path(sender_key)}` will be picked up.\n"- f"Helper output:\n```\n{output.strip()}\n```"- )+ f"Helper output:\n```\n{output.strip()}\n```")return Truediff --git a/plugins/platforms/homeassistant/adapter.py b/plugins/platforms/homeassistant/adapter.pyindex 4d2df6cfb8a..60c7b53eb14 100644--- a/plugins/platforms/homeassistant/adapter.py+++ b/plugins/platforms/homeassistant/adapter.py@@ -122,8 +122,7 @@ class HomeAssistantAdapter(BasePlatformAdapter):"[%s] No watch_domains, watch_entities, or watch_all configured. ""All state_changed events will be dropped. Configure filters in ""your HA platform config to receive events.",- self.name,- )+ self.name)self._listen_task = asyncio.create_task(self._listen_loop())self._running = Truelogger.info("[%s] Connected to %s", self.name, self._hass_url)@@ -242,18 +241,15 @@ class HomeAssistantAdapter(BasePlatformAdapter):returnself._last_event_time[entity_id] = nowmessage = self._format_state_change(- entity_id, event_data.get("old_state", {}), event_data.get("new_state", {}),- )+ entity_id, event_data.get("old_state", {}), event_data.get("new_state", {}))if not message:returnsource = self.build_source(chat_id="ha_events", chat_name="Home Assistant Events", chat_type="channel",- user_id="homeassistant", user_name="Home Assistant",- )+ user_id="homeassistant", user_name="Home Assistant")await self.handle_message(MessageEvent(text=message, message_type=MessageType.TEXT, source=source,- message_id=f"ha_{entity_id}_{int(now)}", timestamp=datetime.now(),- ))+ message_id=f"ha_{entity_id}_{int(now)}", timestamp=datetime.now()))@staticmethoddef _format_state_change(entity_id: str, old_state: Dict[str, Any], new_state: Dict[str, Any]) -> Optional[str]:@@ -270,8 +266,7 @@ class HomeAssistantAdapter(BasePlatformAdapter):name=attrs.get("friendly_name", entity_id), entity_id=entity_id, old=old_val, new=new_val,temp=attrs.get("current_temperature", "?"), target=attrs.get("temperature", "?"),unit=attrs.get("unit_of_measurement", ""), on_off=_on_off(new_val),- triggered=_triggered(new_val), was_triggered=_triggered(old_val),- )+ triggered=_triggered(new_val), was_triggered=_triggered(old_val))# -- Outbound messaging -------------------------------------------------@@ -370,5 +365,4 @@ def register(ctx) -> None:standalone_sender_fn=_standalone_send, # out-of-process cron delivery via notify.notifymax_message_length=HomeAssistantAdapter.MAX_MESSAGE_LENGTH,emoji="🏠",- allow_update_command=True,- )+ allow_update_command=True)diff --git a/plugins/platforms/ntfy/adapter.py b/plugins/platforms/ntfy/adapter.pyindex 5d10e7e0a77..7d177854d07 100644--- a/plugins/platforms/ntfy/adapter.py+++ b/plugins/platforms/ntfy/adapter.py@@ -84,8 +84,7 @@ def _truncate_body(message: str, *, context: str) -> bytes:if len(message) > MAX_MESSAGE_LENGTH:logger.warning("%s: truncating message from %d to %d chars (ntfy limit)",- context, len(message), MAX_MESSAGE_LENGTH,- )+ context, len(message), MAX_MESSAGE_LENGTH)return message[:MAX_MESSAGE_LENGTH].encode("utf-8")@@ -200,8 +199,7 @@ class NtfyAdapter(BasePlatformAdapter):self._set_fatal_error("ntfy_topic_not_found",f"ntfy topic '{self._topic}' returned 404. Check NTFY_TOPIC.",- retryable=False,- )+ retryable=False)raise _FatalStreamError("404 Not Found")async def _consume_stream(self, url: str, headers: Dict[str, str]) -> None:@@ -262,20 +260,17 @@ class NtfyAdapter(BasePlatformAdapter):# NOT drive authorization, so user_id is fixed to the topic name.topic = event.get("topic") or self._topicsource = self.build_source(- chat_id=topic, chat_name=topic, chat_type="dm", user_id=topic, user_name=topic,- )+ chat_id=topic, chat_name=topic, chat_type="dm", user_id=topic, user_name=topic)unix_ts = event.get("time")try:timestamp = (datetime.fromtimestamp(int(unix_ts), tz=timezone.utc)- if unix_ts else datetime.now(tz=timezone.utc)- )+ if unix_ts else datetime.now(tz=timezone.utc))except (ValueError, OSError, TypeError):timestamp = datetime.now(tz=timezone.utc)message_event = MessageEvent(text=text, message_type=MessageType.TEXT, source=source, message_id=msg_id,- raw_message=event, timestamp=timestamp,- )+ raw_message=event, timestamp=timestamp)logger.debug("[%s] Message on topic %s: %s", self.name, topic, text[:80])await self.handle_message(message_event)@@ -305,13 +300,11 @@ class NtfyAdapter(BasePlatformAdapter):if len(content) > self.MAX_MESSAGE_LENGTH:logger.warning("[%s] Message truncated from %d to %d chars (ntfy limit)",- self.name, len(content), self.MAX_MESSAGE_LENGTH,- )+ self.name, len(content), self.MAX_MESSAGE_LENGTH)body = content[:self.MAX_MESSAGE_LENGTH]try:resp = await self._http_client.post(- url, content=body.encode("utf-8"), headers=headers, timeout=15.0,- )+ url, content=body.encode("utf-8"), headers=headers, timeout=15.0)if resp.status_code < 300:return SendResult(success=True, message_id=_response_message_id(resp))body_text = resp.text@@ -345,9 +338,7 @@ def _env_enablement() -> dict | None:if not topic:return Noneseed: dict = {- "topic": topic,- "server": _get_scoped_secret("NTFY_SERVER_URL", DEFAULT_SERVER).rstrip("/"),- }+ "topic": topic, "server": _get_scoped_secret("NTFY_SERVER_URL", DEFAULT_SERVER).rstrip("/")}for key, env in (("publish_topic", "NTFY_PUBLISH_TOPIC"), ("token", "NTFY_TOKEN")):value = _get_scoped_secret(env, "").strip()if value:@@ -380,15 +371,13 @@ async def _standalone_send(or extra.get("publish_topic")or _get_scoped_secret("NTFY_PUBLISH_TOPIC", "").strip()or extra.get("topic")- or _get_scoped_secret("NTFY_TOPIC", "").strip()- )+ or _get_scoped_secret("NTFY_TOPIC", "").strip())if not publish_topic:return {"error": "ntfy standalone send: NTFY_TOPIC not configured"}token = extra.get("token") or _get_scoped_secret("NTFY_TOKEN", "")markdown_env = _get_scoped_secret("NTFY_MARKDOWN", "").strip().lower()headers = _publish_headers(- token, bool(extra.get("markdown")) or markdown_env in _MARKDOWN_TRUTHY, auth_first=False,- )+ token, bool(extra.get("markdown")) or markdown_env in _MARKDOWN_TRUTHY, auth_first=False)body = _truncate_body(message, context="ntfy standalone")try:async with httpx.AsyncClient(timeout=15.0) as client:@@ -428,5 +417,4 @@ def register(ctx) -> None:"(set markdown: true in config or NTFY_MARKDOWN=true). ""Keep responses concise; ntfy is a push notification service ""with a 4096-character per-message limit."- ),- )+ ))diff --git a/plugins/platforms/sms/adapter.py b/plugins/platforms/sms/adapter.pyindex ba94db17d61..a32b60d65b1 100644--- a/plugins/platforms/sms/adapter.py+++ b/plugins/platforms/sms/adapter.py@@ -120,8 +120,7 @@ class SmsAdapter(BasePlatformAdapter):"[sms] SMS_INSECURE_NO_SIGNATURE=true — Twilio signature validation ""is DISABLED. Any client that can reach port %d can inject messages. ""Do NOT use this in production.",- self._webhook_port,- )+ self._webhook_port)# client_max_size bounds every read path (incl. chunked bodies with no# Content-Length) before the handler's own 413 checks run.app = web.Application(client_max_size=_TWILIO_WEBHOOK_MAX_BODY_BYTES)@@ -135,8 +134,7 @@ class SmsAdapter(BasePlatformAdapter):self._running = Truelogger.info("[sms] Twilio webhook server listening on %s:%d, from: %s",- self._webhook_host, self._webhook_port, redact_phone(self._from_number),- )+ self._webhook_host, self._webhook_port, redact_phone(self._from_number))self._wire_plugin_handlers(None)return True@@ -224,8 +222,7 @@ class SmsAdapter(BasePlatformAdapter):else:return Nonereturn urllib.parse.urlunparse(- (parsed.scheme, netloc, parsed.path, parsed.params, parsed.query, parsed.fragment)- )+ (parsed.scheme, netloc, parsed.path, parsed.params, parsed.query, parsed.fragment))# -- Inbound webhook -----------------------------------------------------@@ -253,8 +250,7 @@ class SmsAdapter(BasePlatformAdapter):return _twiml_response(403)# parse_qs returns listsfrom_number, to_number, text, message_sid = (- form.get(key, [""])[0].strip() for key in ("From", "To", "Body", "MessageSid")- )+ form.get(key, [""])[0].strip() for key in ("From", "To", "Body", "MessageSid"))if not from_number or not text:return _twiml_response()if from_number == self._from_number: # echo prevention@@ -281,16 +277,11 @@ class SmsAdapter(BasePlatformAdapter):# Standalone-send markdown stripping: looser than helpers.strip_markdown (no# word-boundary guards on underscores, ``[a-z]*`` fence tags) — kept for parity._SMS_MARKDOWN_SUBS = (- (re.compile(r"\*\*(.+?)\*\*", re.DOTALL), r"\1"),- (re.compile(r"\*(.+?)\*", re.DOTALL), r"\1"),- (re.compile(r"__(.+?)__", re.DOTALL), r"\1"),- (re.compile(r"_(.+?)_", re.DOTALL), r"\1"),- (re.compile(r"```[a-z]*\n?"), ""),- (re.compile(r"`(.+?)`"), r"\1"),- (re.compile(r"^#{1,6}\s+", re.MULTILINE), ""),- (re.compile(r"\[([^\]]+)\]\([^\)]+\)"), r"\1"),- (re.compile(r"\n{3,}"), "\n\n"),-)+ (re.compile(r"\*\*(.+?)\*\*", re.DOTALL), r"\1"), (re.compile(r"\*(.+?)\*", re.DOTALL), r"\1"),+ (re.compile(r"__(.+?)__", re.DOTALL), r"\1"), (re.compile(r"_(.+?)_", re.DOTALL), r"\1"),+ (re.compile(r"```[a-z]*\n?"), ""), (re.compile(r"`(.+?)`"), r"\1"),+ (re.compile(r"^#{1,6}\s+", re.MULTILINE), ""), (re.compile(r"\[([^\]]+)\]\([^\)]+\)"), r"\1"),+ (re.compile(r"\n{3,}"), "\n\n"))def _strip_markdown_for_sms(message: str) -> str:@@ -346,19 +337,10 @@ def _is_connected(config) -> bool:def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""ctx.register_platform(- name="sms",- label="SMS (Twilio)",- adapter_factory=SmsAdapter,- check_fn=check_sms_requirements,- is_connected=_is_connected,+ name="sms", label="SMS (Twilio)", adapter_factory=SmsAdapter,+ check_fn=check_sms_requirements, is_connected=_is_connected,required_env=["TWILIO_ACCOUNT_SID", "TWILIO_AUTH_TOKEN", "TWILIO_PHONE_NUMBER"],- install_hint="pip install aiohttp",- allowed_users_env="SMS_ALLOWED_USERS",- allow_all_env="SMS_ALLOW_ALL_USERS",- cron_deliver_env_var="SMS_HOME_CHANNEL",- standalone_sender_fn=_standalone_send,- max_message_length=MAX_SMS_LENGTH,- pii_safe=True,- emoji="📱",- allow_update_command=True,- )+ install_hint="pip install aiohttp", allowed_users_env="SMS_ALLOWED_USERS",+ allow_all_env="SMS_ALLOW_ALL_USERS", cron_deliver_env_var="SMS_HOME_CHANNEL",+ standalone_sender_fn=_standalone_send, max_message_length=MAX_SMS_LENGTH, pii_safe=True,+ emoji="📱", allow_update_command=True)