diff --git a/docs/event-based-agents/adapters/acceptance-report.md b/docs/event-based-agents/adapters/acceptance-report.md index 7e5ff8e1..3fad77f5 100644 --- a/docs/event-based-agents/adapters/acceptance-report.md +++ b/docs/event-based-agents/adapters/acceptance-report.md @@ -11,6 +11,7 @@ Scope: - `lark-eba` - `wecom-eba` - `wecombot-eba` +- `wecomcs-eba` This report follows `acceptance-checklist.md`. Evidence levels are intentionally strict: @@ -32,6 +33,7 @@ This report follows `acceptance-checklist.md`. Evidence levels are intentionally | Lark / Feishu | Partial EBA acceptance | EBA adapter structure, self-built/store app config, WebSocket/Webhook mode handling, converters, common APIs, platform APIs, and unit tests are in place. One real LangBot organization WebSocket private text event reached `EBAEventProbe`; outbound component sweep was visible in Feishu. Latest real UI image/file sends did not reach local plugin evidence, so media receive remains blocked. | | WeCom | Partial EBA acceptance | Regular WeCom application-message adapter is split into the EBA directory with manifest, converters, API mixin, platform API map, and unit tests. Private text reached `EBAEventProbe` through standalone runtime and the real WeCom client; safe plugin APIs passed. Real inbound media and broader event coverage remain pending. | | WeComBot | Partial EBA acceptance | WeCom AI Bot is split into the EBA directory with WebSocket long connection mode and optional webhook mode, EBA message/feedback/platform-specific conversion, cache-backed common APIs, platform API map, unit tests, and a direct live probe. Private text, outbound component sweep, safe common APIs, and all declared WeComBot platform APIs reached `EBAEventProbe`; group, real inbound media, and feedback callback evidence remain pending. | +| WeCom Customer Service | Partial EBA acceptance | WeCom Customer Service is split into the EBA directory with manifest, converters, API mixin, platform API map, unit tests, docs, and a direct live probe scaffold. Real WeChat customer-side UI text reached `EBAEventProbe`; plugin outbound text/image and safe cache-backed common APIs passed. Inbound media and platform-specific API live coverage remain pending; later fallback text sends were blocked by WeCom `95001 send msg count limit`. | Telegram and DingTalk now have real user-side UI image/file upload evidence in plugin JSONL. Discord and aiocqhttp do not yet have real UI inbound image/file evidence. @@ -49,6 +51,7 @@ Telegram and DingTalk now have real user-side UI image/file upload evidence in p | DingTalk private media | DingTalk Mac, `LangBot Team` org private chat | `data/temp/dingtalk-plugin-e2e-media-ui.jsonl` | | Lark / Feishu unit | local mocked Feishu SDK/client paths | `tests/unit_tests/platform/test_lark_eba_adapter.py` | | Lark / Feishu partial live | Feishu Mac, LangBot organization `LangBotDev` private chat | `data/temp/lark-plugin-e2e-ws.jsonl` | +| WeCom Customer Service | WeChat customer-side UI, `客服消息 -> 浪波智能客服` on `dev.rockchin.top` | `/home/wgc/LangBotxg/LangBotEbaTest/data/temp/wecomcs_eba_plugin_probe.jsonl` | All plugin runs used SDK standalone runtime ports `5400/5401`, LangBot `--standalone-runtime`, and the real plugin at `langbot-plugin-demo/EBAEventProbe`. diff --git a/docs/event-based-agents/adapters/wecomcs.md b/docs/event-based-agents/adapters/wecomcs.md new file mode 100644 index 00000000..b5549396 --- /dev/null +++ b/docs/event-based-agents/adapters/wecomcs.md @@ -0,0 +1,161 @@ +# WeCom Customer Service EBA Adapter + +## Status + +WeCom Customer Service now has an EBA adapter directory: + +```text +src/langbot/pkg/platform/adapters/wecomcs/ +├── adapter.py +├── api_impl.py +├── event_converter.py +├── manifest.yaml +├── message_converter.py +├── platform_api.py +└── types.py +``` + +The adapter is registered as `wecomcs-eba`. It is separate from regular WeCom application messages (`wecom-eba`) and WeCom AI Bot (`wecombot-eba`). + +## Configuration + +| Field | Required | Default | Description | +|-------|----------|---------|-------------| +| `webhook_url` | No | `""` | Unified webhook URL copied into the WeCom Customer Service callback settings. | +| `corpid` | Yes | `""` | WeCom corporate ID. | +| `secret` | Yes | `""` | Customer Service secret used for access tokens. | +| `token` | Yes | `""` | Customer Service callback token. | +| `EncodingAESKey` | Yes | `""` | Customer Service callback encryption key. | +| `api_base_url` | No | `https://qyapi.weixin.qq.com/cgi-bin` | WeCom API base URL, overrideable for proxy/private-network deployments. | + +## Events + +| Event | Status | Notes | +|-------|--------|-------| +| `message.received` | Plugin E2E UI covered for text | Text, image, file, and voice payloads convert to common EBA message components in unit tests. Real WeChat customer-side UI text reached `EBAEventProbe` on May 27, 2026. | +| `platform.specific` | Unit covered | Non-message or unknown Customer Service payloads become structured `PlatformSpecificEvent` records. | + +## Common APIs + +| API | Status | Notes | +|-----|--------|-------| +| `send_message` | Plugin E2E outbound covered | Private/person target only. `target_id` must be `external_userid|open_kfid`. Text and image are implemented; voice/file are explicitly unsupported. | +| `reply_message` | Plugin E2E partial | Replies through Customer Service `kf/send_msg` using the original `source_platform_object`. The pipeline reply path reached the send API, but the dev account later hit WeCom `95001 send msg count limit`. | +| `get_message` | Plugin E2E covered from cache | Returns cached inbound `MessageReceivedEvent` by message ID. | +| `get_user_info` | Plugin E2E covered | Uses cached event users first, then Customer Service `customer/batchget`. | +| `get_friend_list` | Plugin E2E covered, partial | Returns customer users seen by this adapter instance. | +| `call_platform_api` | Unit covered | See platform-specific APIs below. | +| `edit_message` / `delete_message` | Not supported | WeCom Customer Service does not expose a general edit/delete endpoint for bot-sent messages in this adapter. | +| Group/member/moderation APIs | Not supported | Customer Service conversations handled here are private customer sessions, not group chats. | +| `upload_file` / `get_file_url` | Not supported | Media upload is used internally for outbound image; no portable file URL common API is exposed. | + +## Platform-Specific APIs + +| Action | Status | Notes | +|--------|--------|-------| +| `check_access_token` | Unit covered | Checks whether the current access token is present. | +| `refresh_access_token` | Unit covered | Refreshes the Customer Service access token. | +| `get_customer_info` | Unit covered | Calls Customer Service customer lookup by `external_userid`. | + +## Message Components + +Receive: + +| Component | Status | Notes | +|-----------|--------|-------| +| `Source` | Unit covered | Uses Customer Service `msgid` and `send_time`. | +| `Plain` | Unit covered | Text payload content is preserved. | +| `Image` | Unit covered | Uses the base64 data URL produced by the existing SDK image download path. | +| `Voice` | Unit covered | Maps exposed voice media ID to common `Voice.voice_id`; live UI evidence pending. | +| `File` | Unit covered | Maps exposed file media ID/name/size to common `File`; live UI evidence pending. | +| `Quote`, `At`, `AtAll`, `Face`, `Forward` | Not supported inbound | The current Customer Service SDK event model does not expose these as structured inbound fields. | +| `Unknown` | Unit covered | Unsupported message types become `Unknown` in message conversion or `platform.specific` at event level. | + +Send: + +| Component | Status | Notes | +|-----------|--------|-------| +| `Plain` | Plugin E2E outbound covered | Sends through `kf/send_msg` text. | +| `Image` | Plugin E2E outbound covered | Uploads media as WeCom image media and sends through `kf/send_msg` image. | +| `Quote`, `At`, `AtAll`, `Forward` | Unit covered fallback, live partially blocked | Flattened to text where possible. In the May 27 sweep, later text sends hit WeCom `95001 send msg count limit` after the successful text/image sends. | +| `Voice`, `File`, `Face` | Not supported | The adapter raises `NotSupportedError`; no tested Customer Service send path is implemented. | + +## Unit Verification + +Covered by: + +```bash +PYTHONPATH=/Users/wangqiang/code/python/langbot-plugin-sdk/src uv run pytest tests/unit_tests/platform/test_wecomcs_eba_adapter.py +``` + +Result on May 27, 2026: `10 passed`. + +The local `PYTHONPATH` is required in this workspace because the installed SDK package in the LangBot venv does not contain the newer `langbot_plugin.api.entities.builtin.platform.errors` module; the existing EBA adapter tests need the same SDK override. + +## Live Probe + +Auxiliary direct adapter probe: + +```bash +PYTHONPATH=/path/to/langbot-plugin-sdk/src uv run python -m py_compile tests/e2e/live_wecomcs_eba_probe.py + +WECOMCS_CORPID=... \ +WECOMCS_SECRET=... \ +WECOMCS_TOKEN=... \ +WECOMCS_ENCODING_AES_KEY=... \ +PYTHONPATH=/path/to/langbot-plugin-sdk/src \ +uv run python tests/e2e/live_wecomcs_eba_probe.py \ + --path /wecomcs/callback \ + --log data/temp/wecomcs_eba_live_probe.jsonl +``` + +This probe is diagnostic only. Final EBA acceptance still requires the standalone SDK runtime plus `EBAEventProbe` plugin path. + +## Standalone Runtime Plugin E2E Record + +Completed partial plugin E2E on May 27, 2026 against `dev.rockchin.top` and the WeChat customer-side UI entry `微信 -> 客服消息 -> 浪波智能客服`. + +Evidence: + +- Server JSONL: `/home/wgc/LangBotxg/LangBotEbaTest/data/temp/wecomcs_eba_plugin_probe.jsonl` +- Trigger text: `EBA wecomcs dedupe probe 2026-05-27` +- `bot_uuid`: `cc810d2c-91f3-4f92-8f27-e1bf9f7b6cb4` +- `adapter_name`: `wecomcs-eba` +- Observed common event: `MessageReceived`, `event.type=message.received` +- Observed message chain: `Source + Plain` +- Observed chat: `chat_type=private`, `chat_id=external_userid|open_kfid` +- Observed sender: customer `User` with nickname/avatar from Customer Service lookup +- Plugin API probe: `send_message`, `get_message`, `get_user_info`, `get_friend_list`, plugin/workspace storage, and manifest/list APIs succeeded +- Component sweep: outbound `Plain` and `Image` succeeded; `Face` and `File` returned explicit `NotSupportedError`; later quote/forward fallback sends were blocked by WeCom `95001 send msg count limit` + +Command shape used: + +```bash +cd langbot-plugin-sdk +uv run python -m langbot_plugin.cli.__init__ rt --debug-only --ws-control-port 5400 --ws-debug-port 5401 --skip-deps-check + +cd LangBot +PYTHONPATH=/absolute/path/to/langbot-plugin-sdk/src uv run main.py --standalone-runtime + +cd data/plugins/LangBot__EBAEventProbe +DEBUG_RUNTIME_WS_URL=ws://127.0.0.1:5401/plugin/ws \ +EBA_PROBE_LOG=/absolute/path/to/LangBot/data/temp/wecomcs_eba_plugin_probe.jsonl \ +EBA_PROBE_API=1 \ +EBA_PROBE_COMPONENT_SWEEP=1 \ +EBA_PROBE_PLATFORM_API=1 \ +uv --project /absolute/path/to/langbot-plugin-sdk run python -m langbot_plugin.cli.__init__ run +``` + +Required real UI trigger: send a Customer Service message from the WeCom/WeChat customer-side UI to the configured `dev.rockchin.top` Customer Service account. + +## Current Acceptance + +Current status is **partial EBA acceptance**. + +Blocked or pending items: + +- Inbound UI media (`Image`, `Voice`, `File`) was not sent from the real WeChat customer UI during this run, so receive-side media remains unit-covered only. +- Pipeline auto-reply reached `kf/send_msg`, but the test account hit WeCom `95001 send msg count limit` after successful plugin outbound text/image sends. This is recorded as an account/platform rate-limit block, not a conversion or API-shape failure. +- The current `EBAEventProbe` run did not call the adapter-specific `call_platform_api` actions (`check_access_token`, `refresh_access_token`, `get_customer_info`); the platform API map remains unit-covered. +- Inbound voice/file depends on whether the real Customer Service callback plus `sync_msg` endpoint returns those fields in the shape the local SDK models. +- Group, member, edit, delete, moderation, and standalone file URL APIs are intentionally not declared because this Customer Service protocol path does not provide tested common equivalents. diff --git a/src/langbot/libs/wecom_customer_service_api/api.py b/src/langbot/libs/wecom_customer_service_api/api.py index 70270b72..3bc37047 100644 --- a/src/langbot/libs/wecom_customer_service_api/api.py +++ b/src/langbot/libs/wecom_customer_service_api/api.py @@ -207,7 +207,33 @@ class WecomCSClient: return await self.send_text_msg(open_kfid, external_userid, msgid, content) if data['errcode'] != 0: await self.logger.error(f'发送消息失败:{data}') - raise Exception('Failed to send message') + raise Exception(f'Failed to send message: {data}') + return data + + async def send_image_msg(self, open_kfid: str, external_userid: str, msgid: str, media_id: str): + if not await self.check_access_token(): + self.access_token = await self.get_access_token(self.secret) + + url = f'{self.base_url}/kf/send_msg?access_token={self.access_token}' + payload = { + 'touser': external_userid, + 'open_kfid': open_kfid, + 'msgid': msgid, + 'msgtype': 'image', + 'image': { + 'media_id': media_id, + }, + } + + async with httpx.AsyncClient() as client: + response = await client.post(url, json=payload) + data = response.json() + if data['errcode'] == 40014 or data['errcode'] == 42001: + self.access_token = await self.get_access_token(self.secret) + return await self.send_image_msg(open_kfid, external_userid, msgid, media_id) + if data['errcode'] != 0: + await self.logger.error(f'发送图片消息失败:{data}') + raise Exception('Failed to send image message') return data async def handle_callback_request(self): @@ -322,7 +348,7 @@ class WecomCSClient: if not await self.check_access_token(): self.access_token = await self.get_access_token(self.secret) - url = self.base_url + '/media/upload?access_token=' + self.access_token + '&type=file' + url = self.base_url + '/media/upload?access_token=' + self.access_token + '&type=image' file_bytes = None file_name = 'uploaded_file.txt' @@ -368,7 +394,7 @@ class WecomCSClient: self.access_token = await self.get_access_token(self.secret) media_id = await self.upload_to_work(image) if data.get('errcode', 0) != 0: - raise Exception('failed to upload file') + raise Exception(f'failed to upload image: {data}') media_id = data.get('media_id') return media_id diff --git a/src/langbot/pkg/platform/adapters/wecomcs/__init__.py b/src/langbot/pkg/platform/adapters/wecomcs/__init__.py new file mode 100644 index 00000000..e1483424 --- /dev/null +++ b/src/langbot/pkg/platform/adapters/wecomcs/__init__.py @@ -0,0 +1,5 @@ +"""WeCom Customer Service EBA platform adapter.""" + +from langbot.pkg.platform.adapters.wecomcs.adapter import WecomCSAdapter + +__all__ = ['WecomCSAdapter'] diff --git a/src/langbot/pkg/platform/adapters/wecomcs/adapter.py b/src/langbot/pkg/platform/adapters/wecomcs/adapter.py new file mode 100644 index 00000000..017482b5 --- /dev/null +++ b/src/langbot/pkg/platform/adapters/wecomcs/adapter.py @@ -0,0 +1,227 @@ +from __future__ import annotations + +import asyncio +import time +import traceback +import typing +import uuid + +import pydantic + +from langbot.libs.wecom_customer_service_api.api import WecomCSClient +from langbot.libs.wecom_customer_service_api.wecomcsevent import WecomCSEvent +import langbot_plugin.api.definition.abstract.platform.adapter as abstract_platform_adapter +import langbot_plugin.api.definition.abstract.platform.event_logger as abstract_platform_logger +from langbot.pkg.platform.adapters.wecomcs.api_impl import WecomCSAPIMixin +from langbot.pkg.platform.adapters.wecomcs.event_converter import WecomCSEventConverter +from langbot.pkg.platform.adapters.wecomcs.message_converter import WecomCSMessageConverter +from langbot.pkg.platform.adapters.wecomcs.platform_api import PLATFORM_API_MAP +from langbot.pkg.platform.adapters.wecomcs.types import parse_private_chat_id +from langbot_plugin.api.entities.builtin.platform import events as platform_events +from langbot_plugin.api.entities.builtin.platform import message as platform_message +from langbot_plugin.api.entities.builtin.platform.errors import NotSupportedError + + +class WecomCSAdapter(WecomCSAPIMixin, abstract_platform_adapter.AbstractPlatformAdapter): + bot: WecomCSClient = pydantic.Field(exclude=True) + + message_converter: WecomCSMessageConverter = WecomCSMessageConverter() + event_converter: WecomCSEventConverter = WecomCSEventConverter() + + config: dict + bot_uuid: str | None = None + listeners: dict[ + typing.Type[platform_events.Event], + typing.Callable[[platform_events.Event, abstract_platform_adapter.AbstractMessagePlatformAdapter], None], + ] = {} + _message_cache: dict[str, platform_events.MessageReceivedEvent] = {} + _user_cache: dict[str, typing.Any] = {} + + class Config: + arbitrary_types_allowed = True + + def __init__(self, config: dict, logger: abstract_platform_logger.AbstractEventLogger): + required_keys = [ + 'corpid', + 'secret', + 'token', + 'EncodingAESKey', + ] + missing_keys = [key for key in required_keys if key not in config] + if missing_keys: + raise Exception(f'WeComCS missing required config fields: {missing_keys}') + + bot = WecomCSClient( + corpid=config['corpid'], + secret=config['secret'], + token=config['token'], + EncodingAESKey=config['EncodingAESKey'], + logger=logger, + unified_mode=True, + api_base_url=config.get('api_base_url', 'https://qyapi.weixin.qq.com/cgi-bin'), + ) + + super().__init__( + config=config, + logger=logger, + bot=bot, + bot_account_id='', + bot_uuid=None, + listeners={}, + _message_cache={}, + _user_cache={}, + ) + self._register_native_handlers() + + def set_bot_uuid(self, bot_uuid: str): + self.bot_uuid = bot_uuid + + def get_supported_events(self) -> list[str]: + return [ + 'message.received', + 'platform.specific', + ] + + def get_supported_apis(self) -> list[str]: + return [ + 'send_message', + 'reply_message', + 'get_message', + 'get_user_info', + 'get_friend_list', + 'call_platform_api', + ] + + async def send_message( + self, + target_type: str, + target_id: str, + message: platform_message.MessageChain, + ) -> platform_events.MessageResult: + if target_type not in ('person', 'private'): + raise NotSupportedError(f'send_message:{target_type}') + + external_userid, open_kfid = parse_private_chat_id(target_id) + content_list = await WecomCSMessageConverter.yiri2target(message, self.bot) + raw_results = [] + for content in content_list: + raw_results.append(await self._send_content(open_kfid, external_userid, self._make_outbound_msgid(), content)) + return platform_events.MessageResult(raw={'results': raw_results}) + + async def reply_message( + self, + message_source: platform_events.MessageEvent, + message: platform_message.MessageChain, + quote_origin: bool = False, + ) -> platform_events.MessageResult: + wecom_event = await WecomCSEventConverter.yiri2target(message_source) + if not isinstance(wecom_event, WecomCSEvent): + raise ValueError('WeComCS reply_message requires a WecomCSEvent source object') + content_list = await WecomCSMessageConverter.yiri2target(message, self.bot) + raw_results = [] + for content in content_list: + raw_results.append( + await self._send_content( + wecom_event.receiver_id, + wecom_event.user_id, + self._make_outbound_msgid(), + content, + ) + ) + return platform_events.MessageResult(message_id=wecom_event.message_id, raw={'results': raw_results}) + + async def call_platform_api(self, action: str, params: dict = {}) -> dict: + handler = PLATFORM_API_MAP.get(action) + if handler is None: + raise NotSupportedError(f'call_platform_api:{action}') + return await handler(self.bot, params) + + def register_listener( + self, + event_type: typing.Type[platform_events.Event], + callback: typing.Callable[ + [platform_events.Event, abstract_platform_adapter.AbstractMessagePlatformAdapter], None + ], + ): + self.listeners[event_type] = callback + + def unregister_listener( + self, + event_type: typing.Type[platform_events.Event], + callback: typing.Callable[ + [platform_events.Event, abstract_platform_adapter.AbstractMessagePlatformAdapter], None + ], + ): + registered = self.listeners.get(event_type) + if registered is callback: + self.listeners.pop(event_type, None) + + async def handle_unified_webhook(self, bot_uuid: str, path: str, request): + return await self.bot.handle_unified_webhook(request) + + async def run_async(self): + async def keep_alive(): + while True: + await asyncio.sleep(1) + + await self.logger.info('WeComCS EBA adapter running in unified webhook mode') + await keep_alive() + + async def kill(self) -> bool: + return True + + async def is_muted(self, group_id: int | None = None) -> bool: + return False + + def _register_native_handlers(self): + async def on_message(event: WecomCSEvent): + await self._handle_native_event(event) + + for msg_type in ('text', 'image', 'file', 'voice'): + self.bot.on_message(msg_type)(on_message) + + async def _handle_native_event(self, event: WecomCSEvent): + self.bot_account_id = event.receiver_id or self.bot_account_id + try: + if event.message_id and str(event.message_id) in self._message_cache: + await self.logger.debug(f'Skip duplicated WeComCS message: {event.message_id}') + return + + if platform_events.FriendMessage in self.listeners: + legacy_event = await self.event_converter.target2legacy(event, self.bot) + if legacy_event: + callback = self.listeners.get(type(legacy_event)) + if callback: + await callback(legacy_event, self) + + eba_event = await self.event_converter.target2yiri(event, self.bot) + if eba_event: + self._cache_event(eba_event) + await self._dispatch_eba_event(eba_event) + except Exception: + await self.logger.error(f'Error in wecomcs native event: {traceback.format_exc()}') + + async def _dispatch_eba_event(self, event: platform_events.EBAEvent): + for event_type in (type(event), platform_events.EBAEvent, platform_events.Event): + callback = self.listeners.get(event_type) + if callback: + await callback(event, self) + return + + def _cache_event(self, event: platform_events.Event): + if not isinstance(event, platform_events.MessageReceivedEvent): + return + self._message_cache[str(event.message_id)] = event + self._user_cache[str(event.sender.id)] = event.sender + + async def _send_content(self, open_kfid: str, external_userid: str, msgid: str, content: dict): + content_type = content.get('type') + if content_type == 'text': + return await self.bot.send_text_msg(open_kfid, external_userid, msgid, content.get('content', '')) + if content_type == 'image': + return await self.bot.send_image_msg(open_kfid, external_userid, msgid, content['media_id']) + raise NotSupportedError(f'send_content:{content_type}') + + @staticmethod + def _make_outbound_msgid() -> str: + return f'lb-{int(time.time() * 1000)}-{uuid.uuid4().hex[:8]}' diff --git a/src/langbot/pkg/platform/adapters/wecomcs/api_impl.py b/src/langbot/pkg/platform/adapters/wecomcs/api_impl.py new file mode 100644 index 00000000..3fca6327 --- /dev/null +++ b/src/langbot/pkg/platform/adapters/wecomcs/api_impl.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +import typing + +from langbot.libs.wecom_customer_service_api.api import WecomCSClient +from langbot_plugin.api.entities.builtin.platform import entities as platform_entities +from langbot_plugin.api.entities.builtin.platform import events as platform_events +from langbot_plugin.api.entities.builtin.platform import message as platform_message +from langbot_plugin.api.entities.builtin.platform.errors import NotSupportedError + + +class WecomCSAPIMixin: + bot: WecomCSClient + _message_cache: dict[str, platform_events.MessageReceivedEvent] + _user_cache: dict[str, platform_entities.User] + + async def get_message( + self, + chat_type: str, + chat_id: typing.Union[int, str], + message_id: typing.Union[int, str], + ) -> platform_events.MessageReceivedEvent: + event = self._message_cache.get(str(message_id)) + if event is None: + raise NotSupportedError('get_message:message_not_cached') + return event + + async def get_user_info(self, user_id: typing.Union[int, str]) -> platform_entities.User: + cached = self._user_cache.get(str(user_id)) + if cached is not None: + return cached + info = await self.bot.get_customer_info(str(user_id)) + if not info: + raise NotSupportedError('get_user_info:not_found') + return platform_entities.User( + id=info.get('external_userid') or user_id, + nickname=info.get('nickname') or str(user_id), + avatar_url=info.get('avatar'), + username=info.get('external_userid') or None, + ) + + async def get_friend_list(self) -> list[platform_entities.User]: + return list(self._user_cache.values()) + + async def upload_file(self, file_data: bytes, filename: str) -> str: + raise NotSupportedError('upload_file') + + async def get_file_url(self, file_id: str) -> str: + raise NotSupportedError('get_file_url') + + async def get_group_info(self, group_id: typing.Union[int, str]) -> platform_entities.UserGroup: + raise NotSupportedError('get_group_info') + + async def get_group_member_list( + self, + group_id: typing.Union[int, str], + ) -> list[platform_entities.UserGroupMember]: + raise NotSupportedError('get_group_member_list') + + async def get_group_member_info( + self, + group_id: typing.Union[int, str], + user_id: typing.Union[int, str], + ) -> platform_entities.UserGroupMember: + raise NotSupportedError('get_group_member_info') + + async def edit_message( + self, + chat_type: str, + chat_id: typing.Union[int, str], + message_id: typing.Union[int, str], + new_content: platform_message.MessageChain, + ) -> None: + raise NotSupportedError('edit_message') + + async def delete_message( + self, + chat_type: str, + chat_id: typing.Union[int, str], + message_id: typing.Union[int, str], + ) -> None: + raise NotSupportedError('delete_message') diff --git a/src/langbot/pkg/platform/adapters/wecomcs/event_converter.py b/src/langbot/pkg/platform/adapters/wecomcs/event_converter.py new file mode 100644 index 00000000..7c074365 --- /dev/null +++ b/src/langbot/pkg/platform/adapters/wecomcs/event_converter.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +import typing + +from langbot.libs.wecom_customer_service_api.api import WecomCSClient +from langbot.libs.wecom_customer_service_api.wecomcsevent import WecomCSEvent +import langbot_plugin.api.definition.abstract.platform.adapter as abstract_platform_adapter +from langbot.pkg.platform.adapters.wecomcs.message_converter import WecomCSMessageConverter +from langbot.pkg.platform.adapters.wecomcs.types import ADAPTER_NAME, make_private_chat_id +from langbot_plugin.api.entities.builtin.platform import entities as platform_entities +from langbot_plugin.api.entities.builtin.platform import events as platform_events + + +class WecomCSEventConverter(abstract_platform_adapter.AbstractEventConverter): + @staticmethod + async def yiri2target(event: platform_events.Event) -> WecomCSEvent | None: + return getattr(event, 'source_platform_object', None) + + @staticmethod + async def target2legacy(event: WecomCSEvent, bot: WecomCSClient | None = None) -> platform_events.FriendMessage | None: + eba_event = await WecomCSEventConverter.target2yiri(event, bot) + if hasattr(eba_event, 'to_legacy_event'): + return eba_event.to_legacy_event() + return None + + @staticmethod + async def target2yiri(event: WecomCSEvent, bot: WecomCSClient | None = None) -> platform_events.Event | None: + if event.type in {'text', 'image', 'file', 'voice'}: + return await WecomCSEventConverter.message_to_eba(event, bot) + return WecomCSEventConverter.platform_specific(event, f'wecomcs.{event.type or "unknown"}') + + @staticmethod + async def message_to_eba(event: WecomCSEvent, bot: WecomCSClient | None = None) -> platform_events.MessageReceivedEvent: + message_chain = await WecomCSMessageConverter.target2yiri(event) + sender = await WecomCSEventConverter.user_from_event(event, bot) + return platform_events.MessageReceivedEvent( + type='message.received', + adapter_name=ADAPTER_NAME, + message_id=event.message_id or '', + message_chain=message_chain, + sender=sender, + chat_type=platform_entities.ChatType.PRIVATE, + chat_id=make_private_chat_id(event.user_id, event.receiver_id), + group=None, + timestamp=float(event.timestamp or 0), + source_platform_object=event, + ) + + @staticmethod + async def user_from_event(event: WecomCSEvent, bot: WecomCSClient | None = None) -> platform_entities.User: + nickname = str(event.user_id or '') + avatar_url = None + raw: dict[str, typing.Any] = {} + if bot and event.user_id: + try: + raw = await bot.get_customer_info(event.user_id) or {} + nickname = raw.get('nickname') or nickname + avatar_url = raw.get('avatar') + except Exception: + raw = {} + + return platform_entities.User( + id=event.user_id or '', + nickname=nickname, + avatar_url=avatar_url, + username=raw.get('external_userid') or None, + ) + + @staticmethod + def platform_specific(event: WecomCSEvent, action: str) -> platform_events.PlatformSpecificEvent: + return platform_events.PlatformSpecificEvent( + type='platform.specific', + adapter_name=ADAPTER_NAME, + action=action, + data=dict(event), + timestamp=float(event.timestamp or 0), + source_platform_object=event, + ) diff --git a/src/langbot/pkg/platform/adapters/wecomcs/manifest.yaml b/src/langbot/pkg/platform/adapters/wecomcs/manifest.yaml new file mode 100644 index 00000000..b891b1d0 --- /dev/null +++ b/src/langbot/pkg/platform/adapters/wecomcs/manifest.yaml @@ -0,0 +1,106 @@ +apiVersion: v1 +kind: MessagePlatformAdapter + +metadata: + name: wecomcs-eba + label: + en_US: WeCom Customer Service (EBA) + zh_Hans: 企业微信客服 (EBA) + zh_Hant: 企業微信客服 (EBA) + description: + en_US: WeCom Customer Service adapter with Event-Based Agents support + zh_Hans: 企业微信客服适配器(EBA 架构版本),通过统一 Webhook 接收客服会话消息 + zh_Hant: 企業微信客服適配器(EBA 架構版本),透過統一 Webhook 接收客服會話訊息 + icon: wecom.png + +spec: + categories: + - china + help_links: + zh: https://link.langbot.app/zh/platforms/wecomcs + en: https://link.langbot.app/en/platforms/wecomcs + ja: https://link.langbot.app/ja/platforms/wecomcs + config: + - name: webhook_url + label: + en_US: Webhook Callback URL + zh_Hans: Webhook 回调地址 + zh_Hant: Webhook 回調地址 + description: + en_US: Copy this URL and paste it into your WeCom Customer Service webhook configuration. + zh_Hans: 复制此地址并粘贴到企业微信客服的 Webhook 配置中。 + zh_Hant: 複製此地址並貼到企業微信客服的 Webhook 設定中。 + type: webhook-url + required: false + default: "" + - name: corpid + label: + en_US: Corpid + zh_Hans: 企业ID + zh_Hant: 企業ID + type: string + required: true + default: "" + - name: secret + label: + en_US: Secret + zh_Hans: 密钥 (Secret) + zh_Hant: 密鑰 (Secret) + type: string + required: true + default: "" + - name: token + label: + en_US: Token + zh_Hans: 令牌 (Token) + zh_Hant: 令牌 (Token) + type: string + required: true + default: "" + - name: EncodingAESKey + label: + en_US: EncodingAESKey + zh_Hans: 消息加解密密钥 (EncodingAESKey) + zh_Hant: 訊息加解密密鑰 (EncodingAESKey) + type: string + required: true + default: "" + - name: api_base_url + label: + en_US: API Base URL + zh_Hans: API 基础 URL + zh_Hant: API 基礎 URL + description: + en_US: Optional WeCom API base URL for private network or reverse proxy deployments. + zh_Hans: 可选,若部署在内网环境并通过反向代理访问企业微信 API,可根据文档填写此项 + zh_Hant: 可選,若部署在內網環境並透過反向代理存取企業微信 API,可根據文件填寫此項 + type: string + required: false + default: "https://qyapi.weixin.qq.com/cgi-bin" + + supported_events: + - message.received + - platform.specific + + supported_apis: + required: + - send_message + - reply_message + optional: + - get_message + - get_user_info + - get_friend_list + - call_platform_api + + platform_specific_apis: + - action: check_access_token + description: { en_US: "Check whether the current WeCom Customer Service access token is usable", zh_Hans: "检查当前企业微信客服 access token 是否可用" } + - action: refresh_access_token + description: { en_US: "Refresh the WeCom Customer Service access token", zh_Hans: "刷新企业微信客服 access token" } + - action: get_customer_info + description: { en_US: "Get WeCom Customer Service customer information by external user ID", zh_Hans: "按 external_userid 获取企业微信客服客户信息" } + +execution: + python: + path: ./adapter.py + attr: WecomCSAdapter diff --git a/src/langbot/pkg/platform/adapters/wecomcs/message_converter.py b/src/langbot/pkg/platform/adapters/wecomcs/message_converter.py new file mode 100644 index 00000000..4d4ac749 --- /dev/null +++ b/src/langbot/pkg/platform/adapters/wecomcs/message_converter.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +import datetime + +from langbot.libs.wecom_customer_service_api.api import WecomCSClient +import langbot_plugin.api.definition.abstract.platform.adapter as abstract_platform_adapter +from langbot_plugin.api.entities.builtin.platform import message as platform_message +from langbot_plugin.api.entities.builtin.platform.errors import NotSupportedError + + +def split_string_by_bytes(text: str, limit: int = 2048, encoding: str = 'utf-8') -> list[str]: + """Split text without cutting a multi-byte character in half.""" + bytes_data = text.encode(encoding) + total_len = len(bytes_data) + parts: list[str] = [] + start = 0 + + while start < total_len: + end = min(start + limit, total_len) + chunk = bytes_data[start:end] + part = chunk.decode(encoding, errors='ignore') + part_len = len(part.encode(encoding)) + if part_len == 0 and end < total_len: + start += 1 + continue + parts.append(part) + start += part_len + + return parts + + +class WecomCSMessageConverter(abstract_platform_adapter.AbstractMessageConverter): + @staticmethod + async def yiri2target(message_chain: platform_message.MessageChain, bot: WecomCSClient) -> list[dict]: + content_list: list[dict] = [] + + for msg in message_chain: + if isinstance(msg, platform_message.Source): + continue + if isinstance(msg, platform_message.Plain): + content_list.extend({'type': 'text', 'content': chunk} for chunk in split_string_by_bytes(msg.text)) + elif isinstance(msg, platform_message.Image): + content_list.append({'type': 'image', 'media_id': await bot.get_media_id(msg)}) + elif isinstance(msg, platform_message.Forward): + for node in msg.node_list: + content_list.extend(await WecomCSMessageConverter.yiri2target(node.message_chain, bot)) + elif isinstance(msg, platform_message.Quote): + if msg.id is not None: + content_list.append({'type': 'text', 'content': f'[Quote {msg.id}] '}) + if msg.origin: + content_list.extend(await WecomCSMessageConverter.yiri2target(msg.origin, bot)) + elif isinstance(msg, platform_message.At): + content_list.append({'type': 'text', 'content': f'@{msg.display or msg.target}'}) + elif isinstance(msg, platform_message.AtAll): + content_list.append({'type': 'text', 'content': '@all'}) + elif isinstance(msg, (platform_message.Voice, platform_message.File, platform_message.Face)): + raise NotSupportedError(f'wecomcs_send_component:{msg.type}') + else: + content_list.append({'type': 'text', 'content': str(msg)}) + + return content_list + + @staticmethod + async def target2yiri(event: dict) -> platform_message.MessageChain: + message_id = event.get('msgid') or '' + timestamp = event.get('send_time') or event.get('sendtime') or datetime.datetime.now().timestamp() + components: list[platform_message.MessageComponent] = [ + platform_message.Source(id=message_id, time=datetime.datetime.fromtimestamp(float(timestamp))), + ] + + msgtype = event.get('msgtype') + if msgtype == 'text': + components.append(platform_message.Plain(text=(event.get('text') or {}).get('content', ''))) + elif msgtype == 'image': + components.append(platform_message.Image(base64=event.get('picurl') or '')) + elif msgtype == 'file': + file_data = event.get('file') or {} + components.append( + platform_message.File( + id=file_data.get('media_id'), + name=file_data.get('filename') or file_data.get('file_name') or '', + size=file_data.get('file_size') or 0, + ) + ) + elif msgtype == 'voice': + voice_data = event.get('voice') or {} + components.append(platform_message.Voice(voice_id=voice_data.get('media_id') or '')) + else: + components.append(platform_message.Unknown(text=f'[unsupported wecomcs msgtype: {msgtype or "unknown"}]')) + + return platform_message.MessageChain(components) diff --git a/src/langbot/pkg/platform/adapters/wecomcs/platform_api.py b/src/langbot/pkg/platform/adapters/wecomcs/platform_api.py new file mode 100644 index 00000000..3f6bd2ba --- /dev/null +++ b/src/langbot/pkg/platform/adapters/wecomcs/platform_api.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +import typing + +from langbot.libs.wecom_customer_service_api.api import WecomCSClient + + +async def check_access_token(bot: WecomCSClient, params: dict) -> dict: + return {'valid': await bot.check_access_token()} + + +async def refresh_access_token(bot: WecomCSClient, params: dict) -> dict: + bot.access_token = await bot.get_access_token(bot.secret) + return {'ok': bool(bot.access_token)} + + +async def get_customer_info(bot: WecomCSClient, params: dict) -> dict: + user_id = params.get('external_userid') or params.get('user_id') or params.get('userid') + if not user_id: + raise ValueError('external_userid is required') + info = await bot.get_customer_info(str(user_id)) + return info or {} + + +PLATFORM_API_MAP: dict[str, typing.Callable[[WecomCSClient, dict], typing.Awaitable[dict]]] = { + 'check_access_token': check_access_token, + 'refresh_access_token': refresh_access_token, + 'get_customer_info': get_customer_info, +} diff --git a/src/langbot/pkg/platform/adapters/wecomcs/types.py b/src/langbot/pkg/platform/adapters/wecomcs/types.py new file mode 100644 index 00000000..ce8c7e45 --- /dev/null +++ b/src/langbot/pkg/platform/adapters/wecomcs/types.py @@ -0,0 +1,19 @@ +from __future__ import annotations + +ADAPTER_NAME = 'wecomcs-eba' + + +def make_private_chat_id(user_id: str | int | None, open_kfid: str | int | None) -> str: + """Build the routable private chat id used by the WeCom CS EBA adapter.""" + user = str(user_id or '') + kfid = str(open_kfid or '') + if not user or not kfid: + return user + return f'{user}|{kfid}' + + +def parse_private_chat_id(chat_id: str | int) -> tuple[str, str]: + user_id, sep, open_kfid = str(chat_id).partition('|') + if not user_id or not sep or not open_kfid: + raise ValueError('WeComCS target_id must be formatted as "external_userid|open_kfid"') + return user_id, open_kfid diff --git a/src/langbot/pkg/platform/adapters/wecomcs/wecom.png b/src/langbot/pkg/platform/adapters/wecomcs/wecom.png new file mode 100644 index 00000000..8588c20d Binary files /dev/null and b/src/langbot/pkg/platform/adapters/wecomcs/wecom.png differ diff --git a/tests/e2e/live_wecomcs_eba_probe.py b/tests/e2e/live_wecomcs_eba_probe.py new file mode 100644 index 00000000..5a4b6f67 --- /dev/null +++ b/tests/e2e/live_wecomcs_eba_probe.py @@ -0,0 +1,211 @@ +from __future__ import annotations + +import argparse +import asyncio +import json +import os +from pathlib import Path +from typing import Any + +from quart import Quart, request + +from langbot.pkg.platform.adapters.wecomcs.adapter import WecomCSAdapter +from langbot_plugin.api.definition.abstract.platform.event_logger import AbstractEventLogger +from langbot_plugin.api.entities.builtin.platform import events as platform_events +from langbot_plugin.api.entities.builtin.platform import message as platform_message + + +TINY_PNG = ( + 'data:image/png;base64,' + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=' +) + + +class ProbeLogger(AbstractEventLogger): + async def info(self, text, images=None, message_session_id=None, no_throw=True): + print(f'[info] {text}') + + async def debug(self, text, images=None, message_session_id=None, no_throw=True): + print(f'[debug] {text}') + + async def warning(self, text, images=None, message_session_id=None, no_throw=True): + print(f'[warning] {text}') + + async def error(self, text, images=None, message_session_id=None, no_throw=True): + print(f'[error] {text}') + + +def redact(value: Any) -> Any: + if isinstance(value, dict): + redacted = {} + for key, item in value.items(): + if key.lower() in {'secret', 'token', 'encodingaeskey', 'access_token'}: + redacted[key] = '' + else: + redacted[key] = redact(item) + return redacted + if isinstance(value, list): + return [redact(item) for item in value] + return value + + +def summarize_event(event: platform_events.EBAEvent) -> dict: + data = { + 'type': event.type, + 'adapter_name': event.adapter_name, + 'timestamp': event.timestamp, + } + for field in ('message_id', 'chat_id', 'chat_type', 'action', 'data'): + if hasattr(event, field): + value = getattr(event, field) + if hasattr(value, 'value'): + value = value.value + data[field] = redact(value) + if hasattr(event, 'sender') and event.sender is not None: + data['sender'] = event.sender.model_dump() + if hasattr(event, 'message_chain') and event.message_chain is not None: + data['message_chain'] = event.message_chain.model_dump() + return data + + +def record_api(results: list[dict[str, Any]], name: str, ok: bool, result: Any = None, error: Exception | None = None): + entry = {'name': name, 'ok': ok} + if result is not None: + entry['result'] = redact(result) + if error is not None: + entry['error'] = repr(error) + results.append(entry) + print('WECOMCS_EBA_API', json.dumps(entry, ensure_ascii=False, default=str)) + + +async def run_api(results: list[dict[str, Any]], name: str, func): + try: + result = await func() + record_api(results, name, True, result) + return result + except Exception as exc: + record_api(results, name, False, error=exc) + return None + + +def config_from_env() -> dict: + required = { + 'corpid': os.getenv('WECOMCS_CORPID') or os.getenv('WECOM_CORPID', ''), + 'secret': os.getenv('WECOMCS_SECRET') or os.getenv('WECOMCS_KF_SECRET', ''), + 'token': os.getenv('WECOMCS_TOKEN', ''), + 'EncodingAESKey': os.getenv('WECOMCS_ENCODING_AES_KEY', ''), + } + missing = [key for key, value in required.items() if not value] + if missing: + raise RuntimeError(f'Missing required WeComCS env vars for fields: {missing}') + return { + **required, + 'api_base_url': os.getenv('WECOMCS_API_BASE_URL', 'https://qyapi.weixin.qq.com/cgi-bin'), + } + + +async def run_probe(args: argparse.Namespace): + adapter = WecomCSAdapter(config_from_env(), ProbeLogger()) + events: list[platform_events.EBAEvent] = [] + api_results: list[dict[str, Any]] = [] + first_message = asyncio.Event() + log_path = Path(args.log) + log_path.parent.mkdir(parents=True, exist_ok=True) + + async def listener(event, adapter): + events.append(event) + with log_path.open('a', encoding='utf-8') as fp: + fp.write(json.dumps(summarize_event(event), ensure_ascii=False, default=str) + '\n') + print('WECOMCS_EBA_EVENT', json.dumps(summarize_event(event), ensure_ascii=False, default=str)) + if isinstance(event, platform_events.MessageReceivedEvent): + first_message.set() + + adapter.register_listener(platform_events.EBAEvent, listener) + + app = Quart(__name__) + + @app.route(args.path, methods=['GET', 'POST']) + async def callback(): + return await adapter.handle_unified_webhook(args.bot_uuid, '', request) + + server_task = asyncio.create_task(app.run_task(host=args.host, port=args.port)) + try: + print(f'READY: configure WeCom Customer Service callback URL to http://{args.host}:{args.port}{args.path}') + print('READY: send a real customer-service message from WeCom/WeChat UI to the bot now.') + await asyncio.wait_for(first_message.wait(), timeout=args.timeout) + + source = next(event for event in events if isinstance(event, platform_events.MessageReceivedEvent)) + + if not args.skip_api: + await run_api( + api_results, + 'reply_message:text', + lambda: adapter.reply_message( + source, + platform_message.MessageChain([platform_message.Plain(text='WeComCS EBA probe reply')]), + ), + ) + await run_api( + api_results, + 'send_message:text', + lambda: adapter.send_message( + 'person', + source.chat_id, + platform_message.MessageChain([platform_message.Plain(text='WeComCS EBA probe send')]), + ), + ) + await run_api( + api_results, + 'send_message:image', + lambda: adapter.send_message( + 'person', + source.chat_id, + platform_message.MessageChain( + [ + platform_message.Plain(text='WeComCS EBA probe image'), + platform_message.Image(base64=TINY_PNG), + ] + ), + ), + ) + await run_api(api_results, 'get_message', lambda: adapter.get_message('private', source.chat_id, source.message_id)) + await run_api(api_results, 'get_user_info', lambda: adapter.get_user_info(source.sender.id)) + await run_api(api_results, 'get_friend_list', lambda: adapter.get_friend_list()) + await run_api( + api_results, + 'call_platform_api:check_access_token', + lambda: adapter.call_platform_api('check_access_token', {}), + ) + await run_api( + api_results, + 'call_platform_api:get_customer_info', + lambda: adapter.call_platform_api('get_customer_info', {'external_userid': source.sender.id}), + ) + + summary = { + 'events': [event.type for event in events], + 'api_results': api_results, + 'log_path': str(log_path), + } + print('WECOMCS_EBA_SUMMARY', json.dumps(summary, ensure_ascii=False, default=str)) + return summary + finally: + server_task.cancel() + await adapter.kill() + + +def main(): + parser = argparse.ArgumentParser(description='Live WeCom Customer Service EBA adapter probe.') + parser.add_argument('--host', default='0.0.0.0') + parser.add_argument('--port', type=int, default=5313) + parser.add_argument('--path', default='/wecomcs/callback') + parser.add_argument('--timeout', type=int, default=180) + parser.add_argument('--bot-uuid', default='wecomcs-eba-live-probe') + parser.add_argument('--log', default='data/temp/wecomcs_eba_live_probe.jsonl') + parser.add_argument('--skip-api', action='store_true') + args = parser.parse_args() + asyncio.run(run_probe(args)) + + +if __name__ == '__main__': + main() diff --git a/tests/unit_tests/platform/test_wecomcs_eba_adapter.py b/tests/unit_tests/platform/test_wecomcs_eba_adapter.py new file mode 100644 index 00000000..3d147b5d --- /dev/null +++ b/tests/unit_tests/platform/test_wecomcs_eba_adapter.py @@ -0,0 +1,260 @@ +from __future__ import annotations + +import pathlib +from unittest.mock import AsyncMock, patch + +import pytest +import yaml + +from langbot.libs.wecom_customer_service_api.api import WecomCSClient +from langbot.libs.wecom_customer_service_api.wecomcsevent import WecomCSEvent +from langbot.pkg.platform.adapters.wecomcs.adapter import WecomCSAdapter +from langbot.pkg.platform.adapters.wecomcs.event_converter import WecomCSEventConverter +from langbot.pkg.platform.adapters.wecomcs.message_converter import WecomCSMessageConverter, split_string_by_bytes +from langbot.pkg.platform.adapters.wecomcs.platform_api import PLATFORM_API_MAP +from langbot_plugin.api.definition.abstract.platform.event_logger import AbstractEventLogger +from langbot_plugin.api.entities.builtin.platform import entities as platform_entities +from langbot_plugin.api.entities.builtin.platform import events as platform_events +from langbot_plugin.api.entities.builtin.platform import message as platform_message +from langbot_plugin.api.entities.builtin.platform.errors import NotSupportedError + + +class DummyLogger(AbstractEventLogger): + async def info(self, text, images=None, message_session_id=None, no_throw=True): + pass + + async def debug(self, text, images=None, message_session_id=None, no_throw=True): + pass + + async def warning(self, text, images=None, message_session_id=None, no_throw=True): + pass + + async def error(self, text, images=None, message_session_id=None, no_throw=True): + pass + + +class DummyWecomCSClient(WecomCSClient): + def __init__(self, *args, **kwargs): + self.corpid = kwargs['corpid'] + self.secret = kwargs['secret'] + self.token = kwargs['token'] + self.aes = kwargs['EncodingAESKey'] + self.base_url = kwargs.get('api_base_url', 'https://qyapi.weixin.qq.com/cgi-bin') + self.logger = kwargs.get('logger') + self.access_token = '' + self._message_handlers = {} + self.get_media_id = AsyncMock(return_value='media-id') + self.send_text_msg = AsyncMock(return_value={'msgid': 'sent-text'}) + self.send_image_msg = AsyncMock(return_value={'msgid': 'sent-image'}) + self.get_customer_info = AsyncMock( + return_value={'external_userid': 'external-1', 'nickname': 'Alice', 'avatar': 'https://example.test/a.png'} + ) + self.check_access_token = AsyncMock(return_value=True) + self.get_access_token = AsyncMock(return_value='access-token') + self.handle_unified_webhook = AsyncMock(return_value='success') + + def on_message(self, msg_type: str): + def decorator(func): + self._message_handlers.setdefault(msg_type, []).append(func) + return func + + return decorator + + +def manifest() -> dict: + manifest_path = ( + pathlib.Path(__file__).parents[3] + / 'src' + / 'langbot' + / 'pkg' + / 'platform' + / 'adapters' + / 'wecomcs' + / 'manifest.yaml' + ) + return yaml.safe_load(manifest_path.read_text()) + + +def make_adapter() -> WecomCSAdapter: + config = { + 'corpid': 'corp-id', + 'secret': 'secret', + 'token': 'token', + 'EncodingAESKey': 'encoding-key', + 'api_base_url': 'https://qyapi.weixin.qq.com/cgi-bin', + } + with patch('langbot.pkg.platform.adapters.wecomcs.adapter.WecomCSClient', DummyWecomCSClient): + return WecomCSAdapter(config, DummyLogger()) + + +def wecomcs_event(**overrides) -> WecomCSEvent: + msgtype = overrides.get('msgtype', 'text') + payload = { + 'msgtype': msgtype, + 'msgid': overrides.get('message_id', 'msg-1'), + 'external_userid': overrides.get('external_userid', 'external-1'), + 'open_kfid': overrides.get('open_kfid', 'kf-1'), + 'send_time': overrides.get('send_time', 1_714_000_000), + } + if msgtype == 'text': + payload['text'] = {'content': overrides.get('content', 'hello')} + if msgtype == 'image': + payload['image'] = {'media_id': overrides.get('media_id', 'media-id')} + payload['picurl'] = overrides.get('picurl', 'data:image/png;base64,AAAA') + if msgtype == 'file': + payload['file'] = {'media_id': 'file-id', 'filename': 'a.txt', 'file_size': 12} + if msgtype == 'voice': + payload['voice'] = {'media_id': 'voice-id'} + return WecomCSEvent.from_payload(payload) + + +def test_wecomcs_supported_events_match_manifest(): + assert make_adapter().get_supported_events() == manifest()['spec']['supported_events'] + + +def test_wecomcs_supported_apis_match_manifest(): + supported_apis = make_adapter().get_supported_apis() + manifest_apis = manifest()['spec']['supported_apis'] + + assert supported_apis == manifest_apis['required'] + manifest_apis['optional'] + + +def test_wecomcs_platform_api_map_matches_manifest(): + manifest_actions = {item['action'] for item in manifest()['spec']['platform_specific_apis']} + + assert set(PLATFORM_API_MAP) == manifest_actions + + +def test_wecomcs_split_string_by_bytes_keeps_multibyte_boundaries(): + parts = split_string_by_bytes('你好hello', limit=7) + + assert ''.join(parts) == '你好hello' + assert all(len(part.encode('utf-8')) <= 7 for part in parts) + + +@pytest.mark.asyncio +async def test_wecomcs_message_converter_maps_outbound_components(): + adapter = make_adapter() + content = await WecomCSMessageConverter.yiri2target( + platform_message.MessageChain( + [ + platform_message.Plain(text='hi'), + platform_message.Image(base64='data:image/png;base64,AAAA'), + platform_message.Quote( + id='origin', + origin=platform_message.MessageChain([platform_message.Plain(text='quoted')]), + ), + platform_message.At(target='external-2', display='Bob'), + platform_message.AtAll(), + ] + ), + adapter.bot, + ) + + assert content[0] == {'type': 'text', 'content': 'hi'} + assert {'type': 'image', 'media_id': 'media-id'} in content + assert {'type': 'text', 'content': '[Quote origin] '} in content + assert {'type': 'text', 'content': 'quoted'} in content + assert {'type': 'text', 'content': '@Bob'} in content + assert {'type': 'text', 'content': '@all'} in content + + +@pytest.mark.asyncio +async def test_wecomcs_message_converter_rejects_unsupported_outbound_media(): + adapter = make_adapter() + + with pytest.raises(NotSupportedError): + await WecomCSMessageConverter.yiri2target( + platform_message.MessageChain([platform_message.Voice(base64='BBBB')]), + adapter.bot, + ) + + +@pytest.mark.asyncio +async def test_wecomcs_event_converter_maps_text_message_to_eba_and_legacy(): + adapter = make_adapter() + event = await WecomCSEventConverter.target2yiri(wecomcs_event(), adapter.bot) + + assert isinstance(event, platform_events.MessageReceivedEvent) + assert event.adapter_name == 'wecomcs-eba' + assert event.chat_type == platform_entities.ChatType.PRIVATE + assert event.chat_id == 'external-1|kf-1' + assert event.sender.nickname == 'Alice' + assert str(event.message_chain) == 'hello' + + legacy = await WecomCSEventConverter.target2legacy(wecomcs_event(), adapter.bot) + assert isinstance(legacy, platform_events.FriendMessage) + assert legacy.sender.id == 'external-1' + assert str(legacy.message_chain) == 'hello' + + +@pytest.mark.asyncio +async def test_wecomcs_event_converter_maps_media_and_unknown_messages(): + image_event = await WecomCSEventConverter.target2yiri(wecomcs_event(msgtype='image'), make_adapter().bot) + file_event = await WecomCSEventConverter.target2yiri(wecomcs_event(msgtype='file'), make_adapter().bot) + voice_event = await WecomCSEventConverter.target2yiri(wecomcs_event(msgtype='voice'), make_adapter().bot) + unknown_event = await WecomCSEventConverter.target2yiri(wecomcs_event(msgtype='event'), make_adapter().bot) + + assert isinstance(image_event.message_chain[1], platform_message.Image) + assert image_event.message_chain[1].base64 == 'data:image/png;base64,AAAA' + assert isinstance(file_event.message_chain[1], platform_message.File) + assert isinstance(voice_event.message_chain[1], platform_message.Voice) + assert isinstance(unknown_event, platform_events.PlatformSpecificEvent) + assert unknown_event.action == 'wecomcs.event' + + +@pytest.mark.asyncio +async def test_wecomcs_adapter_dispatches_eba_and_legacy_and_caches_message_event(): + adapter = make_adapter() + eba_calls: list[platform_events.Event] = [] + legacy_calls: list[platform_events.Event] = [] + + async def eba_listener(event, adapter): + eba_calls.append(event) + + async def legacy_listener(event, adapter): + legacy_calls.append(event) + + adapter.register_listener(platform_events.MessageReceivedEvent, eba_listener) + adapter.register_listener(platform_events.FriendMessage, legacy_listener) + await adapter._handle_native_event(wecomcs_event()) + + assert len(eba_calls) == 1 + assert len(legacy_calls) == 1 + received = eba_calls[0] + assert isinstance(received, platform_events.MessageReceivedEvent) + assert adapter.bot_account_id == 'kf-1' + assert await adapter.get_message('private', 'external-1|kf-1', 'msg-1') == received + assert (await adapter.get_user_info('external-1')).nickname == 'Alice' + + await adapter._handle_native_event(wecomcs_event()) + assert len(eba_calls) == 1 + assert len(legacy_calls) == 1 + + +@pytest.mark.asyncio +async def test_wecomcs_send_reply_and_platform_api_use_underlying_client(): + adapter = make_adapter() + message = platform_message.MessageChain([platform_message.Plain(text='hello')]) + + await adapter.send_message('person', 'external-1|kf-1', message) + adapter.bot.send_text_msg.assert_awaited_once() + open_kfid, external_userid, msgid, content = adapter.bot.send_text_msg.await_args.args + assert (open_kfid, external_userid, content) == ('kf-1', 'external-1', 'hello') + assert msgid.startswith('lb-') + + image = platform_message.MessageChain([platform_message.Image(base64='data:image/png;base64,AAAA')]) + await adapter.send_message('person', 'external-1|kf-1', image) + adapter.bot.send_image_msg.assert_awaited_once() + + source_event = await WecomCSEventConverter.target2yiri(wecomcs_event(), adapter.bot) + await adapter.reply_message(source_event, message) + open_kfid, external_userid, reply_msgid, content = adapter.bot.send_text_msg.await_args.args + assert (open_kfid, external_userid, content) == ('kf-1', 'external-1', 'hello') + assert reply_msgid.startswith('lb-') + + token_status = await adapter.call_platform_api('check_access_token', {}) + customer_info = await adapter.call_platform_api('get_customer_info', {'external_userid': 'external-1'}) + + assert token_status == {'valid': True} + assert customer_info['nickname'] == 'Alice'