register.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. """Yuanbao plugin registration: setup row, configured check, standalone sender, ``register``."""
  2. import re
  3. import logging
  4. from gateway.platforms._shared import send_error
  5. from gateway.platforms._shared import config_connected_extra
  6. from gateway.platforms.send_targets import NOT_EXPLICIT, StandaloneSendPolicy
  7. # Absolute import (see __init__.py): one ``YuanbaoAdapter`` class object for the registry,
  8. # tools/yuanbao_tools.py and the standalone sender.
  9. from plugins.platforms.yuanbao.adapter import WEBSOCKETS_AVAILABLE, YuanbaoAdapter
  10. logger = logging.getLogger(__name__)
  11. _INSTALL_HINT = "Yuanbao: websockets not installed. Run: pip install websockets"
  12. _SETUP_PLATFORM = {
  13. "key": "yuanbao", "label": "Yuanbao", "emoji": "💎", "token_var": "YUANBAO_APP_ID",
  14. "setup_instructions": [
  15. "1. Download the Yuanbao app from https://yuanbao.tencent.com/",
  16. "2. In the app, go to PAI → My Bot and create a new bot",
  17. "3. After the bot is created, copy the App ID and App Secret",
  18. "4. Enter them below and Hermes will connect automatically over WebSocket",
  19. ],
  20. "vars": [
  21. {"name": "YUANBAO_APP_ID", "prompt": "App ID", "password": False,
  22. "help": "The App ID from your Yuanbao IM Bot credentials."},
  23. {"name": "YUANBAO_APP_SECRET", "prompt": "App Secret", "password": True,
  24. "help": "The App Secret (used for HMAC signing) from your Yuanbao IM Bot."},
  25. ],
  26. }
  27. def check_yuanbao_requirements() -> bool:
  28. """Runtime deps present (the websockets client)."""
  29. return WEBSOCKETS_AVAILABLE
  30. def interactive_setup() -> None:
  31. """``hermes gateway setup`` flow: the standard App ID / App Secret prompts."""
  32. from hermes_cli import gateway as gateway_mod
  33. gateway_mod._setup_standard_platform(dict(_SETUP_PLATFORM))
  34. def _is_connected(config) -> bool:
  35. """Configured = App ID (or legacy App Key) + App Secret, from config extras or env."""
  36. extra = getattr(config, "extra", {}) or {}
  37. import hermes_cli.gateway as gateway_mod
  38. app_id = (extra.get("app_id") or gateway_mod.get_env_value("YUANBAO_APP_ID")
  39. or gateway_mod.get_env_value("YUANBAO_APP_KEY") or "")
  40. secret = extra.get("app_secret") or gateway_mod.get_env_value("YUANBAO_APP_SECRET") or ""
  41. return bool(str(app_id).strip() and str(secret).strip())
  42. async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_files=None, **_kwargs):
  43. """standalone_sender_fn: send via the running adapter's persistent WebSocket (no throwaway
  44. client possible — Yuanbao needs the live signed connection)."""
  45. adapter = YuanbaoAdapter.get_active()
  46. if adapter is None:
  47. return send_error("Yuanbao adapter is not running. Start the gateway with yuanbao platform enabled first.")
  48. try:
  49. return await adapter._outbound.sender.send_direct(chat_id, message, media_files)
  50. except Exception as e:
  51. logger.debug("Yuanbao standalone send failed", exc_info=True)
  52. return send_error(f"Yuanbao send failed: {e}")
  53. # System-prompt platform hint (PlatformEntry.platform_hint); cached-prompt bytes, keep stable.
  54. _PLATFORM_HINT = (
  55. "You are on Yuanbao (\u817e\u8baf\u5143\u5b9d), a Chinese AI assistant "
  56. "platform. Markdown renders (code blocks, tables, bold/italic). "
  57. "You can send files natively: write MEDIA:/absolute/path/to/file in your response. "
  58. "Images (.jpg, .png, .webp, .gif) send as photos, other files as downloadable documents (max 50 MB); "
  59. "image URLs via ![alt](url) are downloaded and sent as photos. Never claim you lack file-sending. "
  60. "Stickers (\u8d34\u7eb8/\u8868\u60c5\u5305): when the user sends one (you see '[emoji: "
  61. "\u540d\u79f0]') or asks for one, use the sticker tools \u2014 yb_search_sticker with a Chinese "
  62. "keyword, then yb_send_sticker with the chosen id \u2014 which send a real native sticker. Never "
  63. "draw sticker-like PNGs and send them as images, and bare Unicode emoji is not a substitute."
  64. )
  65. _SEND_TARGET_RE = re.compile(r"^\s*((?:group|direct):[^:]+)\s*$")
  66. def _parse_send_target(ref):
  67. # "group:<code>" / "direct:<id>"; a bare number is a group code (never generic rules).
  68. match = _SEND_TARGET_RE.fullmatch(ref)
  69. if match:
  70. return match.group(1), None
  71. return (f"group:{ref.strip()}", None) if ref.strip().isdigit() else NOT_EXPLICIT
  72. def register(ctx) -> None:
  73. """Plugin entry point — called by the Hermes plugin system."""
  74. from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)
  75. ctx.register_platform(
  76. target_ref_syntax_fn=_parse_send_target,
  77. standalone_send=StandaloneSendPolicy(label="Yuanbao", media=True, text_direct=True),
  78. name="yuanbao", label="Yuanbao", adapter_factory=YuanbaoAdapter,
  79. dashboard_label="Yuanbao (元宝)",
  80. dashboard_description="Connect Hermes to Tencent Yuanbao.",
  81. dashboard_required_env=(),
  82. check_fn=check_yuanbao_requirements, is_connected=_is_connected,
  83. config_connected_fn=config_connected_extra("app_id", "app_secret"),
  84. required_env=["YUANBAO_APP_ID", "YUANBAO_APP_SECRET"], install_hint=_INSTALL_HINT,
  85. setup_fn=interactive_setup, cron_deliver_env_var="YUANBAO_HOME_CHANNEL",
  86. standalone_sender_fn=_standalone_send, emoji="💎", allow_update_command=False,
  87. platform_hint=_PLATFORM_HINT,
  88. env_overrides=gateway_env.ENV_OVERRIDES,
  89. env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS, **gateway_env.AUTHZ,
  90. )