fix(platform): align messaging APIs and thread docs (LANG-312) (#2886)

* fix(platform): align messaging capabilities and reply contracts

Co-authored-by: multica-agent <[email protected]>

* fix(deps): pin SDK with unified API quote fix

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: multica-agent <[email protected]>
This commit is contained in:
RockChinQ
2026-11-05 20:07:37 +08:00
committed by GitHub
co-authored by multica-agent
parent 045a7ccd8e
commit daedb22d05
12 changed files with 198 additions and 21 deletions
@@ -503,6 +503,17 @@ spec:
> 注:此表为初步评估,具体以各平台 SDK/API 文档为准。
微信公众号(`officialaccount-omni`)与上表的「微信」单独记录:
| API | 微信公众号 | 条件 |
| --- | --- | --- |
| `send_message` | Y(optional) | 仅 `Mode=auto`,通过客服消息接口发送非空 `Plain` 文本;受权限、48 小时回复窗口、额度和关注状态限制。其他模式抛 `NotSupportedError`。 |
| `reply_message` | Y(required) | 按 `drop` / `passive` / `auto` 模式处理入站消息回复。 |
| `get_message` / `get_user_info` / `get_friend_list` | Y(optional) | 依赖已接收消息的缓存。 |
| `call_platform_api` | Y(optional) | 仅开放 manifest 声明的 action。 |
其他未实现的 optional API 抛 `NotSupportedError`。客服发送的错误码和返回值见 [OfficialAccount 适配器记录](adapters/officialaccount.md#customer-service-sends)。
## 6. MessageChain 扩展
### 6.1 保留的通用组件
@@ -4,7 +4,7 @@ Adapter directory: `src/langbot/pkg/platform/adapters/officialaccount/`
Manifest name: `officialaccount-omni`
Status: partial migration. Unit/API-shape coverage is present, and private text `plugin-e2e-ui` plus safe API evidence has been verified against the `dev.rockchin.top` Official Account fixture. Proactive outbound `send_message` remains not supported by this adapter because WeChat Official Account replies must be tied to inbound webhook windows.
Status: partial migration. Unit/API-shape coverage is present, and private text `plugin-e2e-ui` plus safe API evidence has been verified against the `dev.rockchin.top` Official Account fixture. Outbound `send_message` uses the customer-service messaging API in `Mode=auto`; other modes raise `NotSupportedError`.
## Config
@@ -15,8 +15,8 @@ Status: partial migration. Unit/API-shape coverage is present, and private text
| `EncodingAESKey` | yes | WeChat message encryption key. |
| `AppID` | yes | Official Account app ID. |
| `AppSecret` | yes | Official Account app secret. |
| `Mode` | yes | `drop` waits for an in-callback reply; `passive` returns the loading text first and queues the answer for the user's next message. |
| `LoadingMessage` | no | Only used by `passive` mode. |
| `Mode` | yes | `drop` waits for an in-callback reply; `passive` queues the answer for the user's next message; `auto` tries customer-service delivery for `reply_message` and falls back to next-message retrieval when restricted. Only `auto` supports `send_message`. |
| `LoadingMessage` | no | Used for next-message retrieval in `passive` and `auto` modes. |
| `api_base_url` | no | Optional API base URL for proxy deployments. |
## Events
@@ -35,7 +35,22 @@ Status: partial migration. Unit/API-shape coverage is present, and private text
| `get_user_info` | plugin-e2e-ui, unit | Cached inbound sender retrieved by `EBAEventProbe` platform API sweep. |
| `get_friend_list` | plugin-e2e-ui, unit | Cached inbound sender list retrieved by `EBAEventProbe` platform API sweep. |
| `call_platform_api` | plugin-e2e-ui, unit | Safe diagnostic actions verified through `get_mode` and `get_cached_response_status`. |
| `send_message` | not-supported | Official Account customer-service proactive messaging is not implemented by the existing SDK adapter; only webhook reply is supported here. |
| `send_message` | unit | In `auto` mode, sends non-empty `Plain` text to a user's OpenID through the customer-service API. Accepts `person`, `friend`, or `private` targets; other modes or target types raise `NotSupportedError`. |
### Customer-service sends
`send_message` requires customer-service API permission and an eligible user interaction within the 48-hour reply window. WeChat enforces the permission, window, quota, and follow status. Unlike `reply_message`, a rejected `send_message` is not queued for the user's next message.
Nonzero API results raise `OfficialAccountSendError`, with the original code available as `errcode`:
| errcode | Meaning |
| --- | --- |
| `48001` | Customer-service API permission denied. |
| `45015` | The 48-hour customer-service reply window has expired. |
| `45047` | Customer-service message quota exceeded. |
| `43004` | The user is not following the Official Account. |
Other nonzero codes also raise `OfficialAccountSendError`. Transport failures raise `RuntimeError` without exposing request credentials. Empty text and non-`Plain` components raise `ValueError` before delivery. Successful sends return `MessageResult(raw={"errcode": 0})`; this API does not supply a `message_id`.
## Platform APIs
@@ -57,8 +72,8 @@ Status: partial migration. Unit/API-shape coverage is present, and private text
| Send Component | Evidence | Notes |
| --- | --- | --- |
| `Plain` | unit | Sent as webhook reply text. |
| `Image`, `Voice`, `File`, `Quote`, `At`, `AtAll`, `Face`, `Forward`, mixed chain | not-supported | Existing SDK reply path is text XML only; non-text components degrade to readable placeholders in tests and are not declared as supported outbound components. |
| `Plain` | unit | Sent as webhook reply text or customer-service text in `auto` mode. Multiple `Plain` components are concatenated. |
| `Image`, `Voice`, `File`, `Quote`, `At`, `AtAll`, `Face`, `Forward`, mixed chain | not-supported | `send_message` rejects non-text components; the reply path degrades them to readable placeholders and does not declare them as supported outbound components. |
## Verification Record
@@ -73,7 +88,7 @@ Observed event/API evidence:
- `MessageReceived`: `bot_uuid=d7c46880-a9f8-431a-9172-5d3e0d663dbc`, `adapter_name=officialaccount-omni`, `chat_type=private`, `chat_id=ovH9L7OW6hNpWZWvp_NMmypVh26w`, `message_chain=[Source, Plain]`.
- Common safe APIs through probe platform sweep: `get_message`, `get_user_info`, `get_friend_list`.
- Platform APIs through `call_platform_api`: `get_mode`, `get_cached_response_status`.
- `send_message` and outbound component sweep returned explicit `NotSupportedError: send_message:official_account_requires_inbound_webhook_reply`, as expected for this adapter.
- This `drop`-mode probe does not verify customer-service `send_message`; that path has mocked unit coverage in `tests/unit_tests/platform/test_officialaccount_send_message.py`.
Standalone runtime command:
+14 -5
View File
@@ -5,8 +5,8 @@
Slack is migrated into `src/langbot/pkg/platform/adapters/slack/` with the standard EBA adapter layout:
- `adapter.py` owns lifecycle, listener dispatch, unified webhook handling, outbound send/reply, and event caches.
- `event_converter.py` maps Slack `im` and `app_mention` channel events to `message.received`.
- `message_converter.py` maps common `MessageChain` components to Slack text fallback and maps inbound Slack text/image payloads back to EBA components.
- `event_converter.py` maps Slack `im`, `app_mention`, and eligible channel thread replies to `message.received`.
- `message_converter.py` maps text components and inbound attachments; `libs/slack_api/media.py` sends message chains, uploads media, and applies `Quote` thread references.
- `api_impl.py` provides cache-backed common read APIs.
- `platform_api.py` declares safe Slack-specific API actions.
- `manifest.yaml` declares `slack-omni`.
@@ -25,7 +25,7 @@ The legacy `src/langbot/pkg/platform/sources/slack.py` adapter is kept unchanged
| Event | Notes |
|-------|-------|
| `message.received` | Emitted for private `im` messages and channel `app_mention` events. Channel messages are mapped to group chats. |
| `message.received` | Emitted for private `im` messages, channel `app_mention` events, and unmentioned replies in bot-started threads. Channel messages are mapped to group chats. |
| `platform.specific` | Reserved for Slack event types that are not converted into common message events. |
## Common APIs
@@ -48,6 +48,15 @@ Optional:
Cache-backed APIs are only available after the relevant inbound event has been observed.
### Replies and threads
- `send_message` returns the first response's Slack message `ts` as `MessageResult.message_id`; a response without a message timestamp (such as a file-only upload) leaves it empty.
- An outbound chain containing `Quote(id=ts, origin=MessageChain([]))` sends into that thread using the standard message API. No Slack-specific action is needed.
- Inbound channel thread replies end with `Quote(id=thread_ts, origin=MessageChain([]))`, referencing the thread root rather than the individual reply.
- Replies in threads started by the bot are dispatched even without an @mention. They do not receive a synthetic `At`, so pipeline mention rules still distinguish mentions from ordinary thread replies.
- Subscribe to `message.channels` for public-channel messages and `message.groups` for private-channel messages, in addition to `app_mention` and the DM events used by the app. Without the channel message subscriptions, unmentioned replies will not reach the adapter.
- `reply_message` stays in the source thread; `quote_origin=True` starts a thread from an unthreaded source message.
## Platform APIs
| Action | Notes |
@@ -57,8 +66,8 @@ Cache-backed APIs are only available after the relevant inbound event has been o
## Known Limits
- Slack file/image outbound is currently represented as text fallback because the existing Slack SDK wrapper only exposes `chat_postMessage`.
- Inbound channel coverage follows the legacy adapter behavior: only `app_mention` events are treated as group messages.
- File, image, and voice uploads use `files_upload_v2`; attachment bytes are limited to 20 MiB per component.
- Unmentioned channel messages outside bot-started threads are ignored. Thread dispatch requires the payload's `parent_user_id` to match the known bot user ID.
- Real live testing requires a public callback URL configured in Slack Event Subscriptions.
## Verification
+30
View File
@@ -4,6 +4,36 @@ title: "Platform APIs"
Call platform adapter APIs using a bot UUID. Continue using `self.plugin.send_message()` for message chains; use the API below for groups, users, and other platform features.
## Send messages, replies, and threads
The standard `send_message` API returns a `MessageResult`, whose `message_id` identifies the sent message when the platform provides one. `self.plugin.send_message()` returns its serialized dictionary, so read `result["message_id"]` rather than an object attribute. The ID may be `None` or empty when the platform does not return one.
Use the standard `Quote` component to express a reply or thread reference in a message chain. `Quote.id` is the referenced message or thread root ID; `origin` is the quoted message chain and may be empty. Support and reply/thread behavior depend on the adapter. For example, Slack returns the message `ts` as `message_id`, sends a chain with `Quote(id=ts)` into that thread, and appends `Quote(id=thread_ts)` to inbound channel thread replies. This uses standard message APIs, not a Slack-specific action.
```python
from langbot_plugin.api.entities.builtin.platform.message import MessageChain, Plain, Quote
result = await self.plugin.send_message(
bot_uuid=bot_uuid,
target_type="group",
target_id=group_id,
message_chain=MessageChain([Plain(text="Support request")]),
)
message_id = result.get("message_id") if result else None
if message_id is not None and message_id != "":
await self.plugin.send_message(
bot_uuid=bot_uuid,
target_type="group",
target_id=group_id,
message_chain=MessageChain([
Plain(text="Follow-up"),
Quote(id=message_id, origin=MessageChain([])),
]),
)
```
Use IDs from the same bot and conversation. `Quote` preserves reference metadata in serialization but adds no text to `str(message_chain)`, so it does not change command or keyword matching.
## Call a platform API
```python
+30
View File
@@ -4,6 +4,36 @@ title: "プラットフォーム API"
ボット UUID を指定してプラットフォームアダプターの API を呼び出します。メッセージチェーンの送信は `self.plugin.send_message()`、グループやユーザーの取得などは以下を使用します。
## メッセージ送信、返信、スレッド
標準の `send_message` API は `MessageResult` を返します。プラットフォームがメッセージ ID を提供する場合、`message_id` は送信したメッセージを識別します。`self.plugin.send_message()` はシリアライズされた辞書を返すため、オブジェクト属性ではなく `result["message_id"]` を参照します。プラットフォームが ID を返さない場合、この値は `None` または空文字列になります。
メッセージチェーン内の返信やスレッド参照には、標準の `Quote` コンポーネントを使います。`Quote.id` は参照先メッセージまたはスレッドのルートメッセージの ID、`origin` は引用元のメッセージチェーンで、空でも構いません。対応状況と返信/スレッドの動作はアダプターによって異なります。たとえば Slack はメッセージの `ts` を `message_id` として返し、`Quote(id=ts)` を含むチェーンをそのスレッドに送信します。受信したチャンネルのスレッド返信には、末尾に `Quote(id=thread_ts)` が追加されます。これは Slack 固有のアクションではなく、標準メッセージ API を使います。
```python
from langbot_plugin.api.entities.builtin.platform.message import MessageChain, Plain, Quote
result = await self.plugin.send_message(
bot_uuid=bot_uuid,
target_type="group",
target_id=group_id,
message_chain=MessageChain([Plain(text="Support request")]),
)
message_id = result.get("message_id") if result else None
if message_id is not None and message_id != "":
await self.plugin.send_message(
bot_uuid=bot_uuid,
target_type="group",
target_id=group_id,
message_chain=MessageChain([
Plain(text="Follow-up"),
Quote(id=message_id, origin=MessageChain([])),
]),
)
```
同じボット、同じ会話のメッセージ ID を使ってください。`Quote` はシリアライズ時に参照メタデータを保持しますが、`str(message_chain)` にはテキストを追加しないため、コマンドやキーワードの照合に影響しません。
## プラットフォーム API の呼び出し
```python
+32
View File
@@ -0,0 +1,32 @@
import ast
from pathlib import Path
import re
import textwrap
import unittest
ROOT = Path(__file__).resolve().parents[1]
LOCALES = ('en', 'zh', 'ja')
class PlatformMessageDocsTests(unittest.TestCase):
def test_locales_describe_standard_reply_contract(self):
for locale in LOCALES:
with self.subTest(locale=locale):
content = (ROOT / locale / 'plugin/dev/apis/platform.mdx').read_text(encoding='utf-8')
for term in ('MessageResult', 'message_id', 'Quote.id', 'origin', 'thread_ts', 'str(message_chain)'):
self.assertIn(term, content)
def test_reply_examples_match_and_parse_in_all_locales(self):
examples = []
for locale in LOCALES:
content = (ROOT / locale / 'plugin/dev/apis/platform.mdx').read_text(encoding='utf-8')
blocks = re.findall(r'```python\n(.*?)\n```', content, re.DOTALL)
replies = [block for block in blocks if 'Quote(id=message_id' in block]
self.assertEqual(len(replies), 1, locale)
example = replies[0]
ast.parse('async def example():\n' + textwrap.indent(example, ' '))
self.assertIn('result.get("message_id")', example)
self.assertIn('origin=MessageChain([])', example)
examples.append(example)
self.assertEqual(examples, [examples[0]] * len(LOCALES))
+30
View File
@@ -4,6 +4,36 @@ title: "平台 API"
通过机器人 UUID 调用平台适配器的 API。发送消息链可继续使用 `self.plugin.send_message()`;查询群组、用户及其他平台能力使用下面的接口。
## 发送消息、回复与线程
标准 `send_message` API 返回 `MessageResult`;平台提供消息 ID 时,`message_id` 表示已发送的消息。`self.plugin.send_message()` 返回其序列化字典,因此应读取 `result["message_id"]`,而不是对象属性。平台不返回消息 ID 时,该值可能为 `None` 或空字符串。
使用标准消息组件 `Quote` 表达回复或线程引用:`Quote.id` 为被引用消息或线程根消息的 ID,`origin` 为被引用的消息链,可以为空。具体支持情况和回复/线程行为由适配器决定。例如,Slack 将消息的 `ts` 作为 `message_id` 返回,带 `Quote(id=ts)` 的消息链会发到对应线程,入站频道线程回复的消息链末尾会附加 `Quote(id=thread_ts)`。这些操作使用标准消息 API,而非 Slack 专属 action。
```python
from langbot_plugin.api.entities.builtin.platform.message import MessageChain, Plain, Quote
result = await self.plugin.send_message(
bot_uuid=bot_uuid,
target_type="group",
target_id=group_id,
message_chain=MessageChain([Plain(text="Support request")]),
)
message_id = result.get("message_id") if result else None
if message_id is not None and message_id != "":
await self.plugin.send_message(
bot_uuid=bot_uuid,
target_type="group",
target_id=group_id,
message_chain=MessageChain([
Plain(text="Follow-up"),
Quote(id=message_id, origin=MessageChain([])),
]),
)
```
请使用同一机器人、同一会话中的消息 ID。`Quote` 在序列化时保留引用元数据,但不会向 `str(message_chain)` 添加文本,因此不会影响命令或关键词匹配。
## 调用平台 API
```python
+1 -1
View File
@@ -230,7 +230,7 @@ unfixable = []
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
[tool.uv.sources]
langbot-plugin = { git = "https://github.com/langbot-app/langbot-plugin-sdk", rev = "7cc07a18081fe153a42431b28dd9118d08ffa4d6" }
langbot-plugin = { git = "https://github.com/langbot-app/langbot-plugin-sdk", rev = "29338642ff3fbe8792543be75292543480480e07" }
[tool.ruff.format]
# Like Black, use double quotes for strings.
@@ -8,9 +8,9 @@ metadata:
zh_Hans: 微信公众号
zh_Hant: 微信公眾號
description:
en_US: WeChat Official Account adapter with event-driven orchestration support
zh_Hans: 微信公众号适配器,支持事件驱动编排,通过统一 Webhook 接收公众号消息
zh_Hant: 微信公眾號適配器,支援事件驅動編排,透過統一 Webhook 接收公眾號訊息
en_US: "WeChat Official Account adapter with event-driven orchestration support. send_message is available only with Mode=auto; other modes raise NotSupportedError."
zh_Hans: "微信公众号适配器,支持事件驱动编排,通过统一 Webhook 接收公众号消息。send_message 仅在 Mode=auto 时可用,其他模式抛出 NotSupportedError。"
zh_Hant: "微信公眾號適配器,支援事件驅動編排,透過統一 Webhook 接收公眾號訊息。send_message 僅在 Mode=auto 時可用,其他模式拋出 NotSupportedError。"
icon: officialaccount.png
spec:
@@ -139,6 +139,7 @@ spec:
- get_user_info
- get_friend_list
- call_platform_api
- send_message
platform_specific_apis:
- action: get_mode
@@ -0,0 +1,14 @@
import pytest
from langbot_plugin.api.entities.builtin.platform.message import MessageChain, Plain, Quote
@pytest.mark.parametrize('quote_first', [False, True])
@pytest.mark.parametrize('origin_text', [None, 'quoted content'])
def test_quote_preserves_command_text(quote_first, origin_text):
origin = MessageChain([] if origin_text is None else [Plain(text=origin_text)])
quote = Quote(id='1', origin=origin)
plain = Plain(text='!help')
chain = MessageChain([quote, plain] if quote_first else [plain, quote])
assert str(chain) == '!help'
@@ -111,11 +111,16 @@ def test_officialaccount_supported_events_match_manifest():
assert make_adapter().get_supported_events() == manifest()['spec']['supported_events']
def test_officialaccount_supported_apis_match_manifest():
supported_apis = make_adapter().get_supported_apis()
@pytest.mark.parametrize('mode', ['drop', 'passive', 'auto'])
def test_officialaccount_supported_apis_match_manifest(mode):
supported_apis = make_adapter(mode).get_supported_apis()
manifest_apis = manifest()['spec']['supported_apis']
declared_apis = manifest_apis['required'] + manifest_apis['optional']
assert supported_apis == manifest_apis['required'] + manifest_apis['optional']
assert 'send_message' in manifest_apis['optional']
if mode != 'auto':
declared_apis.remove('send_message')
assert supported_apis == declared_apis
def test_officialaccount_platform_api_map_matches_manifest():
Generated
+2 -2
View File
@@ -2244,7 +2244,7 @@ requires-dist = [
{ name = "gewechat-client", specifier = ">=0.1.5" },
{ name = "html2text", specifier = ">=2024.2.26" },
{ name = "httpx", extras = ["socks"], specifier = ">=0.28.1" },
{ name = "langbot-plugin", git = "https://github.com/langbot-app/langbot-plugin-sdk?rev=7cc07a18081fe153a42431b28dd9118d08ffa4d6" },
{ name = "langbot-plugin", git = "https://github.com/langbot-app/langbot-plugin-sdk?rev=29338642ff3fbe8792543be75292543480480e07" },
{ name = "langchain", specifier = ">=1.3.9" },
{ name = "langchain-core", specifier = ">=1.3.3" },
{ name = "langchain-text-splitters", specifier = ">=1.1.2" },
@@ -2316,7 +2316,7 @@ dev = [
[[package]]
name = "langbot-plugin"
version = "0.7.21"
source = { git = "https://github.com/langbot-app/langbot-plugin-sdk?rev=7cc07a18081fe153a42431b28dd9118d08ffa4d6#7cc07a18081fe153a42431b28dd9118d08ffa4d6" }
source = { git = "https://github.com/langbot-app/langbot-plugin-sdk?rev=29338642ff3fbe8792543be75292543480480e07#29338642ff3fbe8792543be75292543480480e07" }
dependencies = [
{ name = "aiofiles" },
{ name = "aiohttp" },