From 552adbe0827c32df8ed9bb19e908c26eff43add7 Mon Sep 17 00:00:00 2001 From: teknium1 <127238744+teknium1@users.noreply.github.com> Date: Sun, 7 Jun 2026 05:17:57 -0700 Subject: [PATCH] refactor(gateway): migrate feishu adapter (+ satellites) to bundled plugin WIP toward #41112. Feishu adapter + its feishu_comment / feishu_comment_rules / feishu_meeting_invite satellites relocated to plugins/platforms/feishu/ with internal imports rewritten to the new package path. register() exposes the platform with standalone_sender_fn (adapter-based send incl native media: images/video/voice/documents), apply_yaml_config_fn (allow_bots bridge), setup_fn (full QR-register + manual + DM/group-policy wizard), is_connected (app_id). Core touchpoints stripped: run.py elif, config.py feishu YAML bridge + _PLATFORM_CONNECTED_CHECKERS entry, gateway.py static dict + _setup_feishu + setup-map entry, send_message_tool _send_feishu + text dispatch + native-media branch (now via registry standalone_sender_fn) + FeishuAdapter MAX_LENGTHS import (registry max_message_length=8000 covers it). telegram still to come (the last one). --- gateway/config.py | 9 +- gateway/run.py | 7 - hermes_cli/gateway.py | 252 +-------------- plugins/platforms/feishu/__init__.py | 3 + .../platforms/feishu/adapter.py | 302 +++++++++++++++++- .../platforms/feishu}/feishu_comment.py | 2 +- .../platforms/feishu}/feishu_comment_rules.py | 0 .../feishu}/feishu_meeting_invite.py | 0 plugins/platforms/feishu/plugin.yaml | 44 +++ tools/send_message_tool.py | 84 +---- 10 files changed, 375 insertions(+), 328 deletions(-) create mode 100644 plugins/platforms/feishu/__init__.py rename gateway/platforms/feishu.py => plugins/platforms/feishu/adapter.py (94%) rename {gateway/platforms => plugins/platforms/feishu}/feishu_comment.py (99%) rename {gateway/platforms => plugins/platforms/feishu}/feishu_comment_rules.py (100%) rename {gateway/platforms => plugins/platforms/feishu}/feishu_meeting_invite.py (100%) create mode 100644 plugins/platforms/feishu/plugin.yaml diff --git a/gateway/config.py b/gateway/config.py index d4b3c36b1fb6..76f6ed098fcf 100644 --- a/gateway/config.py +++ b/gateway/config.py @@ -433,7 +433,6 @@ _PLATFORM_CONNECTED_CHECKERS: dict[Platform, Callable[[PlatformConfig], bool]] = Platform.MSGRAPH_WEBHOOK: lambda cfg: bool( str(cfg.extra.get("client_state") or "").strip() ), - Platform.FEISHU: lambda cfg: bool(cfg.extra.get("app_id")), Platform.WECOM: lambda cfg: bool(cfg.extra.get("bot_id")), Platform.WECOM_CALLBACK: lambda cfg: bool( cfg.extra.get("corp_id") or cfg.extra.get("apps") @@ -1113,11 +1112,9 @@ def load_gateway_config() -> GatewayConfig: # apply_yaml_config_fn hook (plugins/platforms/matrix/adapter.py). # #41112 / #3823. - # Feishu settings β†’ env vars (env vars take precedence) - feishu_cfg = yaml_cfg.get("feishu", {}) - if isinstance(feishu_cfg, dict): - if "allow_bots" in feishu_cfg and not os.getenv("FEISHU_ALLOW_BOTS"): - os.environ["FEISHU_ALLOW_BOTS"] = str(feishu_cfg["allow_bots"]).lower() + # Feishu settings β†’ env vars: migrated to the feishu plugin's + # apply_yaml_config_fn hook (plugins/platforms/feishu/adapter.py). + # #41112 / #3823. except Exception as e: logger.warning( diff --git a/gateway/run.py b/gateway/run.py index eb453aebb690..9b79e7597a5b 100644 --- a/gateway/run.py +++ b/gateway/run.py @@ -6921,13 +6921,6 @@ class GatewayRunner: return None return SmsAdapter(config) - elif platform == Platform.FEISHU: - from gateway.platforms.feishu import FeishuAdapter, check_feishu_requirements - if not check_feishu_requirements(): - logger.warning("Feishu: lark-oapi not installed or FEISHU_APP_ID/SECRET not set") - return None - return FeishuAdapter(config) - elif platform == Platform.WECOM_CALLBACK: from gateway.platforms.wecom_callback import ( WecomCallbackAdapter, diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py index 3cc1835e3a08..ffee053eff5d 100644 --- a/hermes_cli/gateway.py +++ b/hermes_cli/gateway.py @@ -4033,59 +4033,9 @@ _PLATFORMS = [ # DingTalk moved to plugins/platforms/dingtalk/ β€” setup metadata discovered # dynamically via the platform registry entry registered by # plugins/platforms/dingtalk/adapter.py::register(). #41112. - { - "key": "feishu", - "label": "Feishu / Lark", - "emoji": "πŸͺ½", - "token_var": "FEISHU_APP_ID", - "setup_instructions": [ - "1. Go to https://open.feishu.cn/ (or https://open.larksuite.com/ for Lark)", - "2. Create an app and copy the App ID and App Secret", - "3. Enable the Bot capability for the app", - "4. Choose WebSocket (recommended) or Webhook connection mode", - "5. Add the bot to a group chat or message it directly", - "6. Restrict access with FEISHU_ALLOWED_USERS for production use", - ], - "vars": [ - { - "name": "FEISHU_APP_ID", - "prompt": "App ID", - "password": False, - "help": "The App ID from your Feishu/Lark application.", - }, - { - "name": "FEISHU_APP_SECRET", - "prompt": "App Secret", - "password": True, - "help": "The App Secret from your Feishu/Lark application.", - }, - { - "name": "FEISHU_DOMAIN", - "prompt": "Domain β€” feishu or lark (default: feishu)", - "password": False, - "help": "Use 'feishu' for Feishu China, or 'lark' for Lark international.", - }, - { - "name": "FEISHU_CONNECTION_MODE", - "prompt": "Connection mode β€” websocket or webhook (default: websocket)", - "password": False, - "help": "websocket is recommended unless you specifically need webhook mode.", - }, - { - "name": "FEISHU_ALLOWED_USERS", - "prompt": "Allowed user IDs (comma-separated, or empty)", - "password": False, - "is_allowlist": True, - "help": "Restrict which Feishu/Lark users can interact with the bot.", - }, - { - "name": "FEISHU_HOME_CHANNEL", - "prompt": "Home chat ID (optional, for cron/notifications)", - "password": False, - "help": "Chat ID for scheduled results and notifications.", - }, - ], - }, + # Feishu moved to plugins/platforms/feishu/ β€” setup metadata discovered + # dynamically via the platform registry entry registered by + # plugins/platforms/feishu/adapter.py::register(). #41112. { "key": "wecom", "label": "WeCom (Enterprise WeChat)", @@ -5007,197 +4957,8 @@ def _setup_weixin(): print_info(f" User ID: {user_id}") -def _setup_feishu(): - """Interactive setup for Feishu / Lark β€” scan-to-create or manual credentials.""" - print() - print(color(" ─── πŸͺ½ Feishu / Lark Setup ───", Colors.CYAN)) - - existing_app_id = get_env_value("FEISHU_APP_ID") - existing_secret = get_env_value("FEISHU_APP_SECRET") - if existing_app_id and existing_secret: - print() - print_success("Feishu / Lark is already configured.") - if not prompt_yes_no(" Reconfigure Feishu / Lark?", False): - return - - # ── Choose setup method ── - print() - method_choices = [ - "Scan QR code to create a new bot automatically (recommended)", - "Enter existing App ID and App Secret manually", - ] - method_idx = prompt_choice( - " How would you like to set up Feishu / Lark?", method_choices, 0 - ) - - credentials = None - used_qr = False - - if method_idx == 0: - # ── QR scan-to-create ── - try: - from gateway.platforms.feishu import qr_register - except Exception as exc: - print_error(f" Feishu / Lark onboard import failed: {exc}") - qr_register = None - - if qr_register is not None: - try: - credentials = qr_register() - except KeyboardInterrupt: - print() - print_warning(" Feishu / Lark setup cancelled.") - return - except Exception as exc: - print_warning(f" QR registration failed: {exc}") - if credentials: - used_qr = True - if not credentials: - print_info(" QR setup did not complete. Continuing with manual input.") - - # ── Manual credential input ── - if not credentials: - print() - print_info( - " Go to https://open.feishu.cn/ (or https://open.larksuite.com/ for Lark)" - ) - print_info( - " Create an app, enable the Bot capability, and copy the credentials." - ) - print() - app_id = prompt(" App ID", password=False) - if not app_id: - print_warning(" Skipped β€” Feishu / Lark won't work without an App ID.") - return - app_secret = prompt(" App Secret", password=True) - if not app_secret: - print_warning(" Skipped β€” Feishu / Lark won't work without an App Secret.") - return - - domain_choices = ["feishu (China)", "lark (International)"] - domain_idx = prompt_choice(" Domain", domain_choices, 0) - domain = "lark" if domain_idx == 1 else "feishu" - - # Try to probe the bot with manual credentials - bot_name = None - try: - from gateway.platforms.feishu import probe_bot - - bot_info = probe_bot(app_id, app_secret, domain) - if bot_info: - bot_name = bot_info.get("bot_name") - print_success(f" Credentials verified β€” bot: {bot_name or 'unnamed'}") - else: - print_warning( - " Could not verify bot connection. Credentials saved anyway." - ) - except Exception as exc: - print_warning(f" Credential verification skipped: {exc}") - - credentials = { - "app_id": app_id, - "app_secret": app_secret, - "domain": domain, - "open_id": None, - "bot_name": bot_name, - } - - # ── Save core credentials ── - app_id = credentials["app_id"] - app_secret = credentials["app_secret"] - domain = credentials.get("domain", "feishu") - open_id = credentials.get("open_id") - bot_name = credentials.get("bot_name") - - save_env_value("FEISHU_APP_ID", app_id) - save_env_value("FEISHU_APP_SECRET", app_secret) - save_env_value("FEISHU_DOMAIN", domain) - # Bot identity is resolved at runtime via _hydrate_bot_identity(). - - # ── Connection mode ── - if used_qr: - connection_mode = "websocket" - else: - print() - mode_choices = [ - "WebSocket (recommended β€” no public URL needed)", - "Webhook (requires a reachable HTTP endpoint)", - ] - mode_idx = prompt_choice(" Connection mode", mode_choices, 0) - connection_mode = "webhook" if mode_idx == 1 else "websocket" - if connection_mode == "webhook": - print_info(" Webhook defaults: 127.0.0.1:8765/feishu/webhook") - print_info( - " Override with FEISHU_WEBHOOK_HOST / FEISHU_WEBHOOK_PORT / FEISHU_WEBHOOK_PATH" - ) - print_info( - " For signature verification, set FEISHU_ENCRYPT_KEY and FEISHU_VERIFICATION_TOKEN" - ) - save_env_value("FEISHU_CONNECTION_MODE", connection_mode) - - if bot_name: - print() - print_success(f" Bot created: {bot_name}") - - # ── DM security policy ── - print() - access_choices = [ - "Use DM pairing approval (recommended)", - "Allow all direct messages", - "Only allow listed user IDs", - ] - access_idx = prompt_choice( - " How should direct messages be authorized?", access_choices, 0 - ) - if access_idx == 0: - save_env_value("FEISHU_ALLOW_ALL_USERS", "false") - save_env_value("FEISHU_ALLOWED_USERS", "") - print_success(" DM pairing enabled.") - print_info( - " Unknown users can request access; approve with `hermes pairing approve`." - ) - elif access_idx == 1: - save_env_value("FEISHU_ALLOW_ALL_USERS", "true") - save_env_value("FEISHU_ALLOWED_USERS", "") - print_warning(" Open DM access enabled for Feishu / Lark.") - else: - save_env_value("FEISHU_ALLOW_ALL_USERS", "false") - default_allow = open_id or "" - allowlist = prompt( - " Allowed user IDs (comma-separated)", default_allow, password=False - ).replace(" ", "") - save_env_value("FEISHU_ALLOWED_USERS", allowlist) - print_success(" Allowlist saved.") - - # ── Group policy ── - print() - group_choices = [ - "Respond only when @mentioned in groups (recommended)", - "Disable group chats", - ] - group_idx = prompt_choice(" How should group chats be handled?", group_choices, 0) - if group_idx == 0: - save_env_value("FEISHU_GROUP_POLICY", "open") - print_info(" Group chats enabled (bot must be @mentioned).") - else: - save_env_value("FEISHU_GROUP_POLICY", "disabled") - print_info(" Group chats disabled.") - - # ── Home channel ── - print() - home_channel = prompt( - " Home chat ID (optional, for cron/notifications)", password=False - ) - if home_channel: - save_env_value("FEISHU_HOME_CHANNEL", home_channel) - print_success(f" Home channel set to {home_channel}") - - print() - print_success("πŸͺ½ Feishu / Lark configured!") - print_info(f" App ID: {app_id}") - print_info(f" Domain: {domain}") - if bot_name: - print_info(f" Bot: {bot_name}") +# _setup_feishu moved to plugins/platforms/feishu/adapter.py::interactive_setup +# (registered via setup_fn, dispatched through the plugin path). #41112. def _setup_qqbot(): @@ -5484,7 +5245,8 @@ def _builtin_setup_fn(key: str): # plugins/platforms/{whatsapp,dingtalk}/adapter.py::register() and # dispatched via the plugin path in _configure_platform(). #41112. "weixin": _setup_weixin, - "feishu": _setup_feishu, + # feishu moved into the plugin: setup_fn registered by + # plugins/platforms/feishu/adapter.py::register(). #41112. "wecom": _setup_wecom, "qqbot": _setup_qqbot, }.get(key) diff --git a/plugins/platforms/feishu/__init__.py b/plugins/platforms/feishu/__init__.py new file mode 100644 index 000000000000..d4f1d7bf0e3f --- /dev/null +++ b/plugins/platforms/feishu/__init__.py @@ -0,0 +1,3 @@ +from .adapter import register + +__all__ = ["register"] diff --git a/gateway/platforms/feishu.py b/plugins/platforms/feishu/adapter.py similarity index 94% rename from gateway/platforms/feishu.py rename to plugins/platforms/feishu/adapter.py index b361ebc8cfcc..f3abd77f1091 100644 --- a/gateway/platforms/feishu.py +++ b/plugins/platforms/feishu/adapter.py @@ -2467,7 +2467,7 @@ class FeishuAdapter(BasePlatformAdapter): logging, and reaction. Scheduling follows the same ``run_coroutine_threadsafe`` pattern used by ``_on_message_event``. """ - from gateway.platforms.feishu_comment import handle_drive_comment_event + from plugins.platforms.feishu.feishu_comment import handle_drive_comment_event loop = self._loop if not self._loop_accepts_callbacks(loop): @@ -2480,7 +2480,7 @@ class FeishuAdapter(BasePlatformAdapter): def _on_meeting_invited_event(self, data: Any) -> None: """Handle VC bot meeting invitation notification (vc.bot.meeting_invited_v1).""" - from gateway.platforms.feishu_meeting_invite import handle_meeting_invited_event + from plugins.platforms.feishu.feishu_meeting_invite import handle_meeting_invited_event loop = self._loop if not self._loop_accepts_callbacks(loop): @@ -5209,3 +5209,301 @@ def _qr_register_inner( result["bot_open_id"] = None return result + + +# ────────────────────────────────────────────────────────────────────────── +# Plugin migration glue (#41112 / #3823) +# +# Added when the Feishu adapter (+ its feishu_comment / feishu_comment_rules / +# feishu_meeting_invite satellites) moved from gateway/platforms/ into this +# bundled plugin. Mirrors the Discord (#24356) / Slack migrations: a +# register(ctx) entry point plus hook implementations that replace the +# per-platform core touchpoints (the Platform.FEISHU elif in gateway/run.py, +# the feishu_cfg YAMLβ†’env block + _PLATFORM_CONNECTED_CHECKERS entry in +# gateway/config.py, the _setup_feishu wizard + _PLATFORMS["feishu"] static +# dict in hermes_cli/gateway.py, and the _send_feishu dispatch in +# tools/send_message_tool.py). +# ────────────────────────────────────────────────────────────────────────── + +_MIGRATION_IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".gif"} +_MIGRATION_VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".3gp"} +_MIGRATION_AUDIO_EXTS = {".ogg", ".opus", ".mp3", ".wav", ".m4a", ".flac"} +_MIGRATION_VOICE_EXTS = {".ogg", ".opus"} + + +async def _standalone_send( + pconfig, + chat_id, + message, + *, + thread_id=None, + media_files=None, + force_document=False, +): + """Out-of-process Feishu/Lark delivery via the adapter's send pipeline. + + Implements the standalone_sender_fn contract so deliver=feishu cron jobs + succeed when cron runs separately from the gateway. Builds a transient + FeishuAdapter, hydrates its lark client, and sends text + native media + (images, video, voice, documents). Replaces the legacy _send_feishu helper. + """ + if not FEISHU_AVAILABLE: + return {"error": "Feishu dependencies not installed. Run: pip install 'hermes-agent[feishu]'"} + + media_files = media_files or [] + try: + adapter = FeishuAdapter(pconfig) + domain_name = getattr(adapter, "_domain_name", "feishu") + domain = FEISHU_DOMAIN if domain_name != "lark" else LARK_DOMAIN + adapter._client = adapter._build_lark_client(domain) + metadata = {"thread_id": thread_id} if thread_id else None + + last_result = None + if message.strip(): + last_result = await adapter.send(chat_id, message, metadata=metadata) + if not last_result.success: + return {"error": f"Feishu send failed: {last_result.error}"} + + for media_path, is_voice in media_files: + if not os.path.exists(media_path): + return {"error": f"Media file not found: {media_path}"} + ext = os.path.splitext(media_path)[1].lower() + if ext in _MIGRATION_IMAGE_EXTS: + last_result = await adapter.send_image_file(chat_id, media_path, metadata=metadata) + elif ext in _MIGRATION_VIDEO_EXTS: + last_result = await adapter.send_video(chat_id, media_path, metadata=metadata) + elif ext in _MIGRATION_VOICE_EXTS and is_voice: + last_result = await adapter.send_voice(chat_id, media_path, metadata=metadata) + elif ext in _MIGRATION_AUDIO_EXTS: + last_result = await adapter.send_voice(chat_id, media_path, metadata=metadata) + else: + last_result = await adapter.send_document(chat_id, media_path, metadata=metadata) + if not last_result.success: + return {"error": f"Feishu media send failed: {last_result.error}"} + + if last_result is None: + return {"error": "No deliverable text or media remained after processing MEDIA tags"} + return { + "success": True, + "platform": "feishu", + "chat_id": chat_id, + "message_id": last_result.message_id, + } + except Exception as e: + return {"error": f"Feishu send failed: {e}"} + + +def interactive_setup() -> None: + """Interactive setup for Feishu / Lark β€” scan-to-create or manual creds. + + Replaces the central _setup_feishu in hermes_cli/gateway.py and the static + _PLATFORMS["feishu"] dict. CLI helpers are lazy-imported. + """ + from hermes_cli.config import get_env_value, save_env_value + from hermes_cli.cli_output import ( + prompt, + prompt_choice, + prompt_yes_no, + print_header, + print_info, + print_success, + print_warning, + print_error, + ) + + print_header("Feishu / Lark") + existing_app_id = get_env_value("FEISHU_APP_ID") + existing_secret = get_env_value("FEISHU_APP_SECRET") + if existing_app_id and existing_secret: + print_success("Feishu / Lark is already configured.") + if not prompt_yes_no("Reconfigure Feishu / Lark?", False): + return + + method_idx = prompt_choice( + "How would you like to set up Feishu / Lark?", + [ + "Scan QR code to create a new bot automatically (recommended)", + "Enter existing App ID and App Secret manually", + ], + 0, + ) + + credentials = None + used_qr = False + + if method_idx == 0: + try: + credentials = qr_register() + except KeyboardInterrupt: + print_warning("Feishu / Lark setup cancelled.") + return + except Exception as exc: + print_warning(f"QR registration failed: {exc}") + if credentials: + used_qr = True + else: + print_info("QR setup did not complete. Continuing with manual input.") + + if not credentials: + print_info("Go to https://open.feishu.cn/ (or https://open.larksuite.com/ for Lark)") + print_info("Create an app, enable the Bot capability, and copy the credentials.") + app_id = prompt("App ID", password=False) + if not app_id: + print_warning("Skipped β€” Feishu / Lark won't work without an App ID.") + return + app_secret = prompt("App Secret", password=True) + if not app_secret: + print_warning("Skipped β€” Feishu / Lark won't work without an App Secret.") + return + domain_idx = prompt_choice("Domain", ["feishu (China)", "lark (International)"], 0) + domain = "lark" if domain_idx == 1 else "feishu" + + bot_name = None + try: + bot_info = probe_bot(app_id, app_secret, domain) + if bot_info: + bot_name = bot_info.get("bot_name") + print_success(f"Credentials verified β€” bot: {bot_name or 'unnamed'}") + else: + print_warning("Could not verify bot connection. Credentials saved anyway.") + except Exception as exc: + print_warning(f"Credential verification skipped: {exc}") + + credentials = { + "app_id": app_id, + "app_secret": app_secret, + "domain": domain, + "open_id": None, + "bot_name": bot_name, + } + + app_id = credentials["app_id"] + app_secret = credentials["app_secret"] + domain = credentials.get("domain", "feishu") + open_id = credentials.get("open_id") + bot_name = credentials.get("bot_name") + + save_env_value("FEISHU_APP_ID", app_id) + save_env_value("FEISHU_APP_SECRET", app_secret) + save_env_value("FEISHU_DOMAIN", domain) + + if used_qr: + connection_mode = "websocket" + else: + mode_idx = prompt_choice( + "Connection mode", + [ + "WebSocket (recommended β€” no public URL needed)", + "Webhook (requires a reachable HTTP endpoint)", + ], + 0, + ) + connection_mode = "webhook" if mode_idx == 1 else "websocket" + if connection_mode == "webhook": + print_info("Webhook defaults: 127.0.0.1:8765/feishu/webhook") + print_info("Override with FEISHU_WEBHOOK_HOST / FEISHU_WEBHOOK_PORT / FEISHU_WEBHOOK_PATH") + print_info("For signature verification, set FEISHU_ENCRYPT_KEY and FEISHU_VERIFICATION_TOKEN") + save_env_value("FEISHU_CONNECTION_MODE", connection_mode) + + if bot_name: + print_success(f"Bot created: {bot_name}") + + access_idx = prompt_choice( + "How should direct messages be authorized?", + [ + "Use DM pairing approval (recommended)", + "Allow all direct messages", + "Only allow listed user IDs", + ], + 0, + ) + if access_idx == 0: + save_env_value("FEISHU_ALLOW_ALL_USERS", "false") + save_env_value("FEISHU_ALLOWED_USERS", "") + print_success("DM pairing enabled.") + print_info("Unknown users can request access; approve with `hermes pairing approve`.") + elif access_idx == 1: + save_env_value("FEISHU_ALLOW_ALL_USERS", "true") + save_env_value("FEISHU_ALLOWED_USERS", "") + print_warning("Open DM access enabled for Feishu / Lark.") + else: + save_env_value("FEISHU_ALLOW_ALL_USERS", "false") + default_allow = open_id or "" + allowlist = prompt( + "Allowed user IDs (comma-separated)", default_allow, password=False + ).replace(" ", "") + save_env_value("FEISHU_ALLOWED_USERS", allowlist) + print_success("Allowlist saved.") + + group_idx = prompt_choice( + "How should group chats be handled?", + [ + "Respond only when @mentioned in groups (recommended)", + "Disable group chats", + ], + 0, + ) + if group_idx == 0: + save_env_value("FEISHU_GROUP_POLICY", "open") + print_info("Group chats enabled (bot must be @mentioned).") + else: + save_env_value("FEISHU_GROUP_POLICY", "disabled") + print_info("Group chats disabled.") + + home_channel = prompt("Home chat ID (optional, for cron/notifications)", password=False) + if home_channel: + save_env_value("FEISHU_HOME_CHANNEL", home_channel) + print_success(f"Home channel set to {home_channel}") + + print_success("πŸͺ½ Feishu / Lark configured!") + print_info(f"App ID: {app_id}") + print_info(f"Domain: {domain}") + if bot_name: + print_info(f"Bot: {bot_name}") + + +def _apply_yaml_config(yaml_cfg: dict, feishu_cfg: dict) -> dict | None: + """Translate config.yaml feishu: keys into FEISHU_* env vars. + + Implements the apply_yaml_config_fn contract (#24849). Mirrors the legacy + feishu_cfg block from gateway/config.py::load_gateway_config() (allow_bots). + Env vars take precedence over YAML. Returns None β€” flows through env. + """ + if "allow_bots" in feishu_cfg and not os.getenv("FEISHU_ALLOW_BOTS"): + os.environ["FEISHU_ALLOW_BOTS"] = str(feishu_cfg["allow_bots"]).lower() + return None + + +def _is_connected(config) -> bool: + """Feishu is connected when app_id is configured. Mirrors the legacy + _PLATFORM_CONNECTED_CHECKERS[Platform.FEISHU] = lambda cfg: bool(app_id).""" + extra = getattr(config, "extra", {}) or {} + return bool(extra.get("app_id")) + + +def _build_adapter(config): + """Factory wrapper that constructs FeishuAdapter from a PlatformConfig.""" + return FeishuAdapter(config) + + +def register(ctx) -> None: + """Plugin entry point β€” called by the Hermes plugin system.""" + ctx.register_platform( + name="feishu", + label="Feishu / Lark", + adapter_factory=_build_adapter, + check_fn=check_feishu_requirements, + is_connected=_is_connected, + validate_config=_is_connected, + required_env=["FEISHU_APP_ID", "FEISHU_APP_SECRET"], + install_hint="pip install 'hermes-agent[feishu]'", + setup_fn=interactive_setup, + apply_yaml_config_fn=_apply_yaml_config, + allowed_users_env="FEISHU_ALLOWED_USERS", + allow_all_env="FEISHU_ALLOW_ALL_USERS", + cron_deliver_env_var="FEISHU_HOME_CHANNEL", + standalone_sender_fn=_standalone_send, + max_message_length=8000, + emoji="πŸͺ½", + allow_update_command=True, + ) diff --git a/gateway/platforms/feishu_comment.py b/plugins/platforms/feishu/feishu_comment.py similarity index 99% rename from gateway/platforms/feishu_comment.py rename to plugins/platforms/feishu/feishu_comment.py index 4d757cc76467..83b41469fdd9 100644 --- a/gateway/platforms/feishu_comment.py +++ b/plugins/platforms/feishu/feishu_comment.py @@ -1164,7 +1164,7 @@ async def handle_drive_comment_event( ) # Access control - from gateway.platforms.feishu_comment_rules import load_config, resolve_rule, is_user_allowed, has_wiki_keys + from plugins.platforms.feishu.feishu_comment_rules import load_config, resolve_rule, is_user_allowed, has_wiki_keys comments_cfg = load_config() rule = resolve_rule(comments_cfg, file_type, file_token) diff --git a/gateway/platforms/feishu_comment_rules.py b/plugins/platforms/feishu/feishu_comment_rules.py similarity index 100% rename from gateway/platforms/feishu_comment_rules.py rename to plugins/platforms/feishu/feishu_comment_rules.py diff --git a/gateway/platforms/feishu_meeting_invite.py b/plugins/platforms/feishu/feishu_meeting_invite.py similarity index 100% rename from gateway/platforms/feishu_meeting_invite.py rename to plugins/platforms/feishu/feishu_meeting_invite.py diff --git a/plugins/platforms/feishu/plugin.yaml b/plugins/platforms/feishu/plugin.yaml new file mode 100644 index 000000000000..0eabd947ea6c --- /dev/null +++ b/plugins/platforms/feishu/plugin.yaml @@ -0,0 +1,44 @@ +name: feishu-platform +label: Feishu / Lark +kind: platform +version: 1.0.0 +description: > + Feishu / Lark gateway adapter for Hermes Agent. + Connects to Feishu (China) or Lark (International) via the official + lark-oapi SDK over WebSocket or webhook and relays messages between + Feishu/Lark chats and the Hermes agent. Supports text, images, video, + voice, documents, threads, DM pairing, group @mention gating, drive + comment events, and meeting invites. +author: NousResearch +requires_env: + - name: FEISHU_APP_ID + description: "Feishu/Lark app ID" + prompt: "Feishu App ID" + url: "https://open.feishu.cn/" + password: false + - name: FEISHU_APP_SECRET + description: "Feishu/Lark app secret" + prompt: "Feishu App Secret" + url: "https://open.feishu.cn/" + password: true +optional_env: + - name: FEISHU_DOMAIN + description: "Domain: 'feishu' (China) or 'lark' (International)" + prompt: "Domain (feishu/lark)" + password: false + - name: FEISHU_ALLOWED_USERS + description: "Comma-separated Feishu user IDs allowed to talk to the bot" + prompt: "Allowed users (comma-separated)" + password: false + - name: FEISHU_ALLOW_ALL_USERS + description: "Allow any Feishu user to trigger the bot (dev only)" + prompt: "Allow all users? (true/false)" + password: false + - name: FEISHU_HOME_CHANNEL + description: "Default chat ID for cron / notification delivery" + prompt: "Home channel ID" + password: false + - name: FEISHU_HOME_CHANNEL_NAME + description: "Display name for the Feishu home channel" + prompt: "Home channel display name" + password: false diff --git a/tools/send_message_tool.py b/tools/send_message_tool.py index 7c400fedee99..3e866dda956d 100644 --- a/tools/send_message_tool.py +++ b/tools/send_message_tool.py @@ -598,12 +598,8 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None, except ImportError: _telegram_available = False - # Feishu adapter import is optional (requires lark-oapi) - try: - from gateway.platforms.feishu import FeishuAdapter - _feishu_available = True - except ImportError: - _feishu_available = False + # Feishu adapter migrated to a plugin (#41112); its max_message_length + # (8000) now flows through the registry fallback below. media_files = media_files or [] @@ -615,13 +611,12 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None, logger.debug("Failed to apply Slack mrkdwn formatting in _send_to_platform", exc_info=True) # Platform message length limits (from adapter class attributes for - # built-in platforms; from PlatformEntry.max_message_length for plugins). + # built-in platforms; from PlatformEntry.max_message_length for plugins, + # resolved via the registry fallback below β€” covers Feishu since #41112). _MAX_LENGTHS = { Platform.TELEGRAM: TelegramAdapter.MAX_MESSAGE_LENGTH if _telegram_available else 4096, Platform.SLACK: SlackAdapter.MAX_MESSAGE_LENGTH, } - if _feishu_available: - _MAX_LENGTHS[Platform.FEISHU] = FeishuAdapter.MAX_MESSAGE_LENGTH # Check plugin registry for max_message_length if platform not in _MAX_LENGTHS: @@ -742,12 +737,19 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None, last_result = result return last_result - # --- Feishu: native media attachment support via adapter --- + # --- Feishu: native media attachment support via the registry's + # standalone_sender_fn (plugins/platforms/feishu/adapter.py::_standalone_send). #41112 if platform == Platform.FEISHU and media_files: + from gateway.platform_registry import platform_registry as _pr_feishu + from hermes_cli.plugins import discover_plugins as _dp_feishu + _dp_feishu() + _feishu_entry = _pr_feishu.get("feishu") + if _feishu_entry is None or _feishu_entry.standalone_sender_fn is None: + return {"error": "Feishu plugin not registered or missing standalone_sender_fn"} last_result = None for i, chunk in enumerate(chunks): is_last = (i == len(chunks) - 1) - result = await _send_feishu( + result = await _feishu_entry.standalone_sender_fn( pconfig, chat_id, chunk, @@ -791,7 +793,7 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None, elif platform == Platform.DINGTALK: result = await _registry_standalone_send("dingtalk", pconfig, chat_id, chunk, thread_id) elif platform == Platform.FEISHU: - result = await _send_feishu(pconfig, chat_id, chunk, thread_id=thread_id) + result = await _registry_standalone_send("feishu", pconfig, chat_id, chunk, thread_id) elif platform == Platform.WECOM: result = await _send_wecom(pconfig.extra, chat_id, chunk) elif platform == Platform.BLUEBUBBLES: @@ -1516,61 +1518,9 @@ async def _send_bluebubbles(extra, chat_id, message): return _error(f"BlueBubbles send failed: {e}") -async def _send_feishu(pconfig, chat_id, message, media_files=None, thread_id=None): - """Send via Feishu/Lark using the adapter's send pipeline.""" - try: - from gateway.platforms.feishu import FeishuAdapter, FEISHU_AVAILABLE - if not FEISHU_AVAILABLE: - return {"error": "Feishu dependencies not installed. Run: pip install 'hermes-agent[feishu]'"} - from gateway.platforms.feishu import FEISHU_DOMAIN, LARK_DOMAIN - except ImportError: - return {"error": "Feishu dependencies not installed. Run: pip install 'hermes-agent[feishu]'"} - - media_files = media_files or [] - - try: - adapter = FeishuAdapter(pconfig) - domain_name = getattr(adapter, "_domain_name", "feishu") - domain = FEISHU_DOMAIN if domain_name != "lark" else LARK_DOMAIN - adapter._client = adapter._build_lark_client(domain) - metadata = {"thread_id": thread_id} if thread_id else None - - last_result = None - if message.strip(): - last_result = await adapter.send(chat_id, message, metadata=metadata) - if not last_result.success: - return _error(f"Feishu send failed: {last_result.error}") - - for media_path, is_voice in media_files: - if not os.path.exists(media_path): - return _error(f"Media file not found: {media_path}") - - ext = os.path.splitext(media_path)[1].lower() - if ext in _IMAGE_EXTS: - last_result = await adapter.send_image_file(chat_id, media_path, metadata=metadata) - elif ext in _VIDEO_EXTS: - last_result = await adapter.send_video(chat_id, media_path, metadata=metadata) - elif ext in _VOICE_EXTS and is_voice: - last_result = await adapter.send_voice(chat_id, media_path, metadata=metadata) - elif ext in _AUDIO_EXTS: - last_result = await adapter.send_voice(chat_id, media_path, metadata=metadata) - else: - last_result = await adapter.send_document(chat_id, media_path, metadata=metadata) - - if not last_result.success: - return _error(f"Feishu media send failed: {last_result.error}") - - if last_result is None: - return {"error": "No deliverable text or media remained after processing MEDIA tags"} - - return { - "success": True, - "platform": "feishu", - "chat_id": chat_id, - "message_id": last_result.message_id, - } - except Exception as e: - return _error(f"Feishu send failed: {e}") +# _send_feishu moved to plugins/platforms/feishu/adapter.py::_standalone_send, +# wired via standalone_sender_fn and reached through _registry_standalone_send +# (and the feishu media branch above). #41112. def _check_send_message():