Skip to content

The agent that grows with you

refactor(weixin): move adapter into bundled platform plugin

Tekniume36a291671b4
diff --git a/plugins/platforms/weixin/__init__.py b/plugins/platforms/weixin/__init__.py
new file mode 100644
index 00000000000..d4f1d7bf0e3
--- /dev/null
+++ b/plugins/platforms/weixin/__init__.py
@@ -0,0 +1,3 @@
+from .adapter import register
+
+__all__ = ["register"]
diff --git a/gateway/platforms/weixin.py b/plugins/platforms/weixin/adapter.py
similarity index 89%
rename from gateway/platforms/weixin.py
rename to plugins/platforms/weixin/adapter.py
index 59710ed248d..106b6d9f6f0 100644
--- a/gateway/platforms/weixin.py
+++ b/plugins/platforms/weixin/adapter.py
@@ -1241,3 +1241,151 @@ async def send_weixin_direct(
adapter._send_session = adapter._session = session
adapter._token_store = token_store
return await _deliver_direct(adapter, chat_id, message, media_files, context_token)
+
+
+# ---------------------------------------------------------------------------
+# Plugin wiring (formerly core: gateway/run.py _BUILTIN_ADAPTERS row, tools/send_message_senders.py
+# ``_send_weixin``, hermes_cli/gateway_setup_wizard.py ``_setup_weixin``).
+# ---------------------------------------------------------------------------
+
+_INSTALL_HINT = "Weixin: aiohttp/cryptography not installed"
+
+
+def _is_connected(config: Any) -> bool:
+ """Account ID AND token, from ``config`` or the scoped ``WEIXIN_*`` env (``gateway/config.py``'s
+ Weixin connected check reads the same pair)."""
+ extra = getattr(config, "extra", None) or {}
+ account = _extra_or_secret(extra, "account_id")
+ token = str(getattr(config, "token", None) or extra.get("token") or _wx_secret("WEIXIN_TOKEN", "")).strip()
+ return bool(account and token)
+
+
+async def _standalone_send(pconfig: Any, chat_id: str, message: str, *, thread_id: Optional[str] = None,
+ media_files: Optional[list] = None, force_document: bool = False) -> dict[str, Any]:
+ """Out-of-process ``send_message``/cron sender: native text + media via :func:`send_weixin_direct`.
+ ``thread_id``/``force_document`` are signature parity only (iLink has neither). Imports nothing from
+ other plugins, so an unrelated optional SDK (e.g. lark-oapi) can never block Weixin delivery."""
+ from gateway.platforms._shared import send_error
+ if not check_weixin_requirements():
+ return send_error("Weixin requirements not met. Need aiohttp + cryptography.")
+ try:
+ return await send_weixin_direct(extra=getattr(pconfig, "extra", None) or {}, token=getattr(pconfig, "token", None),
+ chat_id=chat_id, message=message, media_files=media_files)
+ except Exception as e:
+ return send_error(f"Weixin send failed: {e}")
+
+
+# Weixin DM policy by menu index (index 2 = allowlist is prompted separately).
+_WEIXIN_DM_POLICIES = {0: ("pairing", "false", "success", " DM pairing enabled."),
+ 1: ("open", "true", "warning", " Open DM access enabled for Weixin."),
+ 3: ("disabled", "false", "warning", " Direct messages disabled.")}
+
+_WEIXIN_GROUP_NOTE = (
+ " Note: QR login connects an iLink bot identity (e.g. [email protected]), not a",
+ " scriptable personal WeChat account. Ordinary WeChat groups typically cannot",
+ " invite an @im.bot identity, and iLink does not deliver ordinary-group events",
+ " to most bot accounts. The settings below only apply when iLink actually",
+ " delivers group events for your account type — otherwise DM remains the only",
+ " working channel regardless of this choice.",
+)
+
+
+def interactive_setup() -> None:
+ """``hermes gateway setup`` flow for Weixin / WeChat personal accounts (QR login via :func:`qr_login`).
+ Helpers resolve through the ``hermes_cli.gateway`` facade so the prompts/output match every other
+ wizard and the facade seams tests patch keep intercepting."""
+ from hermes_cli import gateway as gw
+ from hermes_cli.gateway_setup_wizard import (
+ _confirm_reconfigure, _offer_home_channel, _print_setup_header, _prompt_csv, _save_env_values)
+
+ _print_setup_header("💬 Weixin / WeChat")
+ print()
+ gw._print_info_lines(
+ " 1. Hermes will open Tencent iLink QR login in this terminal.",
+ " 2. Use WeChat to scan and confirm the QR code.",
+ " 3. Hermes will store the returned account_id/token in ~/.hermes/.env.",
+ " 4. This adapter supports native text, image, video, and document delivery.",
+ )
+ if not _confirm_reconfigure("Weixin", "WEIXIN_ACCOUNT_ID", "WEIXIN_TOKEN"):
+ return
+ if not check_weixin_requirements():
+ gw.print_error(" Missing dependencies: Weixin needs aiohttp and cryptography.")
+ gw.print_info(" Install them, then rerun `hermes gateway setup`.")
+ return
+ print()
+ if not gw.prompt_yes_no(" Start QR login now?", True):
+ gw.print_info(" Cancelled.")
+ return
+ try:
+ credentials = gw.asyncio.run(qr_login(str(gw.get_hermes_home())))
+ except KeyboardInterrupt:
+ print()
+ gw.print_warning(" Weixin setup cancelled.")
+ return
+ except Exception as exc:
+ gw.print_error(f" QR login failed: {exc}")
+ return
+ if not credentials:
+ gw.print_warning(" QR login did not complete.")
+ return
+
+ account_id = credentials.get("account_id", "")
+ user_id = credentials.get("user_id", "")
+ gw.save_env_value("WEIXIN_ACCOUNT_ID", account_id)
+ gw.save_env_value("WEIXIN_TOKEN", credentials.get("token", ""))
+ if credentials.get("base_url", ""):
+ gw.save_env_value("WEIXIN_BASE_URL", credentials.get("base_url", ""))
+ gw.save_env_value("WEIXIN_CDN_BASE_URL", gw.get_env_value("WEIXIN_CDN_BASE_URL") or WEIXIN_CDN_BASE_URL)
+
+ print()
+ access_choices = [
+ "Use DM pairing approval (recommended)", "Allow all direct messages", "Only allow listed user IDs",
+ "Disable direct messages",
+ ]
+ access_idx = gw.prompt_choice(" How should direct messages be authorized?", access_choices, 0)
+ if access_idx == 2:
+ allowlist = _prompt_csv(" Allowed Weixin user IDs (comma-separated)", user_id or "")
+ _save_env_values(WEIXIN_DM_POLICY="allowlist", WEIXIN_ALLOW_ALL_USERS="false", WEIXIN_ALLOWED_USERS=allowlist)
+ gw.print_success(" Weixin allowlist saved.")
+ else:
+ policy, allow_all, level, message = _WEIXIN_DM_POLICIES.get(access_idx, _WEIXIN_DM_POLICIES[3])
+ _save_env_values(WEIXIN_DM_POLICY=policy, WEIXIN_ALLOW_ALL_USERS=allow_all, WEIXIN_ALLOWED_USERS="")
+ (gw.print_success if level == "success" else gw.print_warning)(message)
+ if access_idx == 0:
+ gw.print_info(" Unknown DM users can request access and you approve them with `hermes pairing approve`.")
+
+ print()
+ gw._print_info_lines(*_WEIXIN_GROUP_NOTE)
+ group_choices = ["Disable group chats (recommended)", "Allow all group chats", "Only allow listed group chat IDs"]
+ group_idx = gw.prompt_choice(" How should group chats be handled?", group_choices, 0)
+ if group_idx == 0:
+ _save_env_values(WEIXIN_GROUP_POLICY="disabled", WEIXIN_GROUP_ALLOWED_USERS="")
+ gw.print_info(" Group chats disabled.")
+ elif group_idx == 1:
+ _save_env_values(WEIXIN_GROUP_POLICY="open", WEIXIN_GROUP_ALLOWED_USERS="")
+ gw.print_warning(" All group chats enabled (only takes effect if iLink delivers group events).")
+ else:
+ allow_groups = _prompt_csv(" Allowed group chat IDs (comma-separated, not member user IDs)", "")
+ _save_env_values(WEIXIN_GROUP_POLICY="allowlist", WEIXIN_GROUP_ALLOWED_USERS=allow_groups)
+ gw.print_success(" Group allowlist saved (only takes effect if iLink delivers group events).")
+
+ if user_id:
+ print()
+ _offer_home_channel("WEIXIN_HOME_CHANNEL", user_id, "your Weixin user ID")
+ print()
+ gw.print_success("Weixin configured!")
+ gw.print_info(f" Account ID: {account_id}")
+ if user_id:
+ gw.print_info(f" User ID: {user_id}")
+
+
+def register(ctx) -> None:
+ """Plugin entry point — called by the Hermes plugin system."""
+ ctx.register_platform(
+ name="weixin", label="Weixin / WeChat", adapter_factory=WeixinAdapter, check_fn=check_weixin_requirements,
+ is_connected=_is_connected, required_env=["WEIXIN_ACCOUNT_ID", "WEIXIN_TOKEN"], install_hint=_INSTALL_HINT,
+ setup_fn=interactive_setup, allowed_users_env="WEIXIN_ALLOWED_USERS", allow_all_env="WEIXIN_ALLOW_ALL_USERS",
+ cron_deliver_env_var="WEIXIN_HOME_CHANNEL",
+ # Out-of-process send_message/cron; the adapter's own send() chunks (MAX_MESSAGE_LENGTH), so
+ # max_message_length stays 0: send_message hands the full text + all media to one native send.
+ standalone_sender_fn=_standalone_send, max_message_length=0, emoji="💬", allow_update_command=True)
diff --git a/plugins/platforms/weixin/plugin.yaml b/plugins/platforms/weixin/plugin.yaml
new file mode 100644
index 00000000000..cc3e88c706a
--- /dev/null
+++ b/plugins/platforms/weixin/plugin.yaml
@@ -0,0 +1,60 @@
+name: weixin-platform
+label: Weixin / WeChat
+kind: platform
+version: 1.0.0
+description: >
+ Weixin (personal WeChat) gateway adapter for Hermes Agent over Tencent's
+ iLink Bot API. Long-polls getupdates for inbound messages, echoes each
+ peer's context_token on replies, and moves media through the AES-128-ECB
+ encrypted CDN. `hermes gateway setup` performs the iLink QR login.
+author: NousResearch
+requires_env:
+ - name: WEIXIN_ACCOUNT_ID
+ description: "iLink Bot account ID obtained through QR login in hermes gateway setup"
+ prompt: "iLink Bot account ID"
+ password: false
+ - name: WEIXIN_TOKEN
+ description: "iLink Bot token obtained through QR login in hermes gateway setup"
+ prompt: "iLink Bot token"
+ password: true
+optional_env:
+ - name: WEIXIN_BASE_URL
+ description: "iLink API base URL saved by QR login (default: https://ilinkai.weixin.qq.com)"
+ prompt: "iLink API base URL"
+ password: false
+ - name: WEIXIN_CDN_BASE_URL
+ description: "iLink media CDN base URL (default: https://novac2c.cdn.weixin.qq.com/c2c)"
+ prompt: "iLink CDN base URL"
+ password: false
+ - name: WEIXIN_DM_POLICY
+ description: "Direct-message policy: pairing, open, allowlist, or disabled (default: pairing)"
+ prompt: "DM policy (pairing|open|allowlist|disabled)"
+ password: false
+ - name: WEIXIN_GROUP_POLICY
+ description: "Group-chat policy: disabled, open, or allowlist (default: disabled)"
+ prompt: "Group policy (disabled|open|allowlist)"
+ password: false
+ - name: WEIXIN_ALLOWED_USERS
+ description: "Comma-separated Weixin user IDs allowed to DM the bot"
+ prompt: "Allowed users (comma-separated)"
+ password: false
+ - name: WEIXIN_GROUP_ALLOWED_USERS
+ description: "Comma-separated group chat IDs allowed when WEIXIN_GROUP_POLICY=allowlist"
+ prompt: "Allowed group chat IDs (comma-separated)"
+ password: false
+ - name: WEIXIN_ALLOW_ALL_USERS
+ description: "Allow any Weixin user to trigger the bot"
+ prompt: "Allow all users? (true/false)"
+ password: false
+ - name: WEIXIN_HOME_CHANNEL
+ description: "Default chat ID for cron / notification delivery"
+ prompt: "Home channel ID"
+ password: false
+ - name: WEIXIN_HOME_CHANNEL_NAME
+ description: "Display name for the Weixin home channel"
+ prompt: "Home channel display name"
+ password: false
+ - name: WEIXIN_SPLIT_MULTILINE_MESSAGES
+ description: "Send each line of a multi-line reply as its own message (default: false)"
+ prompt: "Split multi-line messages? (true/false)"
+ password: false
diff --git a/tests/gateway/test_access_policy_mixin.py b/tests/gateway/test_access_policy_mixin.py
index 308eb8c6c79..7288c89779b 100644
--- a/tests/gateway/test_access_policy_mixin.py
+++ b/tests/gateway/test_access_policy_mixin.py
@@ -30,7 +30,7 @@ def _scope(secrets):
def _hosts():
"""One bare instance per own-policy class, attributes set exactly as the adapters do."""
from gateway.platforms.qqbot.adapter import QQAdapter
- from gateway.platforms.weixin import WeixinAdapter
+ from plugins.platforms.weixin.adapter import WeixinAdapter
from plugins.platforms.whatsapp_cloud.adapter import WhatsAppCloudAdapter
from gateway.platforms.whatsapp_common import WhatsAppBehaviorMixin
from gateway.platforms.yuanbao import AccessPolicy
diff --git a/tests/gateway/test_config_driven_access_policy.py b/tests/gateway/test_config_driven_access_policy.py
index 7c74140b250..d0a7fe07ffd 100644
--- a/tests/gateway/test_config_driven_access_policy.py
+++ b/tests/gateway/test_config_driven_access_policy.py
@@ -109,7 +109,7 @@ def test_base_adapter_defaults_to_not_owning_access_policy():
"module_path, class_name",
[
("plugins.platforms.wecom.adapter", "WeComAdapter"),
- ("gateway.platforms.weixin", "WeixinAdapter"),
+ ("plugins.platforms.weixin.adapter", "WeixinAdapter"),
("gateway.platforms.yuanbao", "YuanbaoAdapter"),
("gateway.platforms.qqbot.adapter", "QQAdapter"),
("plugins.platforms.whatsapp.adapter", "WhatsAppAdapter"),
@@ -244,7 +244,7 @@ def test_own_policy_open_group_not_authorized_without_allowlist(monkeypatch, pla
[
("plugins.platforms.whatsapp.adapter", "WhatsAppAdapter", "_is_dm_allowed"),
("plugins.platforms.wecom.adapter", "WeComAdapter", "_is_dm_allowed"),
- ("gateway.platforms.weixin", "WeixinAdapter", "_is_dm_allowed"),
+ ("plugins.platforms.weixin.adapter", "WeixinAdapter", "_is_dm_allowed"),
("gateway.platforms.qqbot.adapter", "QQAdapter", "_is_dm_allowed"),
],
)
diff --git a/tests/gateway/test_platform_authz_scope.py b/tests/gateway/test_platform_authz_scope.py
index 6e340c74bb9..f1b648f963e 100644
--- a/tests/gateway/test_platform_authz_scope.py
+++ b/tests/gateway/test_platform_authz_scope.py
@@ -55,7 +55,7 @@ def profile_scope():
@pytest.mark.parametrize(
"module_path,helper_name,var",
[
- ("gateway.platforms.weixin", "_wx_secret", "WEIXIN_ALLOWED_USERS"),
+ ("plugins.platforms.weixin.adapter", "_wx_secret", "WEIXIN_ALLOWED_USERS"),
("gateway.platforms.yuanbao", "_yb_secret", "YUANBAO_DM_POLICY"),
("plugins.platforms.signal.adapter", "_sig_secret", "SIGNAL_ALLOWED_USERS"),
("plugins.platforms.wecom.adapter", "_get_scoped_secret", "WECOM_ALLOWED_USERS"),
@@ -86,7 +86,7 @@ def multiplex_on(monkeypatch):
@pytest.mark.parametrize(
"module_path,helper_name",
[
- ("gateway.platforms.weixin", "_wx_secret"),
+ ("plugins.platforms.weixin.adapter", "_wx_secret"),
("gateway.platforms.yuanbao", "_yb_secret"),
("plugins.platforms.signal.adapter", "_sig_secret"),
("plugins.platforms.wecom.adapter", "_get_scoped_secret"),
@@ -121,7 +121,7 @@ def test_helper_does_not_leak_default_env_into_scoped_miss(
@pytest.mark.parametrize(
"module_path,helper_name,var",
[
- ("gateway.platforms.weixin", "_wx_secret", "WEIXIN_ALLOWED_USERS"),
+ ("plugins.platforms.weixin.adapter", "_wx_secret", "WEIXIN_ALLOWED_USERS"),
("gateway.platforms.yuanbao", "_yb_secret", "YUANBAO_DM_POLICY"),
("plugins.platforms.signal.adapter", "_sig_secret", "SIGNAL_ALLOWED_USERS"),
("plugins.platforms.wecom.adapter", "_get_scoped_secret", "WECOM_ALLOWED_USERS"),
@@ -145,14 +145,14 @@ def test_weixin_open_gate_ignores_default_env_under_scope(profile_scope, multipl
NOT carry it — the gate must stay closed."""
monkeypatch.setenv("GATEWAY_ALLOW_ALL_USERS", "true")
- from gateway.platforms.weixin import WeixinAdapter
+ from plugins.platforms.weixin.adapter import WeixinAdapter
adapter = WeixinAdapter.__new__(WeixinAdapter)
assert adapter._open_dm_opted_in() is False
def test_weixin_open_gate_honors_scope_opt_in():
- from gateway.platforms.weixin import WeixinAdapter
+ from plugins.platforms.weixin.adapter import WeixinAdapter
with _scope({"WEIXIN_ALLOW_ALL_USERS": "yes"}):
adapter = WeixinAdapter.__new__(WeixinAdapter)
diff --git a/tests/gateway/test_poller_fd_lifecycle.py b/tests/gateway/test_poller_fd_lifecycle.py
index 1bbaea2526d..1c7ce213364 100644
--- a/tests/gateway/test_poller_fd_lifecycle.py
+++ b/tests/gateway/test_poller_fd_lifecycle.py
@@ -95,7 +95,7 @@ class TestWeixinPollSessionRecycle(unittest.TestCase):
def _make_adapter(self):
from gateway.config import PlatformConfig
- from gateway.platforms.weixin import WeixinAdapter
+ from plugins.platforms.weixin.adapter import WeixinAdapter
return WeixinAdapter(
PlatformConfig(
@@ -106,7 +106,7 @@ class TestWeixinPollSessionRecycle(unittest.TestCase):
)
def test_recycle_closes_old_and_installs_fresh_session(self):
- from gateway.platforms import weixin as weixin_mod
+ from plugins.platforms.weixin import adapter as weixin_mod
adapter = self._make_adapter()
adapter._running = True
@@ -139,7 +139,7 @@ class TestWeixinPollSessionRecycle(unittest.TestCase):
def test_poll_loop_recycles_after_max_consecutive_failures(self):
- from gateway.platforms import weixin as weixin_mod
+ from plugins.platforms.weixin import adapter as weixin_mod
adapter = self._make_adapter()
adapter._running = True
diff --git a/tests/gateway/test_text_batch_delay_defaults.py b/tests/gateway/test_text_batch_delay_defaults.py
index 011ef1b62d2..86ffccab864 100644
--- a/tests/gateway/test_text_batch_delay_defaults.py
+++ b/tests/gateway/test_text_batch_delay_defaults.py
@@ -7,7 +7,7 @@ before dispatching; Telegram waits 0.3s (1.0s near a split chunk).
import pytest
from gateway.config import PlatformConfig
-from gateway.platforms.weixin import WeixinAdapter
+from plugins.platforms.weixin.adapter import WeixinAdapter
from plugins.platforms.whatsapp.adapter import WhatsAppAdapter
diff --git a/tests/gateway/test_weixin.py b/tests/gateway/test_weixin_plugin.py
similarity index 91%
rename from tests/gateway/test_weixin.py
rename to tests/gateway/test_weixin_plugin.py
index b8a8c459c96..25fd62a0b7b 100644
--- a/tests/gateway/test_weixin.py
+++ b/tests/gateway/test_weixin_plugin.py
@@ -9,8 +9,8 @@ import pytest
from gateway.config import PlatformConfig
from gateway.config import GatewayConfig, Platform
-from gateway.platforms import weixin
-from gateway.platforms.weixin import ContextTokenStore, WeixinAdapter
+from plugins.platforms.weixin import adapter as weixin
+from plugins.platforms.weixin.adapter import ContextTokenStore, WeixinAdapter
from tools.send_message_targets import _parse_target_ref
@@ -168,7 +168,7 @@ class TestWeixinStatePersistence:
def fake_write(path, data, *args, **kwargs):
write_threads.append(threading.get_ident())
- with patch("gateway.platforms.weixin.atomic_json_write", side_effect=fake_write):
+ with patch("plugins.platforms.weixin.adapter.atomic_json_write", side_effect=fake_write):
await store.set("acct-1", "user-1", "ctx-token-abc")
assert store.get("acct-1", "user-1") == "ctx-token-abc"
@@ -194,7 +194,7 @@ class TestWeixinStatePersistence:
time.sleep(0.05)
writes.append(dict(data))
- with patch("gateway.platforms.weixin.atomic_json_write", side_effect=slow_first_write):
+ with patch("plugins.platforms.weixin.adapter.atomic_json_write", side_effect=slow_first_write):
first = _asyncio.create_task(store.set("acct-1", "user-1", "t1"))
await _asyncio.sleep(0.005)
second = _asyncio.create_task(store.set("acct-1", "user-2", "t2"))
@@ -223,8 +223,8 @@ class TestWeixinChunkDelivery:
return adapter
- @patch("gateway.platforms.weixin.asyncio.sleep", new_callable=AsyncMock)
- @patch("gateway.platforms.weixin._send_message", new_callable=AsyncMock)
+ @patch("plugins.platforms.weixin.adapter.asyncio.sleep", new_callable=AsyncMock)
+ @patch("plugins.platforms.weixin.adapter._send_message", new_callable=AsyncMock)
def test_send_retries_failed_chunk_before_continuing(self, send_message_mock, sleep_mock):
adapter = self._connected_adapter()
adapter.MAX_MESSAGE_LENGTH = 12
@@ -249,8 +249,8 @@ class TestWeixinChunkDelivery:
assert first_try["text"] == retry["text"]
assert first_try["client_id"] == retry["client_id"]
- @patch("gateway.platforms.weixin.asyncio.sleep", new_callable=AsyncMock)
- @patch("gateway.platforms.weixin._send_message", new_callable=AsyncMock)
+ @patch("plugins.platforms.weixin.adapter.asyncio.sleep", new_callable=AsyncMock)
+ @patch("plugins.platforms.weixin.adapter._send_message", new_callable=AsyncMock)
def test_repeated_rate_limits_open_circuit_for_followup_sends(self, send_message_mock, sleep_mock):
adapter = self._connected_adapter()
adapter._send_chunk_retries = 3
@@ -279,7 +279,7 @@ class TestWeixinChunkDelivery:
assert sleep_mock.await_count == 1
@pytest.mark.parametrize("error_field", ["ret", "errcode"])
- @patch("gateway.platforms.weixin._send_message", new_callable=AsyncMock)
+ @patch("plugins.platforms.weixin.adapter._send_message", new_callable=AsyncMock)
def test_prepare_failed_retries_without_context_token(self, send_message_mock, error_field):
adapter = self._connected_adapter()
adapter._rate_limit_circuit_threshold = 1
@@ -294,7 +294,7 @@ class TestWeixinChunkDelivery:
assert adapter._rate_limit_circuit_until == 0.0
@pytest.mark.parametrize("stored_token", [None, "ctx-token"])
- @patch("gateway.platforms.weixin._send_message", new_callable=AsyncMock)
+ @patch("plugins.platforms.weixin.adapter._send_message", new_callable=AsyncMock)
def test_prepare_failed_without_recovery_is_not_a_rate_limit(self, send_message_mock, stored_token):
"""No token to drop (fresh pairing, #80125) or a tokenless re-send that still fails: the error names the
real cause and the rate-limit breaker stays closed, instead of "rate limited; cooldown active" for 30s."""
@@ -314,7 +314,7 @@ class TestWeixinChunkDelivery:
assert [call.kwargs["context_token"] for call in send_message_mock.await_args_list] == (
[None] if stored_token is None else ["ctx-token", None])
- @patch("gateway.platforms.weixin._send_message", new_callable=AsyncMock)
+ @patch("plugins.platforms.weixin.adapter._send_message", new_callable=AsyncMock)
def test_tokenless_resend_does_not_consume_retry_budget(self, send_message_mock):
"""With ``send_chunk_retries=0`` the stale-session re-send must still happen: it is a different payload,
not a failed attempt, so it must not eat the (only) retry slot and fall out of the loop (#112709)."""
@@ -392,10 +392,10 @@ class TestWeixinOutboundMedia:
aes_key = bytes(range(16))
expected_aes_key = base64.b64encode(aes_key.hex().encode("ascii")).decode("ascii")
- with patch("gateway.platforms.weixin._get_upload_url", new=AsyncMock(return_value={"upload_full_url": "https://upload.example.com/media"})), \
- patch("gateway.platforms.weixin._api_post", new_callable=AsyncMock) as api_post_mock, \
- patch("gateway.platforms.weixin.secrets.token_hex", return_value="filekey-123"), \
- patch("gateway.platforms.weixin.secrets.token_bytes", return_value=aes_key):
+ with patch("plugins.platforms.weixin.adapter._get_upload_url", new=AsyncMock(return_value={"upload_full_url": "https://upload.example.com/media"})), \
+ patch("plugins.platforms.weixin.adapter._api_post", new_callable=AsyncMock) as api_post_mock, \
+ patch("plugins.platforms.weixin.adapter.secrets.token_hex", return_value="filekey-123"), \
+ patch("plugins.platforms.weixin.adapter.secrets.token_bytes", return_value=aes_key):
message_id = asyncio.run(adapter._send_file("wxid_test123", str(image_path), ""))
assert message_id.startswith("hermes-weixin-")
@@ -865,3 +865,34 @@ class TestWeixinVoiceGatewayHandoff:
"VOICE event body leaked Tencent's STT text — runner would trust "
"the wrong transcript instead of re-transcribing (#27300)."
)
+
+
+def test_register_declares_weixin_platform_entry():
+ """Weixin ships as a bundled platform plugin: register() wires the adapter, setup, and the
+ out-of-process sender that core used to hard-code (_BUILTIN_ADAPTERS / _send_weixin / _setup_weixin)."""
+ captured = {}
+
+ class _Ctx:
+ def register_platform(self, **kwargs):
+ captured.update(kwargs)
+
+ weixin.register(_Ctx())
+ assert captured["name"] == "weixin" and captured["label"] == "Weixin / WeChat" and captured["emoji"] == "💬"
+ assert captured["adapter_factory"] is WeixinAdapter
+ assert captured["check_fn"] is weixin.check_weixin_requirements
+ assert captured["setup_fn"] is weixin.interactive_setup
+ assert captured["standalone_sender_fn"] is weixin._standalone_send
+ assert captured["required_env"] == ["WEIXIN_ACCOUNT_ID", "WEIXIN_TOKEN"]
+ assert (captured["allowed_users_env"], captured["allow_all_env"], captured["cron_deliver_env_var"]) == (
+ "WEIXIN_ALLOWED_USERS", "WEIXIN_ALLOW_ALL_USERS", "WEIXIN_HOME_CHANNEL")
+ assert captured["install_hint"] == "Weixin: aiohttp/cryptography not installed"
+ assert captured["max_message_length"] == 0 and captured["allow_update_command"] is True
+
+
+def test_is_connected_requires_account_and_token(monkeypatch):
+ for name in ("WEIXIN_ACCOUNT_ID", "WEIXIN_TOKEN"):
+ monkeypatch.delenv(name, raising=False)
+ from gateway.config import PlatformConfig
+ assert weixin._is_connected(PlatformConfig(enabled=True, token="t", extra={"account_id": "a"}))
+ assert not weixin._is_connected(PlatformConfig(enabled=True, token="t"))
+ assert not weixin._is_connected(PlatformConfig(enabled=True, extra={"account_id": "a"}))
diff --git a/tests/gateway/test_weixin_secret_scope.py b/tests/gateway/test_weixin_secret_scope.py
index e07ff738119..95997062576 100644
--- a/tests/gateway/test_weixin_secret_scope.py
+++ b/tests/gateway/test_weixin_secret_scope.py
@@ -11,7 +11,7 @@ import pytest
from agent import secret_scope
from gateway.config import PlatformConfig
-from gateway.platforms.weixin import WeixinAdapter, _wx_secret
+from plugins.platforms.weixin.adapter import WeixinAdapter, _wx_secret
@pytest.fixture()
diff --git a/tests/gateway/test_weixin_typing.py b/tests/gateway/test_weixin_typing.py
index 26d18b14c80..e8e249dc65c 100644
--- a/tests/gateway/test_weixin_typing.py
+++ b/tests/gateway/test_weixin_typing.py
@@ -8,7 +8,7 @@ import pytest
@pytest.fixture
def weixin_adapter():
"""Create a minimal WeixinAdapter with mocked internals for typing tests."""
- from gateway.platforms.weixin import WeixinAdapter, TypingTicketCache
+ from plugins.platforms.weixin.adapter import WeixinAdapter, TypingTicketCache
config = MagicMock()
config.extra = {"account_id": "test-account"}
@@ -43,7 +43,7 @@ class TestEnsureTypingTicket:
)
mock_response = {"typing_ticket": "fresh-ticket-xyz"}
- with patch("gateway.platforms.weixin._get_config", new_callable=AsyncMock) as mock_get:
+ with patch("plugins.platforms.weixin.adapter._get_config", new_callable=AsyncMock) as mock_get:
mock_get.return_value = mock_response
ticket = await weixin_adapter._ensure_typing_ticket("user-123")
@@ -62,7 +62,7 @@ class TestEnsureTypingTicket:
weixin_adapter._token_store.get.return_value = "stored-ctx-token"
mock_response = {"typing_ticket": "ticket-with-ctx"}
- with patch("gateway.platforms.weixin._get_config", new_callable=AsyncMock) as mock_get:
+ with patch("plugins.platforms.weixin.adapter._get_config", new_callable=AsyncMock) as mock_get:
mock_get.return_value = mock_response
ticket = await weixin_adapter._ensure_typing_ticket("user-789")
@@ -78,7 +78,7 @@ class TestEnsureTypingTicket:
@pytest.mark.asyncio
async def test_returns_none_when_getconfig_fails(self, weixin_adapter):
"""Return None when getConfig raises an exception."""
- with patch("gateway.platforms.weixin._get_config", new_callable=AsyncMock) as mock_get:
+ with patch("plugins.platforms.weixin.adapter._get_config", new_callable=AsyncMock) as mock_get:
mock_get.side_effect = Exception("network error")
ticket = await weixin_adapter._ensure_typing_ticket("user-123")
diff --git a/tests/gateway/test_weixin_voice_warning_policy.py b/tests/gateway/test_weixin_voice_warning_policy.py
index 7c0835b202d..4c0a124a433 100644
--- a/tests/gateway/test_weixin_voice_warning_policy.py
+++ b/tests/gateway/test_weixin_voice_warning_policy.py
@@ -4,7 +4,7 @@ from unittest.mock import AsyncMock
import pytest
from gateway.config import PlatformConfig
-from gateway.platforms import weixin as wx
+from plugins.platforms.weixin import adapter as wx
@pytest.mark.asyncio
diff --git a/website/docs/developer-guide/adding-platform-adapters.md b/website/docs/developer-guide/adding-platform-adapters.md
index 8edc799ca8a..5f23b286fdf 100644
--- a/website/docs/developer-guide/adding-platform-adapters.md
+++ b/website/docs/developer-guide/adding-platform-adapters.md
@@ -839,6 +839,6 @@ async def disconnect(self):
| Adapter | Pattern | Complexity | Good reference for |
|---------|---------|------------|-------------------|
| `plugins/platforms/bluebubbles/adapter.py` | REST + webhook | Medium | Simple REST API integration |
-| `weixin.py` | Long-poll + CDN | High | Media handling, encryption |
+| `plugins/platforms/weixin/adapter.py` | Long-poll + CDN | High | Media handling, encryption |
| `plugins/platforms/wecom/callback_adapter.py` | Callback/webhook | Medium | HTTP server, AES crypto, multi-app |
| `plugins/platforms/irc/adapter.py` | Long-poll + IRC protocol | High | Full-featured plugin adapter with scoped token lock |
diff --git a/website/docs/developer-guide/gateway-internals.md b/website/docs/developer-guide/gateway-internals.md
index d505e147d42..585ac0e0573 100644
--- a/website/docs/developer-guide/gateway-internals.md
+++ b/website/docs/developer-guide/gateway-internals.md
@@ -565,11 +565,11 @@ plugins/platforms/ # plugin-packaged adapters (one dir each)
├── signal/adapter.py # Signal via signal-cli HTTP daemon (SSE + JSON-RPC)
├── irc/adapter.py # IRC (canonical scoped-lock example)
├── bluebubbles/adapter.py # Apple iMessage via BlueBubbles macOS server
+├── weixin/adapter.py # Weixin (personal WeChat) via iLink Bot API
└── … # google_chat, ntfy, photon, raft, simplex, …
gateway/platforms/ # core base + legacy direct adapters
├── base.py # BasePlatformAdapter — shared logic for all platforms
-├── weixin.py # Weixin (personal WeChat) via iLink Bot API
├── qqbot/ # QQ Bot (Tencent QQ) via Official API v2 (sub-package)
├── yuanbao.py # Yuanbao (Tencent) DM/group adapter
├── msgraph_webhook.py # Microsoft Graph change-notification webhook (Teams, Outlook, etc.)
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/adding-platform-adapters.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/adding-platform-adapters.md
index 17048f6a0c3..4a97faeaf9d 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/adding-platform-adapters.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/adding-platform-adapters.md
@@ -681,6 +681,6 @@ async def disconnect(self):
| 适配器 | 模式 | 复杂度 | 适合参考的场景 |
|---------|---------|------------|-------------------|
| `plugins/platforms/bluebubbles/adapter.py` | REST + webhook | 中 | 简单 REST API 集成 |
-| `weixin.py` | 长轮询 + CDN | 高 | 媒体处理、加密 |
+| `plugins/platforms/weixin/adapter.py` | 长轮询 + CDN | 高 | 媒体处理、加密 |
| `wecom_callback.py` | 回调/webhook | 中 | HTTP 服务器、AES 加密、多应用 |
| `plugins/platforms/irc/adapter.py` | 长轮询 + IRC 协议 | 高 | 带作用域令牌锁的全功能插件适配器 |
\ No newline at end of file
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/gateway-internals.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/gateway-internals.md
index dbca8416799..85861cdc4a3 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/gateway-internals.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/gateway-internals.md
@@ -165,11 +165,11 @@ plugins/platforms/ # 插件打包的适配器(每个一个目
├── signal/adapter.py # Signal(通过 signal-cli HTTP 守护进程,SSE + JSON-RPC)
├── irc/adapter.py # IRC(作用域锁的标准示例)
├── bluebubbles/adapter.py # Apple iMessage(通过 BlueBubbles macOS 服务端)
+├── weixin/adapter.py # 微信(个人版,通过 iLink Bot API)
└── … # google_chat、ntfy、photon、raft、simplex 等
gateway/platforms/ # 核心 base 与旧的直接适配器
├── base.py # BasePlatformAdapter — 所有平台的共享逻辑
-├── weixin.py # 微信(个人版,通过 iLink Bot API)
├── qqbot/ # QQ Bot(腾讯 QQ,通过官方 API v2,子包)
├── yuanbao.py # 元宝(腾讯)私信/群组适配器
├── msgraph_webhook.py # Microsoft Graph 变更通知 webhook(Teams、Outlook 等)