Skip to content

The agent that grows with you

refactor(tools): group I — inline trivial HA wrappers, fold feishu _prepare into factory, docstring compaction

Teknium1265b24bc639
diff --git a/tools/discord_tool.py b/tools/discord_tool.py
index 161979d083f..d2a051a89a5 100644
--- a/tools/discord_tool.py
+++ b/tools/discord_tool.py
@@ -63,8 +63,7 @@ def _discord_request(
req = urllib.request.Request(
url, data=None if body is None else json.dumps(body).encode("utf-8"), method=method,
headers={
- "Authorization": f"Bot {token}",
- "Content-Type": "application/json",
+ "Authorization": f"Bot {token}", "Content-Type": "application/json",
"User-Agent": "Hermes-Agent (https://github.com/NousResearch/hermes-agent)"})
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
@@ -93,7 +92,6 @@ def _channel_type_name(type_id: int) -> str:
# ── capability detection (application intents) ──────────────────────────────
-
# Per-token in-process cache: the app/me endpoint is hit at most once per process.
_capability_cache: Dict[str, Dict[str, Any]] = {}
@@ -113,7 +111,6 @@ _PERMISSIVE_CAPS = {"has_members_intent": True, "has_message_content": True, "de
def _capability_disk_cache_path() -> Path:
from hermes_constants import get_hermes_home
-
return get_hermes_home() / "cache" / "discord_capabilities.json"
@@ -159,12 +156,9 @@ def _save_caps_to_disk(token: str, caps: Dict[str, Any]) -> None:
def _detect_capabilities_nonblocking(token: str) -> Dict[str, Any]:
- """Non-blocking capability lookup for schema builds.
-
- Order: in-process cache → fresh disk cache → permissive default plus a fire-and-forget
- background detection that fills the disk cache for the NEXT process (the blocking
- HTTPS call, ~2-5s, must stay off the cold-start critical path).
- """
+ """Schema-build lookup: in-process cache → fresh disk cache → permissive default plus a
+ fire-and-forget background detection that fills the disk cache for the NEXT process
+ (the ~2-5s blocking HTTPS call must stay off the cold-start critical path)."""
cached = _capability_cache.get(token)
if cached is not None:
return cached
@@ -229,8 +223,6 @@ def _reset_capability_cache() -> None:
# ── action implementations ───────────────────────────────────────────────────
-
-
def _listing(key: str, items: List[Dict[str, Any]]) -> str:
return json.dumps({key: items, "count": len(items)})
@@ -239,15 +231,11 @@ def _member_summary(m: Dict[str, Any], *, full: bool) -> Dict[str, Any]:
"""Member row; ``full`` adds the avatar/join fields member_info exposes
(key order is part of the result text, so the two shapes stay explicit)."""
user = m.get("user", {})
- base = {
- "user_id": user.get("id"), "username": user.get("username"),
- "display_name": user.get("global_name"), "nickname": m.get("nick")}
- tail = {"bot": user.get("bot", False), "roles": m.get("roles", [])}
- if not full:
- return {**base, **tail}
- return {
- **base, "avatar": user.get("avatar"), **tail,
- "joined_at": m.get("joined_at"), "premium_since": m.get("premium_since")}
+ row = {
+ "user_id": user.get("id"), "username": user.get("username"), "display_name": user.get("global_name"),
+ "nickname": m.get("nick"), "avatar": user.get("avatar"), "bot": user.get("bot", False),
+ "roles": m.get("roles", []), "joined_at": m.get("joined_at"), "premium_since": m.get("premium_since")}
+ return row if full else {k: v for k, v in row.items() if k not in ("avatar", "joined_at", "premium_since")}
def _message_summary(msg: Dict[str, Any]) -> Dict[str, Any]:
@@ -375,10 +363,10 @@ def _create_thread(
auto_archive_duration: int = 1440, **_kwargs: Any) -> str:
"""Create a thread — anchored to ``message_id`` when given, else standalone public."""
body: Dict[str, Any] = {"name": name, "auto_archive_duration": auto_archive_duration}
+ path = f"/channels/{channel_id}/threads"
if message_id:
path = f"/channels/{channel_id}/messages/{message_id}/threads"
else:
- path = f"/channels/{channel_id}/threads"
body["type"] = 11 # PUBLIC_THREAD
thread = _discord_request("POST", path, token, body=body)
return json.dumps({"success": True, "thread_id": thread["id"], "name": thread.get("name")})
@@ -404,7 +392,6 @@ _remove_role = _mutation(
# ── action dispatch + metadata ───────────────────────────────────────────────
-
# Single source of truth: (action, handler, required-param signature, description). Order is
# the schema/enum order; the signature drives runtime required-param validation.
_ACTION_MANIFEST = [
@@ -475,7 +462,6 @@ def _available_actions(caps: Dict[str, Any], allowlist: Optional[List[str]]) ->
# ── schema construction ──────────────────────────────────────────────────────
-
_TOOL_DESCRIPTIONS = {
"discord_admin": (
"Manage a Discord server via the REST API.",
@@ -560,7 +546,6 @@ get_dynamic_schema_admin = functools.partial(_get_dynamic_schema, _ADMIN_ACTIONS
# ── 403 error enrichment ─────────────────────────────────────────────────────
-
_NO_MANAGE_MESSAGES = "Bot lacks MANAGE_MESSAGES permission in this channel"
_VIEW_HISTORY = "Bot cannot view this channel (missing VIEW_CHANNEL or READ_MESSAGE_HISTORY)."
_ROLE_HIERARCHY = "Either the bot lacks MANAGE_ROLES, or the target role sits higher than the bot's highest role."
@@ -598,7 +583,6 @@ def check_discord_tool_requirements() -> bool:
# ── handlers ─────────────────────────────────────────────────────────────────
-
_HANDLER_DEFAULTS = {
"guild_id": "", "channel_id": "", "user_id": "", "role_id": "", "message_id": "", "query": "",
"name": "", "limit": 50, "before": "", "after": "", "auto_archive_duration": 1440}
diff --git a/tools/drive_preview_tool.py b/tools/drive_preview_tool.py
index bda96fb2210..a05af03343c 100644
--- a/tools/drive_preview_tool.py
+++ b/tools/drive_preview_tool.py
@@ -1,13 +1,11 @@
#!/usr/bin/env python3
-"""Interact with the in-app browser / preview pane in the Hermes desktop GUI.
+"""Interact with the in-app browser / preview pane in the Hermes desktop GUI (click, type, scroll).
-``open_preview`` shows a page, ``read_preview`` reads it; this is the third leg — clicking,
-typing, scrolling, history. Elements are addressed by legible refs from ``action="elements"``
-(``btn-sign-in``); a ref survives re-renders and only a navigation retires it, so the renderer
-answers with a *delta* (appeared/went/changed/rebound) instead of re-sending the inventory.
-Round-trips through the gateway's blocking-prompt bridge (``preview.act.request`` /
-``preview.act.respond``); this module is schema + a thin dispatcher over the platform-injected
-callback. Lives in the ``desktop_ui`` toolset (GUI gateway, desktop-sourced sessions only).
+Elements are addressed by legible refs from ``action="elements"`` (``btn-sign-in``); a ref survives
+re-renders and only a navigation retires it, so the renderer answers with a *delta* instead of
+re-sending the inventory. Round-trips through the gateway's blocking-prompt bridge
+(``preview.act.request`` / ``preview.act.respond``); this module is schema + a thin dispatcher over
+the platform-injected callback. ``desktop_ui`` toolset: desktop-sourced sessions only.
"""
from typing import Callable, Optional
@@ -24,16 +22,9 @@ NEEDS_TARGET = ("click", "hover", "type", "press")
def drive_preview_tool(
- action: str = "",
- ref: Optional[str] = None,
- selector: Optional[str] = None,
- text: Optional[str] = None,
- key: Optional[str] = None,
- submit: Optional[bool] = None,
- amount: Optional[int] = None,
- to: Optional[str] = None,
- limit: Optional[int] = None,
- full: Optional[bool] = None,
+ action: str = "", ref: Optional[str] = None, selector: Optional[str] = None, text: Optional[str] = None,
+ key: Optional[str] = None, submit: Optional[bool] = None, amount: Optional[int] = None,
+ to: Optional[str] = None, limit: Optional[int] = None, full: Optional[bool] = None,
callback: Optional[Callable] = None) -> str:
"""Dispatch one interaction to the desktop renderer and return its outcome."""
if callback is None:
diff --git a/tools/feishu_drive_tool.py b/tools/feishu_drive_tool.py
index f9a229db983..e1ba075d541 100644
--- a/tools/feishu_drive_tool.py
+++ b/tools/feishu_drive_tool.py
@@ -18,27 +18,19 @@ from tools.registry import registry, tool_error, tool_result
logger = logging.getLogger(__name__)
-def _prepare(args: dict, keys: tuple, missing_msg: str):
- """Client check first, then required fields (stripped). Returns (client, values, error|None)."""
- client = get_client()
- values = tuple(args.get(k, "").strip() for k in keys)
- if client is None:
- return None, values, tool_error("Feishu client not available")
- if not all(values):
- return client, values, tool_error(missing_msg)
- return client, values, None
-
-
def _comment_op(keys, missing_msg, label, method, uri, queries=None, body=None, flag_success=False):
- """Handler factory: validate ``keys`` → lark_call → ``"{label} failed"`` or the data.
+ """Handler factory: client check, then required ``keys`` (stripped) → lark_call → result.
All keys except ``content`` are URI path params. ``queries(args)`` / ``body(args, values)``
build the request pieces; ``flag_success`` adds ``success=True`` to the result (writes).
"""
def _handler(args: dict, **kwargs) -> str:
- client, values, err = _prepare(args, keys, missing_msg)
- if err:
- return err
+ client = get_client()
+ values = tuple(args.get(k, "").strip() for k in keys)
+ if client is None:
+ return tool_error("Feishu client not available")
+ if not all(values):
+ return tool_error(missing_msg)
code, msg, data = lark_call(
client, method, uri, paths={k: v for k, v in zip(keys, values) if k != "content"},
queries=queries and queries(args), body=body and body(args, values))
@@ -186,7 +178,8 @@ _handle_reply_comment = _comment_op(
# new_comments takes the flat "reply_elements[text]" shape with file_type in the body.
_handle_add_comment = _comment_op(
("file_token", "content"), "file_token and content are required", "Add comment", "POST",
- _ADD_COMMENT_URI, body=lambda a, v: {"file_type": _file_type(a), "reply_elements": [{"type": "text", "text": v[-1]}]},
+ _ADD_COMMENT_URI,
+ body=lambda a, v: {"file_type": _file_type(a), "reply_elements": [{"type": "text", "text": v[-1]}]},
flag_success=True)
diff --git a/tools/feishu_lark.py b/tools/feishu_lark.py
index 2077e75a33f..539f79d8080 100644
--- a/tools/feishu_lark.py
+++ b/tools/feishu_lark.py
@@ -67,24 +67,20 @@ def lark_call(client, method, uri, paths=None, queries=None, body=None):
def raw_body(response):
"""Parsed JSON object of the raw HTTP body, or None when absent/unparseable/not a dict."""
raw = getattr(response, "raw", None)
- if raw and hasattr(raw, "content"):
- try:
- body = json.loads(raw.content)
- except (json.JSONDecodeError, AttributeError):
- return None
- if isinstance(body, dict):
- return body
- return None
+ try:
+ body = json.loads(raw.content) if raw and hasattr(raw, "content") else None
+ except (json.JSONDecodeError, AttributeError):
+ return None
+ return body if isinstance(body, dict) else None
def response_data(response) -> dict:
"""``data`` of a lark response: prefer the raw JSON body, fall back to typed .data."""
body = raw_body(response)
data = body.get("data", {}) if body is not None else {}
- if not data:
- resp_data = getattr(response, "data", None)
- if isinstance(resp_data, dict):
- data = resp_data
- elif resp_data and hasattr(resp_data, "__dict__"):
- data = vars(resp_data)
- return data
+ if data:
+ return data
+ resp_data = getattr(response, "data", None)
+ if isinstance(resp_data, dict):
+ return resp_data
+ return vars(resp_data) if resp_data and hasattr(resp_data, "__dict__") else data
diff --git a/tools/homeassistant_tool.py b/tools/homeassistant_tool.py
index a70c15d6dbc..d3fae6a9128 100644
--- a/tools/homeassistant_tool.py
+++ b/tools/homeassistant_tool.py
@@ -58,7 +58,6 @@ def _get_headers(token: str = "") -> Dict[str, str]:
async def _api_json(method: str, path: str, timeout: float, payload: Any = None) -> Any:
"""One HA REST call (GET or POST JSON) that raises on HTTP errors and returns the JSON body."""
import aiohttp
-
hass_url, hass_token = _get_config()
kwargs: Dict[str, Any] = {"headers": _get_headers(hass_token), "timeout": aiohttp.ClientTimeout(total=timeout)}
if method == "POST":
@@ -70,8 +69,7 @@ async def _api_json(method: str, path: str, timeout: float, payload: Any = None)
# ── async helpers (called from sync handlers via _run_async) ─────────────────
-
-def _filter_and_summarize(states: list, domain: Optional[str] = None, area: Optional[str] = None) -> Dict[str, Any]:
+def _filter_and_summarize(states: list, domain: Optional[str] = None, area: Optional[str] = None) -> Dict:
"""Filter raw HA states by domain/area (area matches friendly_name or area attr) and compact them."""
if domain:
states = [s for s in states if s.get("entity_id", "").startswith(f"{domain}.")]
@@ -96,14 +94,11 @@ async def _async_list_entities(domain: Optional[str] = None, area: Optional[str]
async def _async_get_state(entity_id: str) -> Dict[str, Any]:
data = await _api_json("GET", f"/api/states/{entity_id}", 10)
return {
- "entity_id": data["entity_id"],
- "state": data["state"],
- "attributes": data.get("attributes", {}),
- "last_changed": data.get("last_changed"),
- "last_updated": data.get("last_updated")}
+ "entity_id": data["entity_id"], "state": data["state"], "attributes": data.get("attributes", {}),
+ "last_changed": data.get("last_changed"), "last_updated": data.get("last_updated")}
-def _build_service_payload(entity_id: Optional[str] = None, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
+def _build_service_payload(entity_id: Optional[str] = None, data: Optional[Dict[str, Any]] = None) -> Dict:
"""JSON payload for a HA service call; ``entity_id`` overrides data["entity_id"]."""
payload: Dict[str, Any] = dict(data or {})
if entity_id:
@@ -138,21 +133,21 @@ async def _async_list_services(domain: Optional[str] = None) -> Dict[str, Any]:
svc_entry: Dict[str, Any] = {"description": svc_info.get("description", "")}
fields = svc_info.get("fields", {})
if fields:
- svc_entry["fields"] = {k: v.get("description", "") for k, v in fields.items() if isinstance(v, dict)}
+ svc_entry["fields"] = {
+ k: v.get("description", "") for k, v in fields.items() if isinstance(v, dict)}
domain_services[svc_name] = svc_entry
result.append({"domain": svc_domain.get("domain", ""), "services": domain_services})
return {"count": len(result), "domains": result}
# ── sync wrappers (handler signature: (args, **kw) -> str) ───────────────────
-
def _run_async(coro):
"""Run a coroutine from a sync handler; hops to a thread if a loop is already running."""
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = None
- if loop and loop.is_running():
+ if loop and loop.is_running(): # already inside a loop: asyncio.run() needs its own thread
import concurrent.futures
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
return pool.submit(asyncio.run, coro).result(timeout=30)
@@ -168,12 +163,6 @@ def _dispatch(coro, log_name: str, fail_msg: str) -> str:
return tool_error(f"{fail_msg}: {e}")
-def _handle_list_entities(args: dict, **kw) -> str:
- return _dispatch(
- _async_list_entities(domain=args.get("domain"), area=args.get("area")),
- "ha_list_entities", "Failed to list entities")
-
-
def _handle_get_state(args: dict, **kw) -> str:
entity_id = args.get("entity_id", "")
if not entity_id:
@@ -211,18 +200,12 @@ def _handle_call_service(args: dict, **kw) -> str:
"ha_call_service", f"Failed to call {domain}.{service}")
-def _handle_list_services(args: dict, **kw) -> str:
- return _dispatch(
- _async_list_services(domain=args.get("domain")), "ha_list_services", "Failed to list services")
-
-
def _check_ha_available() -> bool:
"""Tool is only available when HASS_TOKEN is set."""
return bool(get_secret("HASS_TOKEN"))
# ── tool schemas ─────────────────────────────────────────────────────────────
-
HA_LIST_ENTITIES_SCHEMA = {
"name": "ha_list_entities",
"description": (
@@ -344,9 +327,12 @@ HA_CALL_SERVICE_SCHEMA = {
for _schema, _handler in (
- (HA_LIST_ENTITIES_SCHEMA, _handle_list_entities),
+ (HA_LIST_ENTITIES_SCHEMA, lambda args, **kw: _dispatch(
+ _async_list_entities(domain=args.get("domain"), area=args.get("area")),
+ "ha_list_entities", "Failed to list entities")),
(HA_GET_STATE_SCHEMA, _handle_get_state),
- (HA_LIST_SERVICES_SCHEMA, _handle_list_services),
+ (HA_LIST_SERVICES_SCHEMA, lambda args, **kw: _dispatch(
+ _async_list_services(domain=args.get("domain")), "ha_list_services", "Failed to list services")),
(HA_CALL_SERVICE_SCHEMA, _handle_call_service)):
registry.register(
name=_schema["name"], toolset="homeassistant", schema=_schema, handler=_handler,