The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(adapters/yuanbao_weixin): 10420->6889; yuanbao_proto spec-table encode/decode (-46%), unify weixin HTTP/send/media/typing helpers, drop dead send_file/register_handler/encode_forward_msg_data, duplicate _on_delta
Teknium9837fd0bc434
diff --git a/gateway/platforms/weixin.py b/gateway/platforms/weixin.pyindex ccf610fc7ae..efc0c5325da 100644--- a/gateway/platforms/weixin.py+++ b/gateway/platforms/weixin.py@@ -14,6 +14,7 @@ from __future__ import annotationsimport asyncioimport base64+import contextlibimport hashlibimport jsonimport logging@@ -28,7 +29,7 @@ import timeimport uuidfrom datetime import datetimefrom pathlib import Path-from typing import Any, Dict, List, Optional, Tuple+from typing import Any, Callable, Dict, List, Optional, Tuplefrom urllib.parse import quote, urlparselogger = logging.getLogger(__name__)@@ -49,10 +50,7 @@ try:CRYPTO_AVAILABLE = Trueexcept ImportError: # pragma: no cover - dependency gate- default_backend = None # type: ignore[assignment]- Cipher = None # type: ignore[assignment]- algorithms = None # type: ignore[assignment]- modes = None # type: ignore[assignment]+ default_backend = Cipher = algorithms = modes = None # type: ignore[assignment]CRYPTO_AVAILABLE = Falsefrom gateway.config import Platform, PlatformConfig@@ -73,22 +71,25 @@ from agent.secret_scope import UnscopedSecretError, get_secretdef _wx_secret(name: str, default: Optional[str] = None) -> Optional[str]:- """Scope-aware WEIXIN_* read with the default-profile startup fallback.-- Secondary profiles construct their adapters under- ``_profile_runtime_scope`` — the scope is authoritative and a scoped miss- returns ``default`` (no cross-profile borrow from ``os.environ``). The- DEFAULT profile's adapter constructs and sends *unscoped* under- multiplexing, where a bare ``get_secret`` would raise- ``UnscopedSecretError`` and crash its Weixin path; there ``os.environ`` is- that profile's own value, so fall back to it. Same pattern as the Slack- ``SLACK_APP_TOKEN`` read (#59739) and WhatsApp's ``_get_wsecret``.- """+ """Scope-aware WEIXIN_* read. Secondary profiles run scoped: a miss returns ``default``+ (never borrow ``os.environ``). The DEFAULT profile runs *unscoped* under multiplexing,+ where ``get_secret`` raises; there ``os.environ`` is its own value, so fall back."""try:return get_secret(name, default)except UnscopedSecretError:return os.getenv(name, default)++def _extra_or_secret(extra: Dict[str, Any], key: str, env: str, default: str = "") -> str:+ """``config.extra[key]`` first, else the scoped secret ``env``; stripped."""+ return str(extra.get(key) or _wx_secret(env, default)).strip()+++def _extra_or_env(extra: Dict[str, Any], key: str, env: str, default: str) -> Any:+ """``config.extra[key]`` first, else plain ``os.getenv(env, default)`` (non-secret tunables)."""+ return extra.get(key) or os.getenv(env, default)++ILINK_BASE_URL = "https://ilinkai.weixin.qq.com"WEIXIN_CDN_BASE_URL = "https://novac2c.cdn.weixin.qq.com/c2c"ILINK_APP_ID = "bot"@@ -116,17 +117,22 @@ RATE_LIMIT_ERRCODE = -2 # iLink frequency limit — backoff and retryMESSAGE_DEDUP_TTL_SECONDS = 300-def _is_stale_session_ret(- ret: "Optional[int]", errcode: "Optional[int]", errmsg: "Optional[str]",-) -> bool:- """True when iLink returns ret=-2 / errcode=-2 with 'unknown error',- which is a stale-session signal (same as errcode=-14) rather than- a genuine rate limit."""+def _is_stale_session_ret(ret: "Optional[int]", errcode: "Optional[int]", errmsg: "Optional[str]") -> bool:+ """True when iLink returns ret/errcode=-2 with 'unknown error' — a stale-session+ signal (same as errcode=-14) rather than a genuine rate limit."""if ret != RATE_LIMIT_ERRCODE and errcode != RATE_LIMIT_ERRCODE:return Falsereturn (errmsg or "").lower() == "unknown error"+def _is_session_expired(resp: Dict[str, Any], ret: Any, errcode: Any) -> bool:+ return (+ ret == SESSION_EXPIRED_ERRCODE+ or errcode == SESSION_EXPIRED_ERRCODE+ or _is_stale_session_ret(ret, errcode, resp.get("errmsg"))+ )++MEDIA_IMAGE = 1MEDIA_VIDEO = 2MEDIA_FILE = 3@@ -136,20 +142,10 @@ _LIVE_ADAPTERS: Dict[str, Any] = {}def _make_ssl_connector() -> Optional["aiohttp.TCPConnector"]:- """Return a TCPConnector with a certifi CA bundle, or None if certifi is unavailable.-- Tencent's iLink server (``ilinkai.weixin.qq.com``) is not verifiable against- some system CA stores (notably Homebrew's OpenSSL on macOS Apple Silicon).- When ``certifi`` is installed, use its Mozilla CA bundle to guarantee- verification. Otherwise fall back to aiohttp's default (which honors- ``SSL_CERT_FILE`` env var when ``gateway.trust_env`` is on).-- Uses a tight ``keepalive_timeout=2`` (default aiohttp: 30s) so idle- connections drain promptly behind proxies like Cloudflare Warp that- leave peer-initiated FIN in ``CLOSE_WAIT`` (same class as #18451).- ``enable_cleanup_closed=True`` helps the connector clean up sockets- that the remote side has already closed.- """+ """TCPConnector with certifi's CA bundle (``ilinkai.weixin.qq.com`` fails some system+ stores, e.g. Homebrew OpenSSL); None without certifi so aiohttp's default (honors+ ``SSL_CERT_FILE`` under trust_env) applies. ``keepalive_timeout=2`` ++ ``enable_cleanup_closed`` drain idle CLOSE_WAIT sockets behind proxies like Warp."""try:import sslimport certifi@@ -158,12 +154,12 @@ def _make_ssl_connector() -> Optional["aiohttp.TCPConnector"]:if not AIOHTTP_AVAILABLE:return Nonessl_ctx = ssl.create_default_context(cafile=certifi.where())- return aiohttp.TCPConnector(- ssl=ssl_ctx,- # Tighter keepalive so idle CLOSE_WAIT drains promptly (#18451, #69089).- keepalive_timeout=2,- enable_cleanup_closed=True,- )+ return aiohttp.TCPConnector(ssl=ssl_ctx, keepalive_timeout=2, enable_cleanup_closed=True)+++def _new_session(**kwargs: Any) -> "aiohttp.ClientSession":+ return aiohttp.ClientSession(trust_env=gateway_trust_env(), connector=_make_ssl_connector(), **kwargs)+ITEM_TEXT = 1ITEM_IMAGE = 2@@ -171,7 +167,6 @@ ITEM_VOICE = 3ITEM_FILE = 4ITEM_VIDEO = 5-MSG_TYPE_USER = 1MSG_TYPE_BOT = 2MSG_STATE_FINISH = 2@@ -181,7 +176,6 @@ TYPING_STOP = 2_HEADER_RE = re.compile(r"^(#{1,6})\s+(.+?)\s*$")_TABLE_RULE_RE = re.compile(r"^\s*\|?(?:\s*:?-{3,}:?\s*\|)+\s*:?-{3,}:?\s*\|?\s*$")_FENCE_RE = re.compile(r"^```([^\n`]*)\s*$")-_MARKDOWN_LINK_RE = re.compile(r"\[([^\]]+)\]\(([^)]+)\)")def check_weixin_requirements() -> bool:@@ -191,11 +185,7 @@ def check_weixin_requirements() -> bool:def _safe_id(value: Optional[str], keep: int = 8) -> str:raw = str(value or "").strip()- if not raw:- return "?"- if len(raw) <= keep:- return raw- return raw[:keep]+ return raw[:keep] if raw else "?"def _json_dumps(payload: Dict[str, Any]) -> str:@@ -207,15 +197,17 @@ def _pkcs7_pad(data: bytes, block_size: int = 16) -> bytes:return data + bytes([pad_len] * pad_len)+def _aes_cipher(key: bytes):+ return Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend())++def _aes128_ecb_encrypt(plaintext: bytes, key: bytes) -> bytes:- cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend())- encryptor = cipher.encryptor()+ encryptor = _aes_cipher(key).encryptor()return encryptor.update(_pkcs7_pad(plaintext)) + encryptor.finalize()def _aes128_ecb_decrypt(ciphertext: bytes, key: bytes) -> bytes:- cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend())- decryptor = cipher.decryptor()+ decryptor = _aes_cipher(key).decryptor()padded = decryptor.update(ciphertext) + decryptor.finalize()if not padded:return padded@@ -258,42 +250,28 @@ def _account_dir(hermes_home: str) -> Path:return path-def _account_file(hermes_home: str, account_id: str) -> Path:- return _account_dir(hermes_home) / f"{account_id}.json"+def _read_json(path: Path) -> Any:+ """Parse a JSON file; ``None`` when missing or unparseable."""+ if not path.exists():+ return None+ try:+ return json.loads(path.read_text(encoding="utf-8"))+ except Exception:+ return None-def save_weixin_account(- hermes_home: str,- *,- account_id: str,- token: str,- base_url: str,- user_id: str = "",-) -> None:+def save_weixin_account(hermes_home: str, *, account_id: str, token: str, base_url: str, user_id: str = "") -> None:"""Persist account credentials for later reuse."""- payload = {- "token": token,- "base_url": base_url,- "user_id": user_id,- "saved_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),- }- path = _account_file(hermes_home, account_id)- atomic_json_write(path, payload)- try:+ saved_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())+ path = _account_dir(hermes_home) / f"{account_id}.json"+ atomic_json_write(path, {"token": token, "base_url": base_url, "user_id": user_id, "saved_at": saved_at})+ with contextlib.suppress(OSError):path.chmod(0o600)- except OSError:- passdef load_weixin_account(hermes_home: str, account_id: str) -> Optional[Dict[str, Any]]:"""Load persisted account credentials."""- path = _account_file(hermes_home, account_id)- if not path.exists():- return None- try:- return json.loads(path.read_text(encoding="utf-8"))- except Exception:- return None+ return _read_json(_account_dir(hermes_home) / f"{account_id}.json")class ContextTokenStore:@@ -335,11 +313,7 @@ class ContextTokenStore:def _persist(self, account_id: str) -> None:prefix = f"{account_id}:"- payload = {- key[len(prefix) :]: value- for key, value in self._cache.items()- if key.startswith(prefix)- }+ payload = {key[len(prefix):]: value for key, value in self._cache.items() if key.startswith(prefix)}try:atomic_json_write(self._path(account_id), payload)except Exception as exc:@@ -355,12 +329,10 @@ class TypingTicketCache:def get(self, user_id: str) -> Optional[str]:entry = self._cache.get(user_id)- if not entry:- return None- if time.time() - entry[1] >= self._ttl_seconds:- self._cache.pop(user_id, None)- return None- return entry[0]+ if entry and time.time() - entry[1] < self._ttl_seconds:+ return entry[0]+ self._cache.pop(user_id, None)+ return Nonedef set(self, user_id: str, ticket: str) -> None:self._cache[user_id] = (ticket, time.time())@@ -398,223 +370,127 @@ def _guess_chat_type(message: Dict[str, Any], account_id: str) -> Tuple[str, strreturn "dm", str(message.get("from_user_id") or "")-async def _api_post(- session: "aiohttp.ClientSession",- *,- base_url: str,- endpoint: str,- payload: Dict[str, Any],- token: Optional[str],- timeout_ms: int,+# All HTTP helpers below enforce timeouts via asyncio.wait_for() rather than+# aiohttp ClientTimeout, which raises "Timeout context manager should be used+# inside a task" when invoked via asyncio.run_coroutine_threadsafe() from cron.+async def _api_request(+ session: "aiohttp.ClientSession", method: str, *, base_url: str, endpoint: str, headers: Dict[str, str],+ timeout_ms: int, body: Optional[str] = None,) -> Dict[str, Any]:- body = _json_dumps({**payload, "base_info": _base_info()})url = f"{base_url.rstrip('/')}/{endpoint}"- # Use asyncio.wait_for() instead of aiohttp ClientTimeout to avoid- # "Timeout context manager should be used inside a task" errors when- # invoked via asyncio.run_coroutine_threadsafe() from cron jobs.+ kwargs = {"data": body} if body is not None else {}+async def _do() -> Dict[str, Any]:- async with session.post(url, data=body, headers=_headers(token, body)) as response:+ async with getattr(session, method.lower())(url, headers=headers, **kwargs) as response:raw = await response.text()if not response.ok:- raise RuntimeError(f"iLink POST {endpoint} HTTP {response.status}: {raw[:200]}")+ raise RuntimeError(f"iLink {method} {endpoint} HTTP {response.status}: {raw[:200]}")return json.loads(raw)return await asyncio.wait_for(_do(), timeout=timeout_ms / 1000)-async def _api_get(- session: "aiohttp.ClientSession",- *,- base_url: str,- endpoint: str,- timeout_ms: int,+async def _api_post(+ session: "aiohttp.ClientSession", *, base_url: str, endpoint: str,+ payload: Dict[str, Any], token: Optional[str], timeout_ms: int,) -> Dict[str, Any]:- url = f"{base_url.rstrip('/')}/{endpoint}"- headers = {- "iLink-App-Id": ILINK_APP_ID,- "iLink-App-ClientVersion": str(ILINK_APP_CLIENT_VERSION),- }- # Use asyncio.wait_for() instead of aiohttp ClientTimeout to avoid- # "Timeout context manager should be used inside a task" errors when- # invoked via asyncio.run_coroutine_threadsafe() from cron jobs.- async def _do() -> Dict[str, Any]:- async with session.get(url, headers=headers) as response:- raw = await response.text()- if not response.ok:- raise RuntimeError(f"iLink GET {endpoint} HTTP {response.status}: {raw[:200]}")- return json.loads(raw)- return await asyncio.wait_for(_do(), timeout=timeout_ms / 1000)+ body = _json_dumps({**payload, "base_info": _base_info()})+ return await _api_request(+ session, "POST", base_url=base_url, endpoint=endpoint,+ headers=_headers(token, body), timeout_ms=timeout_ms, body=body,+ )-async def _get_updates(- session: "aiohttp.ClientSession",- *,- base_url: str,- token: str,- sync_buf: str,- timeout_ms: int,-) -> Dict[str, Any]:+async def _api_get(session: "aiohttp.ClientSession", *, base_url: str, endpoint: str, timeout_ms: int) -> Dict[str, Any]:+ headers = {"iLink-App-Id": ILINK_APP_ID, "iLink-App-ClientVersion": str(ILINK_APP_CLIENT_VERSION)}+ return await _api_request(session, "GET", base_url=base_url, endpoint=endpoint, headers=headers, timeout_ms=timeout_ms)+++async def _get_updates(session: "aiohttp.ClientSession", *, base_url: str, token: str, sync_buf: str, timeout_ms: int) -> Dict[str, Any]:try:return await _api_post(- session,- base_url=base_url,- endpoint=EP_GET_UPDATES,- payload={"get_updates_buf": sync_buf},- token=token,- timeout_ms=timeout_ms,+ session, base_url=base_url, endpoint=EP_GET_UPDATES,+ payload={"get_updates_buf": sync_buf}, token=token, timeout_ms=timeout_ms,)except asyncio.TimeoutError:return {"ret": 0, "msgs": [], "get_updates_buf": sync_buf}-async def _send_message(- session: "aiohttp.ClientSession",- *,- base_url: str,- token: str,- to: str,- text: str,- context_token: Optional[str],- client_id: str,+async def _send_items(+ session: "aiohttp.ClientSession", *, base_url: str, token: str, to: str, item_list: List[Dict[str, Any]],+ context_token: Optional[str], client_id: str,) -> Dict[str, Any]:- """Send a text message via iLink sendmessage API.-- Returns the raw API response dict (may contain error codes like- ``errcode: -14`` for session expiry that the caller can inspect).- """- if not text or not text.strip():- raise ValueError("_send_message: text must not be empty")+ """POST one ``sendmessage`` with the given item list; returns the raw response."""message: Dict[str, Any] = {"from_user_id": "","to_user_id": to,"client_id": client_id,"message_type": MSG_TYPE_BOT,"message_state": MSG_STATE_FINISH,- "item_list": [{"type": ITEM_TEXT, "text_item": {"text": text}}],+ "item_list": item_list,}if context_token:message["context_token"] = context_tokenreturn await _api_post(- session,- base_url=base_url,- endpoint=EP_SEND_MESSAGE,- payload={"msg": message},- token=token,- timeout_ms=API_TIMEOUT_MS,+ session, base_url=base_url, endpoint=EP_SEND_MESSAGE,+ payload={"msg": message}, token=token, timeout_ms=API_TIMEOUT_MS,)-async def _send_typing(- session: "aiohttp.ClientSession",- *,- base_url: str,- token: str,- to_user_id: str,- typing_ticket: str,- status: int,-) -> None:- await _api_post(- session,- base_url=base_url,- endpoint=EP_SEND_TYPING,- payload={- "ilink_user_id": to_user_id,- "typing_ticket": typing_ticket,- "status": status,- },- token=token,- timeout_ms=CONFIG_TIMEOUT_MS,+async def _send_message(+ session: "aiohttp.ClientSession", *, base_url: str, token: str, to: str, text: str, context_token: Optional[str],+ client_id: str,+) -> Dict[str, Any]:+ """Send a text message. Returns the raw API response (may carry ``errcode: -14`` etc.)."""+ if not text or not text.strip():+ raise ValueError("_send_message: text must not be empty")+ return await _send_items(+ session, base_url=base_url, token=token, to=to,+ item_list=[{"type": ITEM_TEXT, "text_item": {"text": text}}],+ context_token=context_token, client_id=client_id,)async def _get_config(- session: "aiohttp.ClientSession",- *,- base_url: str,- token: str,- user_id: str,- context_token: Optional[str],+ session: "aiohttp.ClientSession", *, base_url: str, token: str, user_id: str, context_token: Optional[str],) -> Dict[str, Any]:payload: Dict[str, Any] = {"ilink_user_id": user_id}if context_token:payload["context_token"] = context_tokenreturn await _api_post(- session,- base_url=base_url,- endpoint=EP_GET_CONFIG,- payload=payload,- token=token,- timeout_ms=CONFIG_TIMEOUT_MS,+ session, base_url=base_url, endpoint=EP_GET_CONFIG, payload=payload, token=token, timeout_ms=CONFIG_TIMEOUT_MS,)async def _get_upload_url(- session: "aiohttp.ClientSession",- *,- base_url: str,- token: str,- to_user_id: str,- media_type: int,- filekey: str,- rawsize: int,- rawfilemd5: str,- filesize: int,- aeskey_hex: str,+ session: "aiohttp.ClientSession", *, base_url: str, token: str, to_user_id: str, media_type: int,+ filekey: str, rawsize: int, rawfilemd5: str, filesize: int, aeskey_hex: str,) -> Dict[str, Any]:return await _api_post(- session,- base_url=base_url,- endpoint=EP_GET_UPLOAD_URL,+ session, base_url=base_url, endpoint=EP_GET_UPLOAD_URL,payload={- "filekey": filekey,- "media_type": media_type,- "to_user_id": to_user_id,- "rawsize": rawsize,- "rawfilemd5": rawfilemd5,- "filesize": filesize,- "no_need_thumb": True,- "aeskey": aeskey_hex,+ "filekey": filekey, "media_type": media_type, "to_user_id": to_user_id, "rawsize": rawsize,+ "rawfilemd5": rawfilemd5, "filesize": filesize, "no_need_thumb": True, "aeskey": aeskey_hex,},- token=token,- timeout_ms=API_TIMEOUT_MS,+ token=token, timeout_ms=API_TIMEOUT_MS,)-async def _upload_ciphertext(- session: "aiohttp.ClientSession",- *,- ciphertext: bytes,- upload_url: str,-) -> str:- """Upload encrypted media to the CDN.-- Accepts either a constructed CDN URL (from upload_param) or a direct- upload_full_url — both use POST with the raw ciphertext as the body.- """- # Use asyncio.wait_for() instead of aiohttp ClientTimeout to avoid- # "Timeout context manager should be used inside a task" errors when- # invoked via asyncio.run_coroutine_threadsafe() from cron jobs.+async def _upload_ciphertext(session: "aiohttp.ClientSession", *, ciphertext: bytes, upload_url: str) -> str:+ """POST encrypted media to the CDN (constructed URL or direct ``upload_full_url``)."""async def _do_upload() -> str:async with session.post(upload_url, data=ciphertext, headers={"Content-Type": "application/octet-stream"}) as response:+ encrypted_param = response.headers.get("x-encrypted-param") if response.status == 200 else None+ if encrypted_param:+ await response.read()+ return encrypted_param+ raw = await response.text()if response.status == 200:- encrypted_param = response.headers.get("x-encrypted-param")- if encrypted_param:- await response.read()- return encrypted_param- raw = await response.text()raise RuntimeError(f"CDN upload missing x-encrypted-param header: {raw[:200]}")- raw = await response.text()raise RuntimeError(f"CDN upload HTTP {response.status}: {raw[:200]}")return await asyncio.wait_for(_do_upload(), timeout=120)-async def _download_bytes(- session: "aiohttp.ClientSession",- *,- url: str,- timeout_seconds: float = 60.0,-) -> bytes:- # Use asyncio.wait_for() instead of aiohttp ClientTimeout to avoid- # "Timeout context manager should be used inside a task" errors.+async def _download_bytes(session: "aiohttp.ClientSession", *, url: str, timeout_seconds: float = 60.0) -> bytes:async def _do_download() -> bytes:async with session.get(url) as response:response.raise_for_status()@@ -622,17 +498,10 @@ async def _download_bytes(return await asyncio.wait_for(_do_download(), timeout=timeout_seconds)-_WEIXIN_CDN_ALLOWLIST: frozenset[str] = frozenset(- {- "novac2c.cdn.weixin.qq.com",- "ilinkai.weixin.qq.com",- "wx.qlogo.cn",- "thirdwx.qlogo.cn",- "res.wx.qq.com",- "mmbiz.qpic.cn",- "mmbiz.qlogo.cn",- }-)+_WEIXIN_CDN_ALLOWLIST: frozenset[str] = frozenset({+ "novac2c.cdn.weixin.qq.com", "ilinkai.weixin.qq.com", "wx.qlogo.cn", "thirdwx.qlogo.cn",+ "res.wx.qq.com", "mmbiz.qpic.cn", "mmbiz.qlogo.cn",+})def _assert_weixin_cdn_url(url: str) -> None:@@ -643,36 +512,19 @@ def _assert_weixin_cdn_url(url: str) -> None:host = parsed.hostname or ""except Exception as exc: # noqa: BLE001raise ValueError(f"Unparseable media URL: {url!r}") from exc-if scheme not in {"http", "https"}:- raise ValueError(- f"Media URL has disallowed scheme {scheme!r}; only http/https are permitted."- )+ raise ValueError(f"Media URL has disallowed scheme {scheme!r}; only http/https are permitted.")if host not in _WEIXIN_CDN_ALLOWLIST:- raise ValueError(- f"Media URL host {host!r} is not in the WeChat CDN allowlist. "- "Refusing to fetch to prevent SSRF."- )---def _media_reference(item: Dict[str, Any], key: str) -> Dict[str, Any]:- return (item.get(key) or {}).get("media") or {}+ raise ValueError(f"Media URL host {host!r} is not in the WeChat CDN allowlist. Refusing to fetch to prevent SSRF.")async def _download_and_decrypt_media(- session: "aiohttp.ClientSession",- *,- cdn_base_url: str,- encrypted_query_param: Optional[str],- aes_key_b64: Optional[str],- full_url: Optional[str],- timeout_seconds: float,+ session: "aiohttp.ClientSession", *, cdn_base_url: str, encrypted_query_param: Optional[str],+ aes_key_b64: Optional[str], full_url: Optional[str], timeout_seconds: float,) -> bytes:if encrypted_query_param:raw = await _download_bytes(- session,- url=_cdn_download_url(cdn_base_url, encrypted_query_param),- timeout_seconds=timeout_seconds,+ session, url=_cdn_download_url(cdn_base_url, encrypted_query_param), timeout_seconds=timeout_seconds,)elif full_url:_assert_weixin_cdn_url(full_url)@@ -684,44 +536,25 @@ async def _download_and_decrypt_media(return raw-def _mime_from_filename(filename: str) -> str:- return mimetypes.guess_type(filename)[0] or "application/octet-stream"---def _split_table_row(line: str) -> List[str]:- """Delegate to the canonical table-row splitter in agent.markdown_tables."""- from agent.markdown_tables import split_table_row-- return split_table_row(line)--def _normalize_markdown_blocks(content: str) -> str:- lines = content.splitlines()result: List[str] = []in_code_block = Falseblank_run = 0-- for raw_line in lines:+ for raw_line in content.splitlines():line = raw_line.rstrip()if _FENCE_RE.match(line.strip()):in_code_block = not in_code_blockresult.append(line)blank_run = 0- continue-- if in_code_block:+ elif in_code_block:result.append(line)- continue-- if not line.strip():+ elif not line.strip():blank_run += 1if blank_run <= 1:result.append("")- continue-- blank_run = 0- result.append(line)-+ else:+ blank_run = 0+ result.append(line)return "\n".join(result).strip()@@ -729,20 +562,15 @@ def _wrap_copy_friendly_lines_for_weixin(content: str) -> str:"""Wrap long display lines that are hard to copy in WeChat clients."""if not content:return content-wrapped: List[str] = []in_code_block = False-for raw_line in content.splitlines():line = raw_line.rstrip()stripped = line.strip()-if _FENCE_RE.match(stripped):in_code_block = not in_code_blockwrapped.append(line)- continue-- if (+ elif (in_code_blockor len(line) <= WEIXIN_COPY_LINE_WIDTHor not stripped@@ -750,116 +578,83 @@ def _wrap_copy_friendly_lines_for_weixin(content: str) -> str:or _TABLE_RULE_RE.match(stripped)):wrapped.append(line)- continue-- wrapped_lines = textwrap.wrap(- line,- width=WEIXIN_COPY_LINE_WIDTH,- break_long_words=False,- break_on_hyphens=False,- replace_whitespace=False,- drop_whitespace=True,- )- wrapped.extend(wrapped_lines or [line])-+ else:+ wrapped.extend(textwrap.wrap(+ line, width=WEIXIN_COPY_LINE_WIDTH, break_long_words=False,+ break_on_hyphens=False, replace_whitespace=False, drop_whitespace=True,+ ) or [line])return "\n".join(wrapped).strip()def _split_markdown_blocks(content: str) -> List[str]:+ """Split on blank lines, keeping each fenced code block as one block."""if not content:return []-blocks: List[str] = []- lines = content.splitlines()current: List[str] = []in_code_block = False- for raw_line in lines:+ def flush() -> None:+ if current:+ blocks.append("\n".join(current).strip())+ current.clear()+ for raw_line in content.splitlines():line = raw_line.rstrip()if _FENCE_RE.match(line.strip()):- if not in_code_block and current:- blocks.append("\n".join(current).strip())- current = []+ if not in_code_block:+ flush()current.append(line)in_code_block = not in_code_blockif not in_code_block:- blocks.append("\n".join(current).strip())- current = []- continue-- if in_code_block:+ flush()+ elif in_code_block:current.append(line)- continue-- if not line.strip():- if current:- blocks.append("\n".join(current).strip())- current = []- continue- current.append(line)-- if current:- blocks.append("\n".join(current).strip())+ elif not line.strip():+ flush()+ else:+ current.append(line)+ flush()return [block for block in blocks if block]def _split_delivery_units_for_weixin(content: str) -> List[str]:"""Split formatted content into chat-friendly delivery units.- Weixin can render Markdown, but chat readability is better when top-level- line breaks become separate messages. Keep fenced code blocks intact and- attach indented continuation lines to the previous top-level line so nested- list items do not get torn apart.+ Top-level line breaks become separate messages; fenced code blocks stay+ intact and indented continuation lines attach to the previous top-level+ line so nested list items are not torn apart."""units: List[str] = []-for block in _split_markdown_blocks(content):if _FENCE_RE.match(block.splitlines()[0].strip()):units.append(block)continue-current: List[str] = []for raw_line in block.splitlines():line = raw_line.rstrip()- if not line.strip():- if current:- units.append("\n".join(current).strip())- current = []- continue-- is_continuation = bool(current) and raw_line.startswith((" ", "\t"))- if is_continuation:- current.append(line)+ if current and line.strip() and raw_line.startswith((" ", "\t")):+ current.append(line) # indented continuationcontinue-if current:units.append("\n".join(current).strip())- current = [line]-+ current = [line] if line.strip() else []if current:units.append("\n".join(current).strip())-return [unit for unit in units if unit]def _looks_like_chatty_line_for_weixin(line: str) -> bool:"""Return True when a line looks like a standalone chat utterance."""stripped = line.strip()- if not stripped:- return False- if len(stripped) > 48:- return False- if line.startswith((" ", "\t")):- return False- if stripped.startswith((">", "-", "*", "【", "#", "|")):- return False- if _TABLE_RULE_RE.match(stripped):- return False- if re.match(r"^\*\*[^*]+\*\*$", stripped):- return False- if re.match(r"^\d+\.\s", stripped):- return False- return True+ return bool(+ stripped+ and len(stripped) <= 48+ and not line.startswith((" ", "\t"))+ and not stripped.startswith((">", "-", "*", "【", "#", "|"))+ and not _TABLE_RULE_RE.match(stripped)+ and not re.match(r"^\*\*[^*]+\*\*$", stripped)+ and not re.match(r"^\d+\.\s", stripped)+ )def _looks_like_heading_line_for_weixin(line: str) -> bool:@@ -867,9 +662,7 @@ def _looks_like_heading_line_for_weixin(line: str) -> bool:stripped = line.strip()if not stripped:return False- if _HEADER_RE.match(stripped):- return True- return len(stripped) <= 24 and stripped.endswith((":", ":"))+ return bool(_HEADER_RE.match(stripped)) or (len(stripped) <= 24 and stripped.endswith((":", ":")))def _should_split_short_chat_block_for_weixin(block: str) -> bool:@@ -885,57 +678,36 @@ def _should_split_short_chat_block_for_weixin(block: str) -> bool:def _pack_markdown_blocks_for_weixin(content: str, max_length: int) -> List[str]:if len(content) <= max_length:return [content]- # Block extraction stays weixin-local (_split_markdown_blocks uses the- # anchored _FENCE_RE + per-line rstrip semantics); the greedy packing- # loop is the shared core's.+ # Block extraction stays weixin-local (anchored _FENCE_RE + per-line rstrip);+ # the greedy packing loop is the shared core's.return greedy_pack_blocks(- _split_markdown_blocks(content),- max_length,+ _split_markdown_blocks(content), max_length,overflow=lambda block: BasePlatformAdapter.truncate_message(block, max_length),)-def _split_text_for_weixin_delivery(- content: str, max_length: int, split_per_line: bool = False,-) -> List[str]:+def _split_text_for_weixin_delivery(content: str, max_length: int, split_per_line: bool = False) -> List[str]:"""Split content into sequential Weixin messages.- *compact* (default): Keep everything in a single message whenever it fits- within the platform limit, even when the author used explicit line breaks.- Only fall back to block-aware packing when the payload exceeds- ``max_length``.-- *per_line* (``split_per_line=True``): Legacy behavior — top-level line- breaks become separate chat messages; oversized units still use- block-aware packing.-- The active mode is controlled via ``config.yaml`` ->- ``platforms.weixin.extra.split_multiline_messages`` (``true`` / ``false``)- or the env var ``WEIXIN_SPLIT_MULTILINE_MESSAGES``.+ Compact (default): one message when it fits — unless it reads as a short chatty+ exchange, which becomes separate bubbles. Per-line (legacy, via+ ``extra.split_multiline_messages`` / ``WEIXIN_SPLIT_MULTILINE_MESSAGES``): top-level+ line breaks become separate messages. Oversized units use block-aware packing."""if not content:return []if split_per_line:- # Legacy: one message per top-level delivery unit.if len(content) <= max_length and "\n" not in content:return [content]- chunks: List[str] = []- for unit in _split_delivery_units_for_weixin(content):- if len(unit) <= max_length:- chunks.append(unit)- continue- chunks.extend(_pack_markdown_blocks_for_weixin(unit, max_length))+ chunks = [+ c for unit in _split_delivery_units_for_weixin(content)+ for c in ([unit] if len(unit) <= max_length else _pack_markdown_blocks_for_weixin(unit, max_length))+ ]return [c for c in chunks if c] or [content]-- # Compact (default): single message when under the limit — unless the- # content looks like a short chatty exchange, in which case split into- # separate bubbles for a more natural chat feel.if len(content) <= max_length:- return (- [u for u in _split_delivery_units_for_weixin(content) if u]- if _should_split_short_chat_block_for_weixin(content)- else [content]- )+ if _should_split_short_chat_block_for_weixin(content):+ return [u for u in _split_delivery_units_for_weixin(content) if u]+ return [content]return _pack_markdown_blocks_for_weixin(content, max_length) or [content]@@ -948,8 +720,6 @@ def _coerce_bool(value: Any, default: bool = True) -> bool:if isinstance(value, (int, float)):return bool(value)text = str(value).strip().lower()- if not text:- return defaultif text in {"1", "true", "yes", "on"}:return Trueif text in {"0", "false", "no", "off"}:@@ -963,52 +733,37 @@ def _extract_text(item_list: List[Dict[str, Any]]) -> str:text = str((item.get("text_item") or {}).get("text") or "")ref = item.get("ref_msg") or {}ref_item = ref.get("message_item") or {}- ref_type = ref_item.get("type")- if ref_type in {ITEM_IMAGE, ITEM_VIDEO, ITEM_FILE, ITEM_VOICE}:+ if ref_item.get("type") in {ITEM_IMAGE, ITEM_VIDEO, ITEM_FILE, ITEM_VOICE}:title = ref.get("title") or ""prefix = f"[引用媒体: {title}]\n" if title else "[引用媒体]\n"return f"{prefix}{text}".strip()if ref_item:- parts: List[str] = []- if ref.get("title"):- parts.append(str(ref["title"]))- ref_text = _extract_text([ref_item])- if ref_text:- parts.append(ref_text)+ parts = [p for p in (str(ref["title"]) if ref.get("title") else "", _extract_text([ref_item])) if p]if parts:return f"[引用: {' | '.join(parts)}]\n{text}".strip()return textfor item in item_list:if item.get("type") == ITEM_VOICE:- # #27300: Tencent Cloud's `voice_item.text` is their STT output,- # which is wrong for any non-Chinese audio (the original report- # was a Russian voice message that came back as English- # gibberish). Return empty so the central STT pipeline in- # ``gateway/run.py`` produces the body from the downloaded- # audio instead.+ # Tencent's ``voice_item.text`` is their STT output and is wrong for+ # non-Chinese audio. When raw audio exists return "" so the central+ # STT pipeline in gateway/run.py transcribes the download instead.voice_item = item.get("voice_item") or {}if not (voice_item.get("media") or {}):- # No raw audio to download — Weixin supplied only its own- # speech-to-text result. Use it, but preserve the voice- # origin so the agent can distinguish this from text the- # user typed (#65022).+ # No audio to download — use Weixin's transcript but mark its+ # voice origin so the agent can tell it apart from typed text.voice_text = str(voice_item.get("text") or "")if voice_text:- return (- "[Voice transcription provided by Weixin]\n"- f"{voice_text}"- )- continue+ return f"[Voice transcription provided by Weixin]\n{voice_text}"return ""+_MIME_PREFIX_TYPES = (("image/", MessageType.PHOTO), ("video/", MessageType.VIDEO), ("audio/", MessageType.VOICE))++def _message_type_from_media(media_types: List[str], text: str) -> MessageType:- if any(m.startswith("image/") for m in media_types):- return MessageType.PHOTO- if any(m.startswith("video/") for m in media_types):- return MessageType.VIDEO- if any(m.startswith("audio/") for m in media_types):- return MessageType.VOICE+ for prefix, message_type in _MIME_PREFIX_TYPES:+ if any(m.startswith(prefix) for m in media_types):+ return message_typeif media_types:return MessageType.DOCUMENTif text.startswith("/"):@@ -1021,80 +776,61 @@ def _sync_buf_path(hermes_home: str, account_id: str) -> Path:def _load_sync_buf(hermes_home: str, account_id: str) -> str:- path = _sync_buf_path(hermes_home, account_id)- if not path.exists():- return ""- try:- return json.loads(path.read_text(encoding="utf-8")).get("get_updates_buf", "")- except Exception:- return ""+ data = _read_json(_sync_buf_path(hermes_home, account_id))+ return data.get("get_updates_buf", "") if isinstance(data, dict) else ""def _save_sync_buf(hermes_home: str, account_id: str, sync_buf: str) -> None:- path = _sync_buf_path(hermes_home, account_id)- atomic_json_write(path, {"get_updates_buf": sync_buf})+ atomic_json_write(_sync_buf_path(hermes_home, account_id), {"get_updates_buf": sync_buf})-async def qr_login(- hermes_home: str,- *,- bot_type: str = "3",- timeout_seconds: int = 480,-) -> Optional[Dict[str, str]]:- """- Run the interactive iLink QR login flow.+async def _fetch_qr(session: "aiohttp.ClientSession", bot_type: str) -> Tuple[str, str]:+ """Fetch a login QR; returns (qrcode hex token, qrcode_img_content URL)."""+ qr_resp = await _api_get(+ session, base_url=ILINK_BASE_URL, endpoint=f"{EP_GET_BOT_QR}?bot_type={bot_type}", timeout_ms=QR_TIMEOUT_MS,+ )+ return str(qr_resp.get("qrcode") or ""), str(qr_resp.get("qrcode_img_content") or "")- Returns a credential dict on success, or ``None`` if login fails or times out.- """++def _print_qr(qrcode_value: str, qrcode_url: str, *, report_render_error: bool) -> None:+ """Print the QR URL and an ASCII rendering. WeChat must scan the full liteapp+ URL (``qrcode_img_content``) when available, not the bare hex token."""+ if qrcode_url:+ print(qrcode_url)+ try:+ import qrcode+ qr = qrcode.QRCode()+ qr.add_data(qrcode_url or qrcode_value)+ qr.make(fit=True)+ qr.print_ascii(invert=True)+ except Exception as _qr_exc:+ if report_render_error:+ print(f"(终端二维码渲染失败: {_qr_exc},请直接打开上面的二维码链接)")+++async def qr_login(hermes_home: str, *, bot_type: str = "3", timeout_seconds: int = 480) -> Optional[Dict[str, str]]:+ """Run the interactive iLink QR login flow; credential dict on success, else ``None``."""if not AIOHTTP_AVAILABLE:raise RuntimeError("aiohttp is required for Weixin QR login")-- async with aiohttp.ClientSession(trust_env=gateway_trust_env(), connector=_make_ssl_connector()) as session:+ async with _new_session() as session:try:- qr_resp = await _api_get(- session,- base_url=ILINK_BASE_URL,- endpoint=f"{EP_GET_BOT_QR}?bot_type={bot_type}",- timeout_ms=QR_TIMEOUT_MS,- )+ qrcode_value, qrcode_url = await _fetch_qr(session, bot_type)except Exception as exc:logger.error("weixin: failed to fetch QR code: %s", exc)return None-- qrcode_value = str(qr_resp.get("qrcode") or "")- qrcode_url = str(qr_resp.get("qrcode_img_content") or "")if not qrcode_value:logger.error("weixin: QR response missing qrcode")return None-- # qrcode_url is the full scannable liteapp URL; qrcode_value is just the hex token- # WeChat needs to scan the full URL, not the raw hex string- qr_scan_data = qrcode_url if qrcode_url else qrcode_value-print("\n请使用微信扫描以下二维码:")- if qrcode_url:- print(qrcode_url)- try:- import qrcode-- qr = qrcode.QRCode()- qr.add_data(qr_scan_data)- qr.make(fit=True)- qr.print_ascii(invert=True)- except Exception as _qr_exc:- print(f"(终端二维码渲染失败: {_qr_exc},请直接打开上面的二维码链接)")-+ _print_qr(qrcode_value, qrcode_url, report_render_error=True)deadline = time.monotonic() + timeout_secondscurrent_base_url = ILINK_BASE_URLrefresh_count = 0-while time.monotonic() < deadline:try:status_resp = await _api_get(- session,- base_url=current_base_url,- endpoint=f"{EP_GET_QR_STATUS}?qrcode={qrcode_value}",- timeout_ms=QR_TIMEOUT_MS,+ session, base_url=current_base_url,+ endpoint=f"{EP_GET_QR_STATUS}?qrcode={qrcode_value}", timeout_ms=QR_TIMEOUT_MS,)except asyncio.TimeoutError:await asyncio.sleep(1)@@ -1103,7 +839,6 @@ async def qr_login(logger.warning("weixin: QR poll error: %s", exc)await asyncio.sleep(1)continue-status = str(status_resp.get("status") or "wait")if status == "wait":print(".", end="", flush=True)@@ -1120,25 +855,8 @@ async def qr_login(return Noneprint(f"\n二维码已过期,正在刷新... ({refresh_count}/3)")try:- qr_resp = await _api_get(- session,- base_url=ILINK_BASE_URL,- endpoint=f"{EP_GET_BOT_QR}?bot_type={bot_type}",- timeout_ms=QR_TIMEOUT_MS,- )- qrcode_value = str(qr_resp.get("qrcode") or "")- qrcode_url = str(qr_resp.get("qrcode_img_content") or "")- qr_scan_data = qrcode_url if qrcode_url else qrcode_value- if qrcode_url:- print(qrcode_url)- try:- import qrcode as _qrcode- qr = _qrcode.QRCode()- qr.add_data(qr_scan_data)- qr.make(fit=True)- qr.print_ascii(invert=True)- except Exception:- pass+ qrcode_value, qrcode_url = await _fetch_qr(session, bot_type)+ _print_qr(qrcode_value, qrcode_url, report_render_error=False)except Exception as exc:logger.error("weixin: QR refresh failed: %s", exc)return None@@ -1150,26 +868,69 @@ async def qr_login(if not account_id or not token:logger.error("weixin: QR confirmed but credential payload was incomplete")return None- save_weixin_account(- hermes_home,- account_id=account_id,- token=token,- base_url=base_url,- user_id=user_id,- )+ save_weixin_account(hermes_home, account_id=account_id, token=token, base_url=base_url, user_id=user_id)print(f"\n微信连接成功,account_id={account_id}")- return {- "account_id": account_id,- "token": token,- "base_url": base_url,- "user_id": user_id,- }+ return {"account_id": account_id, "token": token, "base_url": base_url, "user_id": user_id}await asyncio.sleep(1)-print("\n微信登录超时。")return None+def _encrypted_media(kw: Dict[str, Any]) -> Dict[str, Any]:+ return {"encrypt_query_param": kw["encrypt_query_param"], "aes_key": kw["aes_key_for_api"], "encrypt_type": 1}+++def _file_item(**kw: Any) -> Dict[str, Any]:+ return {+ "type": ITEM_FILE,+ "file_item": {"media": _encrypted_media(kw), "file_name": kw["filename"], "len": str(kw["plaintext_size"])},+ }+++def _image_item(**kw: Any) -> Dict[str, Any]:+ return {"type": ITEM_IMAGE, "image_item": {"media": _encrypted_media(kw), "mid_size": kw["ciphertext_size"]}}+++def _video_item(**kw: Any) -> Dict[str, Any]:+ return {+ "type": ITEM_VIDEO,+ "video_item": {+ "media": _encrypted_media(kw),+ "video_size": kw["ciphertext_size"],+ "play_length": kw.get("play_length", 0),+ "video_md5": kw.get("rawfilemd5", ""),+ },+ }+++def _voice_item(**kw: Any) -> Dict[str, Any]:+ return {+ "type": ITEM_VOICE,+ "voice_item": {+ "media": _encrypted_media(kw),+ "encode_type": kw.get("encode_type"),+ "bits_per_sample": kw.get("bits_per_sample"),+ "sample_rate": kw.get("sample_rate"),+ "playtime": kw.get("playtime", 0),+ },+ }+++# Inbound media dispatch: item type -> (item key, download timeout, cache fn, mime or None (= guess from+# file_name), log label). Cache fns are lambdas so monkeypatching the module names takes effect at call time.+_INBOUND_MEDIA: Dict[int, Tuple[str, float, Callable[[bytes, str], str], Optional[str], str]] = {+ ITEM_IMAGE: ("image_item", 30.0, lambda data, _name: cache_image_from_bytes(data, ".jpg"), "image/jpeg", "image"),+ ITEM_VIDEO: ("video_item", 120.0, lambda data, _name: cache_document_from_bytes(data, "video.mp4"), "video/mp4", "video"),+ ITEM_FILE: ("file_item", 60.0, lambda data, name: cache_document_from_bytes(data, name), None, "file"),+ ITEM_VOICE: ("voice_item", 60.0, lambda data, _name: cache_audio_from_bytes(data, ".silk"), "audio/silk", "voice"),+}++_AUDIO_EXTS = {".ogg", ".opus", ".mp3", ".wav", ".m4a", ".flac"}+_VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm", ".3gp"}+_IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".gif"}+_DIRECT_IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"}++class WeixinAdapter(BasePlatformAdapter):"""Native Hermes adapter for Weixin personal accounts."""@@ -1178,8 +939,8 @@ class WeixinAdapter(BasePlatformAdapter):MAX_MESSAGE_LENGTH = 2000- # WeChat does not support editing sent messages — streaming must use the- # fallback "send-final-only" path so the cursor (▉) is never left visible.+ # WeChat cannot edit sent messages — streaming must use the send-final-only+ # path so the cursor (▉) is never left visible.SUPPORTS_MESSAGE_EDITING = Falsedef __init__(self, config: PlatformConfig):@@ -1193,74 +954,48 @@ class WeixinAdapter(BasePlatformAdapter):self._send_session: Optional[aiohttp.ClientSession] = Noneself._poll_task: Optional[asyncio.Task] = Noneself._dedup = MessageDeduplicator(ttl_seconds=MESSAGE_DEDUP_TTL_SECONDS)-- self._account_id = str(extra.get("account_id") or _wx_secret("WEIXIN_ACCOUNT_ID", "")).strip()+ self._account_id = _extra_or_secret(extra, "account_id", "WEIXIN_ACCOUNT_ID")self._token = str(config.token or extra.get("token") or _wx_secret("WEIXIN_TOKEN", "")).strip()- self._base_url = str(extra.get("base_url") or _wx_secret("WEIXIN_BASE_URL", ILINK_BASE_URL)).strip().rstrip("/")- self._cdn_base_url = str(- extra.get("cdn_base_url") or _wx_secret("WEIXIN_CDN_BASE_URL", WEIXIN_CDN_BASE_URL)- ).strip().rstrip("/")+ self._base_url = _extra_or_secret(extra, "base_url", "WEIXIN_BASE_URL", ILINK_BASE_URL).rstrip("/")+ self._cdn_base_url = _extra_or_secret(extra, "cdn_base_url", "WEIXIN_CDN_BASE_URL", WEIXIN_CDN_BASE_URL).rstrip("/")self._send_chunk_delay_seconds = float(- extra.get("send_chunk_delay_seconds") or os.getenv("WEIXIN_SEND_CHUNK_DELAY_SECONDS", "1.5")- )- self._send_chunk_retries = int(- extra.get("send_chunk_retries") or os.getenv("WEIXIN_SEND_CHUNK_RETRIES", "4")+ _extra_or_env(extra, "send_chunk_delay_seconds", "WEIXIN_SEND_CHUNK_DELAY_SECONDS", "1.5"))+ self._send_chunk_retries = int(_extra_or_env(extra, "send_chunk_retries", "WEIXIN_SEND_CHUNK_RETRIES", "4"))self._send_chunk_retry_delay_seconds = float(- extra.get("send_chunk_retry_delay_seconds")- or os.getenv("WEIXIN_SEND_CHUNK_RETRY_DELAY_SECONDS", "1.0")+ _extra_or_env(extra, "send_chunk_retry_delay_seconds", "WEIXIN_SEND_CHUNK_RETRY_DELAY_SECONDS", "1.0"))self._send_text_gate = asyncio.Lock()self._rate_limit_circuit_threshold = max(- 1,- int(- extra.get("rate_limit_circuit_threshold")- or os.getenv("WEIXIN_RATE_LIMIT_CIRCUIT_THRESHOLD", "1")- ),+ 1, int(_extra_or_env(extra, "rate_limit_circuit_threshold", "WEIXIN_RATE_LIMIT_CIRCUIT_THRESHOLD", "1")))self._rate_limit_circuit_window_seconds = float(- extra.get("rate_limit_circuit_window_seconds")- or os.getenv("WEIXIN_RATE_LIMIT_CIRCUIT_WINDOW_SECONDS", "30.0")+ _extra_or_env(extra, "rate_limit_circuit_window_seconds", "WEIXIN_RATE_LIMIT_CIRCUIT_WINDOW_SECONDS", "30.0"))self._rate_limit_circuit_open_seconds = float(- extra.get("rate_limit_circuit_open_seconds")- or os.getenv("WEIXIN_RATE_LIMIT_CIRCUIT_OPEN_SECONDS", "30.0")+ _extra_or_env(extra, "rate_limit_circuit_open_seconds", "WEIXIN_RATE_LIMIT_CIRCUIT_OPEN_SECONDS", "30.0"))self._rate_limit_circuit_until = 0.0self._rate_limit_events: List[float] = []- self._dm_policy = str(extra.get("dm_policy") or _wx_secret("WEIXIN_DM_POLICY", "pairing")).strip().lower()- self._group_policy = str(extra.get("group_policy") or _wx_secret("WEIXIN_GROUP_POLICY", "disabled")).strip().lower()- allow_from = extra.get("allow_from")- if allow_from is None:- allow_from = _wx_secret("WEIXIN_ALLOWED_USERS", "")- group_allow_from = extra.get("group_allow_from")- if group_allow_from is None:- group_allow_from = _wx_secret("WEIXIN_GROUP_ALLOWED_USERS", "")- self._allow_from = self._coerce_list(allow_from)- self._group_allow_from = self._coerce_list(group_allow_from)+ self._dm_policy = _extra_or_secret(extra, "dm_policy", "WEIXIN_DM_POLICY", "pairing").lower()+ self._group_policy = _extra_or_secret(extra, "group_policy", "WEIXIN_GROUP_POLICY", "disabled").lower()+ # ``extra`` wins even when falsy (an explicit empty list disables the env allowlist).+ allow_from, group_allow_from = extra.get("allow_from"), extra.get("group_allow_from")+ self._allow_from = self._coerce_list(_wx_secret("WEIXIN_ALLOWED_USERS", "") if allow_from is None else allow_from)+ self._group_allow_from = self._coerce_list(+ _wx_secret("WEIXIN_GROUP_ALLOWED_USERS", "") if group_allow_from is None else group_allow_from+ )self._split_multiline_messages = _coerce_bool(- extra.get("split_multiline_messages")- or os.getenv("WEIXIN_SPLIT_MULTILINE_MESSAGES"),- default=False,+ extra.get("split_multiline_messages") or os.getenv("WEIXIN_SPLIT_MULTILINE_MESSAGES"), default=False,)- # Text debounce batching (mirrors Telegram adapter pattern).- # iLink delivers messages individually, so rapid multi-message- # bursts (forwarded batches, paste-splits) each trigger a- # separate agent invocation. Default 3s delay / 5s split delay- # are tuned for iLink's typical delivery cadence. Tunable via- # config.yaml under- # ``gateway.platforms.weixin.extra.text_batch_delay_seconds`` /- # ``text_batch_split_delay_seconds``.- self._text_batch_delay_seconds = self._coerce_float_extra(- "text_batch_delay_seconds", 3.0- )- self._text_batch_split_delay_seconds = self._coerce_float_extra(- "text_batch_split_delay_seconds", 5.0- )+ # Text debounce batching (Telegram pattern): iLink delivers messages individually, so rapid+ # bursts would each trigger a separate agent run. 3s / 5s (after a ~2048-char split chunk)+ # suit iLink's cadence; tunable via ``extra.text_batch_delay_seconds`` / ``text_batch_split_delay_seconds``.+ self._text_batch_delay_seconds = self._coerce_float_extra("text_batch_delay_seconds", 3.0)+ self._text_batch_split_delay_seconds = self._coerce_float_extra("text_batch_split_delay_seconds", 5.0)self._pending_text_batches: Dict[str, MessageEvent] = {}self._pending_text_batch_tasks: Dict[str, asyncio.Task] = {}-if self._account_id and not self._token:persisted = load_weixin_account(hermes_home, self._account_id)if persisted:@@ -1268,23 +1003,14 @@ class WeixinAdapter(BasePlatformAdapter):self._base_url = str(persisted.get("base_url") or self._base_url).strip().rstrip("/")def _coerce_float_extra(self, key: str, default: float) -> float:- """Read a float from ``config.extra``, guarding against bad/non-finite values.-- The result is fed directly to ``asyncio.sleep()``, so NaN/Inf and- unparseable values fall back to ``default``.- """+ """Float from ``config.extra``; fed to ``asyncio.sleep()``, so NaN/Inf/negative/unparseable → default."""import math-value = self.config.extra.get(key) if getattr(self.config, "extra", None) else None- if value is None:- return float(default)try:- parsed = float(value)+ parsed = float(value) if value is not None else float(default)except (TypeError, ValueError):return float(default)- if not math.isfinite(parsed) or parsed < 0:- return float(default)- return parsed+ return parsed if math.isfinite(parsed) and parsed >= 0 else float(default)@staticmethoddef _coerce_list(value: Any) -> List[str]:@@ -1297,35 +1023,28 @@ class WeixinAdapter(BasePlatformAdapter):return [str(value).strip()] if str(value).strip() else []async def connect(self, *, is_reconnect: bool = False) -> bool:- if not check_weixin_requirements():- message = "Weixin startup failed: aiohttp and cryptography are required"- self._set_fatal_error("weixin_missing_dependency", message, retryable=False)- logger.warning("[%s] %s", self.name, message)- return False- if not self._token:- message = "Weixin startup failed: WEIXIN_TOKEN is required"- self._set_fatal_error("weixin_missing_token", message, retryable=False)- logger.warning("[%s] %s", self.name, message)- return False- if not self._account_id:- message = "Weixin startup failed: WEIXIN_ACCOUNT_ID is required"- self._set_fatal_error("weixin_missing_account", message, retryable=False)- logger.warning("[%s] %s", self.name, message)- return False-+ preflight = (+ (check_weixin_requirements(), "weixin_missing_dependency", "aiohttp and cryptography are required"),+ (self._token, "weixin_missing_token", "WEIXIN_TOKEN is required"),+ (self._account_id, "weixin_missing_account", "WEIXIN_ACCOUNT_ID is required"),+ )+ for ok, code, reason in preflight:+ if not ok:+ message = f"Weixin startup failed: {reason}"+ self._set_fatal_error(code, message, retryable=False)+ logger.warning("[%s] %s", self.name, message)+ return Falsetry:if not self._acquire_platform_lock('weixin-bot-token', self._token, 'Weixin bot token'):return Falseexcept Exception as exc:logger.debug("[%s] Token lock unavailable (non-fatal): %s", self.name, exc)-- self._poll_session = aiohttp.ClientSession(trust_env=gateway_trust_env(), connector=_make_ssl_connector())- # Disable aiohttp's built-in ClientTimeout (total=None) to prevent- # "Timeout context manager should be used inside a task" errors when- # send() is invoked via asyncio.run_coroutine_threadsafe() from cron.- # Timeout is managed externally via asyncio.wait_for() in _api_post/_api_get.- _no_aiohttp_timeout = aiohttp.ClientTimeout(total=None, connect=None, sock_connect=None, sock_read=None)- self._send_session = aiohttp.ClientSession(trust_env=gateway_trust_env(), connector=_make_ssl_connector(), timeout=_no_aiohttp_timeout)+ self._poll_session = _new_session()+ # total=None disables aiohttp's ClientTimeout so send() works via run_coroutine_threadsafe()+ # from cron; _api_post/_api_get enforce timeouts with asyncio.wait_for() instead.+ self._send_session = _new_session(+ timeout=aiohttp.ClientTimeout(total=None, connect=None, sock_connect=None, sock_read=None)+ )self._token_store.restore(self._account_id)self._poll_task = asyncio.create_task(self._poll_loop(), name="weixin-poll")self._mark_connected()@@ -1333,14 +1052,11 @@ class WeixinAdapter(BasePlatformAdapter):logger.info("[%s] Connected account=%s base=%s", self.name, _safe_id(self._account_id), self._base_url)if self._group_policy != "disabled":logger.warning(- "[%s] WEIXIN_GROUP_POLICY=%s is set, but QR-login connects an iLink bot "- "identity (e.g. [email protected]) which typically cannot be invited into ordinary "- "WeChat groups. iLink usually does not deliver ordinary-group events for "- "these accounts, so group messages may never reach Hermes regardless of this "- "policy. If group delivery doesn't work, the limitation is on the iLink side, "- "not in Hermes.",- self.name,- self._group_policy,+ "[%s] WEIXIN_GROUP_POLICY=%s is set, but QR-login connects an iLink bot identity (e.g. [email protected]) "+ "which typically cannot be invited into ordinary WeChat groups. iLink usually does not deliver "+ "ordinary-group events for these accounts, so group messages may never reach Hermes regardless of "+ "this policy. If group delivery doesn't work, the limitation is on the iLink side, not in Hermes.",+ self.name, self._group_policy,)# Plugin-registered native handlers (ctx.register_platform_handler).self._wire_plugin_handlers(None)@@ -1356,70 +1072,58 @@ class WeixinAdapter(BasePlatformAdapter):self._pending_text_batch_tasks.clear()if self._poll_task and not self._poll_task.done():self._poll_task.cancel()- try:+ with contextlib.suppress(asyncio.CancelledError):await self._poll_task- except asyncio.CancelledError:- passself._poll_task = None- if self._poll_session and not self._poll_session.closed:- await self._poll_session.close()- self._poll_session = None- if self._send_session and not self._send_session.closed:- await self._send_session.close()- self._send_session = None+ for attr in ("_poll_session", "_send_session"):+ session = getattr(self, attr)+ if session and not session.closed:+ await session.close()+ setattr(self, attr, None)self._release_platform_lock()self._mark_disconnected()logger.info("[%s] Disconnected", self.name)+ @staticmethod+ async def _poll_backoff(consecutive_failures: int) -> int:+ """Sleep for the failure streak; returns the new streak count (0 after a full streak)."""+ streak_done = consecutive_failures >= MAX_CONSECUTIVE_FAILURES+ await asyncio.sleep(BACKOFF_DELAY_SECONDS if streak_done else RETRY_DELAY_SECONDS)+ return 0 if streak_done else consecutive_failures+async def _poll_loop(self) -> None:assert self._poll_session is not Nonesync_buf = _load_sync_buf(self._hermes_home, self._account_id)timeout_ms = LONG_POLL_TIMEOUT_MSconsecutive_failures = 0-while self._running:try:response = await _get_updates(- self._poll_session,- base_url=self._base_url,- token=self._token,- sync_buf=sync_buf,- timeout_ms=timeout_ms,+ self._poll_session, base_url=self._base_url, token=self._token, sync_buf=sync_buf, timeout_ms=timeout_ms,)suggested_timeout = response.get("longpolling_timeout_ms")if isinstance(suggested_timeout, int) and suggested_timeout > 0:timeout_ms = suggested_timeout-ret = response.get("ret", 0)errcode = response.get("errcode", 0)if ret not in {0, None} or errcode not in {0, None}:- if (ret == SESSION_EXPIRED_ERRCODE or errcode == SESSION_EXPIRED_ERRCODE- or _is_stale_session_ret(ret, errcode, response.get("errmsg"))):+ if _is_session_expired(response, ret, errcode):logger.error("[%s] Session expired; pausing for 10 minutes", self.name)await asyncio.sleep(600)consecutive_failures = 0continueconsecutive_failures += 1logger.warning(- "[%s] getUpdates failed ret=%s errcode=%s errmsg=%s (%d/%d)",- self.name,- ret,- errcode,- response.get("errmsg", ""),- consecutive_failures,- MAX_CONSECUTIVE_FAILURES,+ "[%s] getUpdates failed ret=%s errcode=%s errmsg=%s (%d/%d)", self.name, ret, errcode,+ response.get("errmsg", ""), consecutive_failures, MAX_CONSECUTIVE_FAILURES,)- await asyncio.sleep(BACKOFF_DELAY_SECONDS if consecutive_failures >= MAX_CONSECUTIVE_FAILURES else RETRY_DELAY_SECONDS)- if consecutive_failures >= MAX_CONSECUTIVE_FAILURES:- consecutive_failures = 0+ consecutive_failures = await self._poll_backoff(consecutive_failures)continue-consecutive_failures = 0new_sync_buf = str(response.get("get_updates_buf") or "")if new_sync_buf:sync_buf = new_sync_buf_save_sync_buf(self._hermes_home, self._account_id, sync_buf)-for message in response.get("msgs") or []:asyncio.create_task(self._process_message_safe(message))except asyncio.CancelledError:@@ -1427,34 +1131,21 @@ class WeixinAdapter(BasePlatformAdapter):except Exception as exc:consecutive_failures += 1logger.error("[%s] poll error (%d/%d): %s", self.name, consecutive_failures, MAX_CONSECUTIVE_FAILURES, exc)- await asyncio.sleep(BACKOFF_DELAY_SECONDS if consecutive_failures >= MAX_CONSECUTIVE_FAILURES else RETRY_DELAY_SECONDS)- if consecutive_failures >= MAX_CONSECUTIVE_FAILURES:- consecutive_failures = 0- # Recycle the poll session after a full failure streak.- # Failed connection attempts through a local HTTP proxy- # (e.g. Clash on 127.0.0.1:7890) can strand sockets that- # never return to the connector's keepalive pool, so the- # tight keepalive_timeout never reaps them. On macOS the- # default 256-fd soft limit turns that drip into- # `[Errno 24] Too many open files` and a gateway crash- # (#79889). Closing the session tears down its connector- # and every socket it holds; a fresh session starts the- # next attempt from zero fds.+ consecutive_failures = await self._poll_backoff(consecutive_failures)+ if consecutive_failures == 0:+ # Full failure streak: recycle the session. Failed connects through a+ # local proxy (e.g. Clash) strand sockets the keepalive reaper never+ # sees; on macOS the 256-fd soft limit then yields EMFILE and a crash.+ # Closing the session tears down its connector and every socket.await self._recycle_poll_session()async def _recycle_poll_session(self) -> None:- """Replace ``_poll_session`` with a fresh one, closing the old.-- Swap-then-close so concurrent ``_process_message`` tasks that grab- ``self._poll_session`` never observe a closed session; in-flight- requests on the old session finish or fail independently.- """+ """Swap in a fresh ``_poll_session`` *then* close the old one, so concurrent+ ``_process_message`` tasks never observe a closed session."""if not self._running or aiohttp is None:returnold = self._poll_session- self._poll_session = aiohttp.ClientSession(- trust_env=gateway_trust_env(), connector=_make_ssl_connector()- )+ self._poll_session = _new_session()if old is not None and not old.closed:try:await old.close()@@ -1470,16 +1161,13 @@ class WeixinAdapter(BasePlatformAdapter):async def _process_message(self, message: Dict[str, Any]) -> None:assert self._poll_session is not Nonesender_id = str(message.get("from_user_id") or "").strip()- if not sender_id:+ if not sender_id or sender_id == self._account_id:return- if sender_id == self._account_id:- return-message_id = str(message.get("message_id") or "").strip()if message_id and self._dedup.is_duplicate(message_id):return- # Secondary content-fingerprint dedup for text messages+ # Secondary content-fingerprint dedup: upstream re-sends identical text under new message_ids.item_list = message.get("item_list") or []text = _extract_text(item_list)if text:@@ -1487,51 +1175,32 @@ class WeixinAdapter(BasePlatformAdapter):if self._dedup.is_duplicate(content_key):logger.debug("[%s] Content-dedup: skipping duplicate message from %s", self.name, sender_id)return-chat_type, effective_chat_id = _guess_chat_type(message, self._account_id)if chat_type == "group":- if self._group_policy == "disabled":+ if self._group_policy == "disabled" or self._group_policy == "pairing":returnif self._group_policy == "allowlist" and effective_chat_id not in self._group_allow_from:return- if self._group_policy == "pairing":- returnelif not self._is_dm_intake_allowed(sender_id):return-context_token = str(message.get("context_token") or "").strip()if context_token:self._token_store.set(self._account_id, sender_id, context_token)asyncio.create_task(self._maybe_fetch_typing_ticket(sender_id, context_token or None))-media_paths: List[str] = []media_types: List[str] = []-for item in item_list:await self._collect_media(item, media_paths, media_types)- ref_message = item.get("ref_msg") or {}- ref_item = ref_message.get("message_item")+ ref_item = (item.get("ref_msg") or {}).get("message_item")if isinstance(ref_item, dict):await self._collect_media(ref_item, media_paths, media_types)-if not text and not media_paths:return-- source = self.build_source(- chat_id=effective_chat_id,- chat_type=chat_type,- user_id=sender_id,- user_name=sender_id,- )+ source = self.build_source(chat_id=effective_chat_id, chat_type=chat_type, user_id=sender_id, user_name=sender_id)event = MessageEvent(- text=text,- message_type=_message_type_from_media(media_types, text),- source=source,- raw_message=message,- message_id=message_id or None,- media_urls=media_paths,- media_types=media_types,- timestamp=datetime.now(),+ text=text, message_type=_message_type_from_media(media_types, text), source=source,+ raw_message=message, message_id=message_id or None, media_urls=media_paths,+ media_types=media_types, timestamp=datetime.now(),)logger.info("[%s] inbound from=%s type=%s media=%d", self.name, _safe_id(sender_id), source.chat_type, len(media_paths))if event.message_type == MessageType.TEXT:@@ -1540,15 +1209,13 @@ class WeixinAdapter(BasePlatformAdapter):await self.handle_message(event)def _open_dm_opted_in(self) -> bool:- # Scoped reads (#93522): the default profile's allow-all flag must- # not leak into a multiplexed secondary profile's admission gate.+ # Scoped reads: the default profile's allow-all flag must not leak into a+ # multiplexed secondary profile's admission gate.if (_wx_secret("GATEWAY_ALLOW_ALL_USERS", "") or "").lower() in {"true", "1", "yes"}:return Truereturn (_wx_secret("WEIXIN_ALLOW_ALL_USERS", "") or "").lower() in {"true", "1", "yes"}def _is_dm_allowed(self, sender_id: str) -> bool:- if self._dm_policy == "disabled":- return Falseif self._dm_policy == "allowlist":return sender_id in self._allow_fromif self._dm_policy == "open":@@ -1556,15 +1223,8 @@ class WeixinAdapter(BasePlatformAdapter):return Falsedef _is_dm_intake_allowed(self, sender_id: str) -> bool:- if self._dm_policy == "disabled":- return False- if self._dm_policy == "allowlist":- return sender_id in self._allow_from- if self._dm_policy == "pairing":- return True- if self._dm_policy == "open":- return self._open_dm_opted_in()- return False+ """Like ``_is_dm_allowed`` but ``pairing`` admits everyone at intake (pairing gate runs later)."""+ return self._dm_policy == "pairing" or self._is_dm_allowed(sender_id)@propertydef enforces_own_access_policy(self) -> bool:@@ -1587,46 +1247,14 @@ class WeixinAdapter(BasePlatformAdapter):profile=event.source.profile,)- def _enqueue_text_event(self, event: MessageEvent) -> None:- """Buffer a text event and reset the flush timer.-- When users forward multiple messages or send rapid-fire texts- via WeChat, each arrives as a separate iLink message. This- concatenates them and waits for a short quiet period before- dispatching the combined message.- """- key = self._text_batch_key(event)- existing = self._pending_text_batches.get(key)- chunk_len = len(event.text or "")- if existing is None:- event._last_chunk_len = chunk_len # type: ignore[attr-defined]- self._pending_text_batches[key] = event- else:- if event.text:- existing.text = f"{existing.text}\n{event.text}" if existing.text else event.text- existing._last_chunk_len = chunk_len # type: ignore[attr-defined]- if event.media_urls:- existing.media_urls.extend(event.media_urls)- existing.media_types.extend(event.media_types)-- prior_task = self._pending_text_batch_tasks.get(key)- if prior_task and not prior_task.done():- prior_task.cancel()- self._pending_text_batch_tasks[key] = asyncio.create_task(- self._flush_text_batch(key)- )-async def _flush_text_batch(self, key: str) -> None:"""Wait for quiet period then dispatch aggregated text."""current_task = asyncio.current_task()try:pending = self._pending_text_batches.get(key)last_len = getattr(pending, "_last_chunk_len", 0) if pending else 0- if last_len >= self._SPLIT_THRESHOLD:- delay = self._text_batch_split_delay_seconds- else:- delay = self._text_batch_delay_seconds- await asyncio.sleep(delay)+ split = last_len >= self._SPLIT_THRESHOLD+ await asyncio.sleep(self._text_batch_split_delay_seconds if split else self._text_batch_delay_seconds)if self._pending_text_batch_tasks.get(key) is not current_task:returnevent = self._pending_text_batches.pop(key, None)@@ -1638,128 +1266,61 @@ class WeixinAdapter(BasePlatformAdapter):self._pending_text_batch_tasks.pop(key, None)async def _collect_media(self, item: Dict[str, Any], media_paths: List[str], media_types: List[str]) -> None:- item_type = item.get("type")- if item_type == ITEM_IMAGE:- path = await self._download_image(item)- if path:- media_paths.append(path)- media_types.append("image/jpeg")- elif item_type == ITEM_VIDEO:- path = await self._download_video(item)- if path:- media_paths.append(path)- media_types.append("video/mp4")- elif item_type == ITEM_FILE:- path, mime = await self._download_file(item)- if path:- media_paths.append(path)- media_types.append(mime)- elif item_type == ITEM_VOICE:- voice_path = await self._download_voice(item)- if voice_path:- media_paths.append(voice_path)- media_types.append("audio/silk")-- async def _download_image(self, item: Dict[str, Any]) -> Optional[str]:- media = _media_reference(item, "image_item")- try:- data = await _download_and_decrypt_media(- self._poll_session,- cdn_base_url=self._cdn_base_url,- encrypted_query_param=media.get("encrypt_query_param"),- aes_key_b64=(item.get("image_item") or {}).get("aeskey")- and base64.b64encode(bytes.fromhex(str((item.get("image_item") or {}).get("aeskey")))).decode("ascii")- or media.get("aes_key"),- full_url=media.get("full_url"),- timeout_seconds=30.0,- )- return cache_image_from_bytes(data, ".jpg")- except Exception as exc:- logger.warning("[%s] image download failed: %s", self.name, exc)- return None-- async def _download_video(self, item: Dict[str, Any]) -> Optional[str]:- media = _media_reference(item, "video_item")- try:- data = await _download_and_decrypt_media(- self._poll_session,- cdn_base_url=self._cdn_base_url,- encrypted_query_param=media.get("encrypt_query_param"),- aes_key_b64=media.get("aes_key"),- full_url=media.get("full_url"),- timeout_seconds=120.0,- )- return cache_document_from_bytes(data, "video.mp4")- except Exception as exc:- logger.warning("[%s] video download failed: %s", self.name, exc)- return None-- async def _download_file(self, item: Dict[str, Any]) -> Tuple[Optional[str], str]:- file_item = item.get("file_item") or {}- media = file_item.get("media") or {}- filename = str(file_item.get("file_name") or "document.bin")- mime = _mime_from_filename(filename)+ spec = _INBOUND_MEDIA.get(item.get("type"))+ if spec is None:+ return+ path, mime = await self._download_media(item, spec)+ if path:+ media_paths.append(path)+ media_types.append(mime)++ async def _download_media(self, item: Dict[str, Any], spec: Tuple[Any, ...]) -> Tuple[Optional[str], str]:+ """Download + decrypt one inbound media item; returns (cached path or None, mime)."""+ item_key, timeout_seconds, cache_fn, mime, label = spec+ payload = item.get(item_key) or {}+ media = payload.get("media") or {}+ filename = str(payload.get("file_name") or "document.bin")+ if mime is None:+ mime = mimetypes.guess_type(filename)[0] or "application/octet-stream"try:+ aes_key_b64 = media.get("aes_key")+ if item_key == "image_item" and payload.get("aeskey"):+ # image_item may carry a raw hex ``aeskey`` beside the media block.+ aes_key_b64 = base64.b64encode(bytes.fromhex(str(payload.get("aeskey")))).decode("ascii") or aes_key_b64data = await _download_and_decrypt_media(- self._poll_session,- cdn_base_url=self._cdn_base_url,- encrypted_query_param=media.get("encrypt_query_param"),- aes_key_b64=media.get("aes_key"),- full_url=media.get("full_url"),- timeout_seconds=60.0,+ self._poll_session, cdn_base_url=self._cdn_base_url, encrypted_query_param=media.get("encrypt_query_param"),+ aes_key_b64=aes_key_b64, full_url=media.get("full_url"), timeout_seconds=timeout_seconds,)- return cache_document_from_bytes(data, filename), mime+ return cache_fn(data, filename), mimeexcept Exception as exc:- logger.warning("[%s] file download failed: %s", self.name, exc)+ logger.warning("[%s] %s download failed: %s", self.name, label, exc)return None, mimeasync def _download_voice(self, item: Dict[str, Any]) -> Optional[str]:- voice_item = item.get("voice_item") or {}- media = voice_item.get("media") or {}- # #27300: previously short-circuited when ``voice_item.text`` was set- # on the assumption that Tencent Cloud's STT was good enough.- # For non-Chinese audio that text is garbage (e.g. a Russian- # message comes back as English phonemes) — we must always- # download the raw audio so ``gateway/run.py``'s central STT- # pipeline can re-transcribe with the user's configured- # mlx-whisper / whisper.cpp / faster-whisper backend.- try:- data = await _download_and_decrypt_media(- self._poll_session,- cdn_base_url=self._cdn_base_url,- encrypted_query_param=media.get("encrypt_query_param"),- aes_key_b64=media.get("aes_key"),- full_url=media.get("full_url"),- timeout_seconds=60.0,- )- return cache_audio_from_bytes(data, ".silk")- except Exception as exc:- logger.warning("[%s] voice download failed: %s", self.name, exc)- return None+ # Always download raw audio (never trust Tencent's ``voice_item.text``) so+ # gateway/run.py's central STT can re-transcribe with the user's backend.+ return (await self._download_media(item, _INBOUND_MEDIA[ITEM_VOICE]))[0]- async def _maybe_fetch_typing_ticket(self, user_id: str, context_token: Optional[str]) -> None:- if not self._poll_session or not self._token:- return- if self._typing_cache.get(user_id):- return+ async def _fetch_typing_ticket(self, session: Any, user_id: str, context_token: Optional[str], failure_label: str) -> Optional[str]:try:response = await _get_config(- self._poll_session,- base_url=self._base_url,- token=self._token,- user_id=user_id,- context_token=context_token,+ session, base_url=self._base_url, token=self._token, user_id=user_id, context_token=context_token,)typing_ticket = str(response.get("typing_ticket") or "")if typing_ticket:self._typing_cache.set(user_id, typing_ticket)+ return typing_ticketexcept Exception as exc:- logger.debug("[%s] getConfig failed for %s: %s", self.name, _safe_id(user_id), exc)+ logger.debug("[%s] %s for %s: %s", self.name, failure_label, _safe_id(user_id), exc)+ return None++ async def _maybe_fetch_typing_ticket(self, user_id: str, context_token: Optional[str]) -> None:+ if not self._poll_session or not self._token or self._typing_cache.get(user_id):+ return+ await self._fetch_typing_ticket(self._poll_session, user_id, context_token, "getConfig failed")def _split_text(self, content: str) -> List[str]:- return _split_text_for_weixin_delivery(- content, self.MAX_MESSAGE_LENGTH, self._split_multiline_messages,- )+ return _split_text_for_weixin_delivery(content, self.MAX_MESSAGE_LENGTH, self._split_multiline_messages)def _rate_limit_cooldown_remaining(self) -> float:return max(0.0, self._rate_limit_circuit_until - time.monotonic())@@ -1769,14 +1330,6 @@ class WeixinAdapter(BasePlatformAdapter):f"iLink sendmessage rate limited; cooldown active for {self._rate_limit_cooldown_remaining():.1f}s")- def _open_rate_limit_circuit(self) -> None:- if self._rate_limit_circuit_open_seconds <= 0:- return- self._rate_limit_circuit_until = max(- self._rate_limit_circuit_until,- time.monotonic() + self._rate_limit_circuit_open_seconds,- )-def _record_rate_limit_event(self) -> bool:"""Record a genuine iLink rate limit and return True if breaker opened."""now = time.monotonic()@@ -1784,7 +1337,10 @@ class WeixinAdapter(BasePlatformAdapter):self._rate_limit_events = [ts for ts in self._rate_limit_events if ts >= window_start]self._rate_limit_events.append(now)if len(self._rate_limit_events) >= self._rate_limit_circuit_threshold:- self._open_rate_limit_circuit()+ if self._rate_limit_circuit_open_seconds > 0:+ self._rate_limit_circuit_until = max(+ self._rate_limit_circuit_until, time.monotonic() + self._rate_limit_circuit_open_seconds,+ )return self._rate_limit_cooldown_remaining() > 0return False@@ -1792,38 +1348,14 @@ class WeixinAdapter(BasePlatformAdapter):self._rate_limit_events.clear()self._rate_limit_circuit_until = 0.0- async def _send_text_chunk(- self,- *,- chat_id: str,- chunk: str,- context_token: Optional[str],- client_id: str,- ) -> None:- """Send a single text chunk with per-chunk retry and backoff.-- On session-expired errors (errcode -14), automatically retries- *without* ``context_token`` — iLink accepts tokenless sends as a- degraded fallback, which keeps cron-initiated push messages working- even when no user message has refreshed the session recently.- """+ async def _send_text_chunk(self, *, chat_id: str, chunk: str, context_token: Optional[str], client_id: str) -> None:+ """Send one text chunk with retry/backoff under the adapter-wide text gate. On session-expired+ (errcode -14) retry once *without* ``context_token`` — iLink accepts tokenless sends as a+ degraded fallback, which keeps cron pushes working when no user message refreshed the session."""async with self._send_text_gate:- await self._send_text_chunk_locked(- chat_id=chat_id,- chunk=chunk,- context_token=context_token,- client_id=client_id,- )+ await self._send_text_chunk_locked(chat_id=chat_id, chunk=chunk, context_token=context_token, client_id=client_id)- async def _send_text_chunk_locked(- self,- *,- chat_id: str,- chunk: str,- context_token: Optional[str],- client_id: str,- ) -> None:- """Send a text chunk while holding the adapter-wide outbound text gate."""+ async def _send_text_chunk_locked(self, *, chat_id: str, chunk: str, context_token: Optional[str], client_id: str) -> None:last_error: Optional[Exception] = Noneretried_without_token = Falsefor attempt in range(self._send_chunk_retries + 1):@@ -1831,46 +1363,24 @@ class WeixinAdapter(BasePlatformAdapter):raise self._rate_limit_error()try:resp = await _send_message(- self._send_session,- base_url=self._base_url,- token=self._token,- to=chat_id,- text=chunk,- context_token=context_token,- client_id=client_id,+ self._send_session, base_url=self._base_url, token=self._token, to=chat_id,+ text=chunk, context_token=context_token, client_id=client_id,)- # Check iLink response for session-expired errorif resp and isinstance(resp, dict):ret = resp.get("ret")errcode = resp.get("errcode")- if (ret is not None and ret not in {0,}) or (errcode is not None and errcode not in {0,}):- is_session_expired = (- ret == SESSION_EXPIRED_ERRCODE- or errcode == SESSION_EXPIRED_ERRCODE- or _is_stale_session_ret(ret, errcode, resp.get("errmsg"))- )- # Session expired — strip token and retry once- if is_session_expired and not retried_without_token and context_token:+ if (ret is not None and ret not in {0}) or (errcode is not None and errcode not in {0}):+ if _is_session_expired(resp, ret, errcode) and not retried_without_token and context_token:retried_without_token = Truecontext_token = None- self._token_store._cache.pop(- self._token_store._key(self._account_id, chat_id), None- )+ self._token_store._cache.pop(self._token_store._key(self._account_id, chat_id), None)logger.warning(- "[%s] session expired for %s; retrying without context_token",- self.name, _safe_id(chat_id),+ "[%s] session expired for %s; retrying without context_token", self.name, _safe_id(chat_id),)continue- # Rate limit (-2) — backoff and retry- is_rate_limited = (- ret == RATE_LIMIT_ERRCODE- or errcode == RATE_LIMIT_ERRCODE- )- if is_rate_limited:+ if ret == RATE_LIMIT_ERRCODE or errcode == RATE_LIMIT_ERRCODE:errmsg = resp.get("errmsg") or resp.get("msg") or "rate limited"- # Record the error so we raise a descriptive- # RuntimeError (instead of AssertionError) if the- # loop exhausts with the server still rate-limiting.+ # Keep a descriptive error for when the loop exhausts while still limited.last_error = RuntimeError(f"iLink sendmessage rate limited: ret={ret} errcode={errcode} errmsg={errmsg}")@@ -1881,15 +1391,12 @@ class WeixinAdapter(BasePlatformAdapter):breakwait = self._send_chunk_retry_delay_seconds * 3 # 3x backoff for rate limitlogger.warning(- "[%s] rate limited for %s; backing off %.1fs before retry",- self.name, _safe_id(chat_id), wait,+ "[%s] rate limited for %s; backing off %.1fs before retry", self.name, _safe_id(chat_id), wait,)await asyncio.sleep(wait)continueerrmsg = resp.get("errmsg") or resp.get("msg") or "unknown error"- raise RuntimeError(- f"iLink sendmessage error: ret={ret} errcode={errcode} errmsg={errmsg}"- )+ raise RuntimeError(f"iLink sendmessage error: ret={ret} errcode={errcode} errmsg={errmsg}")self._reset_rate_limit_circuit()returnexcept Exception as exc:@@ -1899,12 +1406,7 @@ class WeixinAdapter(BasePlatformAdapter):wait = self._send_chunk_retry_delay_seconds * (attempt + 1)logger.warning("[%s] send chunk failed to=%s attempt=%d/%d, retrying in %.2fs: %s",- self.name,- _safe_id(chat_id),- attempt + 1,- self._send_chunk_retries + 1,- wait,- exc,+ self.name, _safe_id(chat_id), attempt + 1, self._send_chunk_retries + 1, wait, exc,)if wait > 0:await asyncio.sleep(wait)@@ -1912,11 +1414,7 @@ class WeixinAdapter(BasePlatformAdapter):raise last_errorasync def send(- self,- chat_id: str,- content: str,- reply_to: Optional[str] = None,- metadata: Optional[Dict[str, Any]] = None,+ self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None,) -> SendResult:if not self._send_session or not self._token:return SendResult(success=False, error="Not connected")@@ -1930,46 +1428,26 @@ class WeixinAdapter(BasePlatformAdapter):local_files, final_content = self.extract_local_files(image_cleaned)local_files = self.filter_local_delivery_paths(local_files)- _AUDIO_EXTS = {".ogg", ".opus", ".mp3", ".wav", ".m4a", ".flac"}- _VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm", ".3gp"}- _IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".gif"}-- async def _deliver_media(path: str, is_voice: bool = False) -> None:- ext = Path(path).suffix.lower()- if is_voice or ext in _AUDIO_EXTS:- await self.send_voice(chat_id=chat_id, audio_path=path, metadata=metadata)- elif ext in _VIDEO_EXTS:- await self.send_video(chat_id=chat_id, video_path=path, metadata=metadata)- elif ext in _IMAGE_EXTS:- await self.send_image_file(chat_id=chat_id, image_path=path, metadata=metadata)- else:- await self.send_document(chat_id=chat_id, file_path=path, metadata=metadata)-+ deliveries = [(p, v, "media") for p, v in media_files] + [(p, False, "local file") for p in local_files]try:- # Deliver extracted MEDIA: attachments first.- for media_path, is_voice in media_files:- try:- await _deliver_media(media_path, is_voice)- except Exception as exc:- logger.warning("[%s] media delivery failed for %s: %s", self.name, media_path, exc)-- # Deliver bare local file paths.- for file_path in local_files:+ for path, is_voice, label in deliveries:+ ext = Path(path).suffix.lower()+ if is_voice or ext in _AUDIO_EXTS:+ sender, key = self.send_voice, "audio_path"+ elif ext in _VIDEO_EXTS:+ sender, key = self.send_video, "video_path"+ elif ext in _IMAGE_EXTS:+ sender, key = self.send_image_file, "image_path"+ else:+ sender, key = self.send_document, "file_path"try:- await _deliver_media(file_path, is_voice=False)+ await sender(chat_id=chat_id, metadata=metadata, **{key: path})except Exception as exc:- logger.warning("[%s] local file delivery failed for %s: %s", self.name, file_path, exc)-- # Deliver text content.+ logger.warning("[%s] %s delivery failed for %s: %s", self.name, label, path, exc)chunks = [c for c in self._split_text(self.format_message(final_content)) if c and c.strip()]for idx, chunk in enumerate(chunks):client_id = f"hermes-weixin-{uuid.uuid4().hex}"- await self._send_text_chunk(- chat_id=chat_id,- chunk=chunk,- context_token=context_token,- client_id=client_id,- )+ await self._send_text_chunk(chat_id=chat_id, chunk=chunk, context_token=context_token, client_id=client_id)last_message_id = client_idif idx < len(chunks) - 1 and self._send_chunk_delay_seconds > 0:await asyncio.sleep(self._send_chunk_delay_seconds)@@ -1979,84 +1457,39 @@ class WeixinAdapter(BasePlatformAdapter):return SendResult(success=False, error=str(exc))async def _ensure_typing_ticket(self, chat_id: str) -> Optional[str]:- """Return a valid typing ticket, refreshing from getConfig if expired.-- The iLink typing ticket has a 600-second TTL. When a long-running- session exceeds that window the cached ticket evicts, and both- ``send_typing`` and ``stop_typing`` silently no-op — leaving the- WeChat client stuck showing the typing indicator forever. This- method transparently refreshes the ticket so the stop signal can- always be delivered.- """+ """Return a valid typing ticket, refreshing via getConfig once the 600s TTL evicts it —+ otherwise ``stop_typing`` no-ops and the WeChat client shows the indicator forever."""ticket = self._typing_cache.get(chat_id)if ticket:return ticketif not self._send_session or not self._token:return None- # Ticket expired or never fetched — refresh via getConfig.- # Use the most recent context_token for this peer if available.context_token = self._token_store.get(self._account_id, chat_id)- try:- response = await _get_config(- self._send_session,- base_url=self._base_url,- token=self._token,- user_id=chat_id,- context_token=context_token,- )- typing_ticket = str(response.get("typing_ticket") or "")- if typing_ticket:- self._typing_cache.set(chat_id, typing_ticket)- return typing_ticket- except Exception as exc:- logger.debug(- "[%s] typing ticket refresh failed for %s: %s",- self.name, _safe_id(chat_id), exc,- )- return None+ return await self._fetch_typing_ticket(self._send_session, chat_id, context_token, "typing ticket refresh failed")- async def send_typing(self, chat_id: str, metadata: Optional[Dict[str, Any]] = None) -> None:+ async def _set_typing(self, chat_id: str, status: int, label: str) -> None:if not self._send_session or not self._token:returntyping_ticket = await self._ensure_typing_ticket(chat_id)if not typing_ticket:returntry:- await _send_typing(- self._send_session,- base_url=self._base_url,- token=self._token,- to_user_id=chat_id,- typing_ticket=typing_ticket,- status=TYPING_START,+ await _api_post(+ self._send_session, base_url=self._base_url, endpoint=EP_SEND_TYPING,+ payload={"ilink_user_id": chat_id, "typing_ticket": typing_ticket, "status": status},+ token=self._token, timeout_ms=CONFIG_TIMEOUT_MS,)except Exception as exc:- logger.debug("[%s] typing start failed for %s: %s", self.name, _safe_id(chat_id), exc)+ logger.debug("[%s] typing %s failed for %s: %s", self.name, label, _safe_id(chat_id), exc)++ async def send_typing(self, chat_id: str, metadata: Optional[Dict[str, Any]] = None) -> None:+ await self._set_typing(chat_id, TYPING_START, "start")async def stop_typing(self, chat_id: str) -> None:- if not self._send_session or not self._token:- return- typing_ticket = await self._ensure_typing_ticket(chat_id)- if not typing_ticket:- return- try:- await _send_typing(- self._send_session,- base_url=self._base_url,- token=self._token,- to_user_id=chat_id,- typing_ticket=typing_ticket,- status=TYPING_STOP,- )- except Exception as exc:- logger.debug("[%s] typing stop failed for %s: %s", self.name, _safe_id(chat_id), exc)+ await self._set_typing(chat_id, TYPING_STOP, "stop")async def send_image(- self,- chat_id: str,- image_url: str,- caption: str,- reply_to: Optional[str] = None,+ self, chat_id: str, image_url: str, caption: str, reply_to: Optional[str] = None,metadata: Optional[Dict[str, Any]] = None,) -> SendResult:if image_url.startswith(("http://", "https://")):@@ -2071,118 +1504,61 @@ class WeixinAdapter(BasePlatformAdapter):return await self.send_document(chat_id, file_path, caption=caption, metadata=metadata)finally:if cleanup and file_path and os.path.exists(file_path):- try:+ with contextlib.suppress(OSError):os.unlink(file_path)- except OSError:- passasync def send_image_file(- self,- chat_id: str,- image_path: str,- caption: Optional[str] = None,- reply_to: Optional[str] = None,- metadata: Optional[Dict[str, Any]] = None,- **kwargs,+ self, chat_id: str, image_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None,+ metadata: Optional[Dict[str, Any]] = None, **kwargs,) -> SendResult:del reply_to, kwargs- return await self.send_document(- chat_id=chat_id,- file_path=image_path,- caption=caption,- metadata=metadata,- )+ return await self.send_document(chat_id=chat_id, file_path=image_path, caption=caption, metadata=metadata)- async def send_document(- self,- chat_id: str,- file_path: str,- caption: Optional[str] = None,- file_name: Optional[str] = None,- reply_to: Optional[str] = None,- metadata: Optional[Dict[str, Any]] = None,- **kwargs,- ) -> SendResult:- del file_name, reply_to, metadata, kwargs+ async def _send_file_result(self, chat_id: str, path: str, caption: str, label: str, **kwargs: Any) -> SendResult:if not self._send_session or not self._token:return SendResult(success=False, error="Not connected")try:- message_id = await self._send_file(chat_id, file_path, caption or "")+ message_id = await self._send_file(chat_id, path, caption, **kwargs)return SendResult(success=True, message_id=message_id)except Exception as exc:- logger.error("[%s] send_document failed to=%s: %s", self.name, _safe_id(chat_id), exc)+ logger.error("[%s] %s failed to=%s: %s", self.name, label, _safe_id(chat_id), exc)return SendResult(success=False, error=str(exc))+ async def send_document(+ self, chat_id: str, file_path: str, caption: Optional[str] = None, file_name: Optional[str] = None,+ reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs,+ ) -> SendResult:+ del file_name, reply_to, metadata, kwargs+ return await self._send_file_result(chat_id, file_path, caption or "", "send_document")+async def send_video(- self,- chat_id: str,- video_path: str,- caption: Optional[str] = None,- reply_to: Optional[str] = None,+ self, chat_id: str, video_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None,metadata: Optional[Dict[str, Any]] = None,) -> SendResult:- if not self._send_session or not self._token:- return SendResult(success=False, error="Not connected")- try:- message_id = await self._send_file(chat_id, video_path, caption or "")- return SendResult(success=True, message_id=message_id)- except Exception as exc:- logger.error("[%s] send_video failed to=%s: %s", self.name, _safe_id(chat_id), exc)- return SendResult(success=False, error=str(exc))+ return await self._send_file_result(chat_id, video_path, caption or "", "send_video")async def send_voice(- self,- chat_id: str,- audio_path: str,- caption: Optional[str] = None,- reply_to: Optional[str] = None,+ self, chat_id: str, audio_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None,metadata: Optional[Dict[str, Any]] = None,) -> SendResult:- if not self._send_session or not self._token:- return SendResult(success=False, error="Not connected")-- # Native outbound Weixin voice bubbles are not proven-working in the- # upstream reference implementation. Prefer a reliable file attachment- # fallback so users at least receive playable audio, even for .silk.- fallback_caption = caption or "[voice message as attachment]"- try:- message_id = await self._send_file(- chat_id,- audio_path,- fallback_caption,- force_file_attachment=True,- )- return SendResult(success=True, message_id=message_id)- except Exception as exc:- logger.error("[%s] send_voice failed to=%s: %s", self.name, _safe_id(chat_id), exc)- return SendResult(success=False, error=str(exc))+ # Native outbound voice bubbles are not proven-working upstream; send a+ # file attachment so users at least receive playable audio (even .silk).+ return await self._send_file_result(+ chat_id, audio_path, caption or "[voice message as attachment]", "send_voice", force_file_attachment=True,+ )async def _download_remote_media(self, url: str) -> str:from tools.url_safety import is_safe_url-if not is_safe_url(url):raise ValueError(f"Blocked unsafe URL (SSRF protection): {url}")-assert self._send_session is not None- # Use asyncio.wait_for() instead of aiohttp ClientTimeout to avoid- # "Timeout context manager should be used inside a task" errors.- async def _do_fetch():- async with self._send_session.get(url) as response:- response.raise_for_status()- return await response.read()- data = await asyncio.wait_for(_do_fetch(), timeout=30)+ data = await _download_bytes(self._send_session, url=url, timeout_seconds=30)suffix = Path(url.split("?", 1)[0]).suffix or ".bin"with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as handle:handle.write(data)return handle.name- async def _send_file(- self,- chat_id: str,- path: str,- caption: str,- force_file_attachment: bool = False,- ) -> str:+ async def _send_file(self, chat_id: str, path: str, caption: str, force_file_attachment: bool = False) -> str:assert self._send_session is not None and self._token is not Noneplaintext = Path(path).read_bytes()media_type, item_builder = self._outbound_media_builder(path, force_file_attachment=force_file_attachment)@@ -2191,157 +1567,57 @@ class WeixinAdapter(BasePlatformAdapter):rawsize = len(plaintext)rawfilemd5 = hashlib.md5(plaintext).hexdigest()upload_response = await _get_upload_url(- self._send_session,- base_url=self._base_url,- token=self._token,- to_user_id=chat_id,- media_type=media_type,- filekey=filekey,- rawsize=rawsize,- rawfilemd5=rawfilemd5,- filesize=_aes_padded_size(rawsize),- aeskey_hex=aes_key.hex(),+ self._send_session, base_url=self._base_url, token=self._token, to_user_id=chat_id,+ media_type=media_type, filekey=filekey, rawsize=rawsize, rawfilemd5=rawfilemd5,+ filesize=_aes_padded_size(rawsize), aeskey_hex=aes_key.hex(),)upload_param = str(upload_response.get("upload_param") or "")upload_full_url = str(upload_response.get("upload_full_url") or "")ciphertext = _aes128_ecb_encrypt(plaintext, aes_key)- # Prefer upload_full_url (direct CDN), fall back to constructed CDN URL- # from upload_param. Both paths use POST — the old PUT for- # upload_full_url caused 404s on the WeChat CDN.- if upload_full_url:- upload_url = upload_full_url- elif upload_param:- upload_url = _cdn_upload_url(self._cdn_base_url, upload_param, filekey)- else:+ # Prefer upload_full_url (direct CDN), else construct from upload_param.+ # Both use POST — PUT to upload_full_url 404s on the WeChat CDN.+ upload_url = upload_full_url or (upload_param and _cdn_upload_url(self._cdn_base_url, upload_param, filekey))+ if not upload_url:raise RuntimeError(f"getUploadUrl returned neither upload_param nor upload_full_url: {upload_response}")-- encrypted_query_param = await _upload_ciphertext(- self._send_session,- ciphertext=ciphertext,- upload_url=upload_url,- )+ encrypted_query_param = await _upload_ciphertext(self._send_session, ciphertext=ciphertext, upload_url=upload_url)context_token = self._token_store.get(self._account_id, chat_id)- # The iLink API expects aes_key as base64(hex_string), not base64(raw_bytes).- # Sending base64(raw_bytes) causes images to show as grey boxes on the- # receiver side because the decryption key doesn't match.- aes_key_for_api = base64.b64encode(aes_key.hex().encode("ascii")).decode("ascii")+ # iLink expects aes_key as base64(hex_string), not base64(raw_bytes) —+ # otherwise images render as grey boxes because the key doesn't match.item_kwargs = {"encrypt_query_param": encrypted_query_param,- "aes_key_for_api": aes_key_for_api,+ "aes_key_for_api": base64.b64encode(aes_key.hex().encode("ascii")).decode("ascii"),"ciphertext_size": len(ciphertext),"plaintext_size": rawsize,"filename": Path(path).name,"rawfilemd5": rawfilemd5,}if media_type == MEDIA_VOICE and path.endswith(".silk"):- item_kwargs["encode_type"] = 6- item_kwargs["sample_rate"] = 24000- item_kwargs["bits_per_sample"] = 16+ item_kwargs.update(encode_type=6, sample_rate=24000, bits_per_sample=16)media_item = item_builder(**item_kwargs)-- last_message_id = Noneif caption:- last_message_id = f"hermes-weixin-{uuid.uuid4().hex}"await _send_message(- self._send_session,- base_url=self._base_url,- token=self._token,- to=chat_id,- text=self.format_message(caption),- context_token=context_token,- client_id=last_message_id,+ self._send_session, base_url=self._base_url, token=self._token, to=chat_id,+ text=self.format_message(caption), context_token=context_token,+ client_id=f"hermes-weixin-{uuid.uuid4().hex}",)-last_message_id = f"hermes-weixin-{uuid.uuid4().hex}"- await _api_post(- self._send_session,- base_url=self._base_url,- endpoint=EP_SEND_MESSAGE,- payload={- "msg": {- "from_user_id": "",- "to_user_id": chat_id,- "client_id": last_message_id,- "message_type": MSG_TYPE_BOT,- "message_state": MSG_STATE_FINISH,- "item_list": [media_item],- **({"context_token": context_token} if context_token else {}),- }- },- token=self._token,- timeout_ms=API_TIMEOUT_MS,+ await _send_items(+ self._send_session, base_url=self._base_url, token=self._token, to=chat_id,+ item_list=[media_item], context_token=context_token, client_id=last_message_id,)return last_message_iddef _outbound_media_builder(self, path: str, force_file_attachment: bool = False):+ """Return (iLink media_type, item builder) for an outbound file."""mime = mimetypes.guess_type(path)[0] or "application/octet-stream"if mime.startswith("image/"):- return MEDIA_IMAGE, lambda **kw: {- "type": ITEM_IMAGE,- "image_item": {- "media": {- "encrypt_query_param": kw["encrypt_query_param"],- "aes_key": kw["aes_key_for_api"],- "encrypt_type": 1,- },- "mid_size": kw["ciphertext_size"],- },- }+ return MEDIA_IMAGE, _image_itemif mime.startswith("video/"):- return MEDIA_VIDEO, lambda **kw: {- "type": ITEM_VIDEO,- "video_item": {- "media": {- "encrypt_query_param": kw["encrypt_query_param"],- "aes_key": kw["aes_key_for_api"],- "encrypt_type": 1,- },- "video_size": kw["ciphertext_size"],- "play_length": kw.get("play_length", 0),- "video_md5": kw.get("rawfilemd5", ""),- },- }+ return MEDIA_VIDEO, _video_itemif path.endswith(".silk") and not force_file_attachment:- return MEDIA_VOICE, lambda **kw: {- "type": ITEM_VOICE,- "voice_item": {- "media": {- "encrypt_query_param": kw["encrypt_query_param"],- "aes_key": kw["aes_key_for_api"],- "encrypt_type": 1,- },- "encode_type": kw.get("encode_type"),- "bits_per_sample": kw.get("bits_per_sample"),- "sample_rate": kw.get("sample_rate"),- "playtime": kw.get("playtime", 0),- },- }- if mime.startswith("audio/"):- return MEDIA_FILE, lambda **kw: {- "type": ITEM_FILE,- "file_item": {- "media": {- "encrypt_query_param": kw["encrypt_query_param"],- "aes_key": kw["aes_key_for_api"],- "encrypt_type": 1,- },- "file_name": kw["filename"],- "len": str(kw["plaintext_size"]),- },- }- return MEDIA_FILE, lambda **kw: {- "type": ITEM_FILE,- "file_item": {- "media": {- "encrypt_query_param": kw["encrypt_query_param"],- "aes_key": kw["aes_key_for_api"],- "encrypt_type": 1,- },- "file_name": kw["filename"],- "len": str(kw["plaintext_size"]),- },- }+ return MEDIA_VOICE, _voice_item+ return MEDIA_FILE, _file_item # audio/* and everything else ship as file attachmentsasync def get_chat_info(self, chat_id: str) -> Dict[str, Any]:chat_type = "group" if chat_id.endswith("@chatroom") else "dm"@@ -2353,102 +1629,68 @@ class WeixinAdapter(BasePlatformAdapter):return _wrap_copy_friendly_lines_for_weixin(_normalize_markdown_blocks(content))+async def _deliver_direct(+ adapter: WeixinAdapter, chat_id: str, message: str,+ media_files: Optional[List[Tuple[str, bool]]], context_token: Optional[str],+) -> Dict[str, Any]:+ last_result: Optional[SendResult] = None+ cleaned = adapter.format_message(message)+ if cleaned:+ last_result = await adapter.send(chat_id, cleaned)+ if not last_result.success:+ return {"error": f"Weixin send failed: {last_result.error}"}+ for media_path, _is_voice in media_files or []:+ if Path(media_path).suffix.lower() in _DIRECT_IMAGE_EXTS:+ last_result = await adapter.send_image_file(chat_id, media_path)+ else:+ last_result = await adapter.send_document(chat_id, media_path)+ if not last_result.success:+ return {"error": f"Weixin media send failed: {last_result.error}"}+ return {+ "success": True,+ "platform": "weixin",+ "chat_id": chat_id,+ "message_id": last_result.message_id if last_result else None,+ "context_token_used": bool(context_token),+ }++async def send_weixin_direct(- *,- extra: Dict[str, Any],- token: Optional[str],- chat_id: str,- message: str,+ *, extra: Dict[str, Any], token: Optional[str], chat_id: str, message: str,media_files: Optional[List[Tuple[str, bool]]] = None,) -> Dict[str, Any]:- """- One-shot send helper for ``send_message`` and cron delivery.+ """One-shot send helper for ``send_message`` and cron delivery.- This bypasses the long-poll adapter lifecycle and uses the raw API directly.+ Reuses the live adapter's session when one is connected on this loop;+ otherwise builds a throwaway adapter over a fresh session."""- account_id = str(extra.get("account_id") or _wx_secret("WEIXIN_ACCOUNT_ID", "")).strip()- base_url = str(extra.get("base_url") or _wx_secret("WEIXIN_BASE_URL", ILINK_BASE_URL)).strip().rstrip("/")- cdn_base_url = str(extra.get("cdn_base_url") or _wx_secret("WEIXIN_CDN_BASE_URL", WEIXIN_CDN_BASE_URL)).strip().rstrip("/")+ account_id = _extra_or_secret(extra, "account_id", "WEIXIN_ACCOUNT_ID")+ base_url = _extra_or_secret(extra, "base_url", "WEIXIN_BASE_URL", ILINK_BASE_URL).rstrip("/")+ cdn_base_url = _extra_or_secret(extra, "cdn_base_url", "WEIXIN_CDN_BASE_URL", WEIXIN_CDN_BASE_URL).rstrip("/")resolved_token = str(token or extra.get("token") or _wx_secret("WEIXIN_TOKEN", "")).strip()if not resolved_token:return {"error": "Weixin token missing. Configure WEIXIN_TOKEN or platforms.weixin.token."}if not account_id:return {"error": "Weixin account ID missing. Configure WEIXIN_ACCOUNT_ID or platforms.weixin.extra.account_id."}-token_store = ContextTokenStore(str(get_hermes_home()))token_store.restore(account_id)context_token = token_store.get(account_id, chat_id)-live_adapter = _LIVE_ADAPTERS.get(resolved_token)send_session = getattr(live_adapter, '_send_session', None)if (live_adapter is not None and send_session is not Noneand not send_session.closedand send_session._loop is asyncio.get_running_loop()):- last_result: Optional[SendResult] = None- cleaned = live_adapter.format_message(message)- if cleaned:- last_result = await live_adapter.send(chat_id, cleaned)- if not last_result.success:- return {"error": f"Weixin send failed: {last_result.error}"}-- for media_path, _is_voice in media_files or []:- ext = Path(media_path).suffix.lower()- if ext in {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"}:- last_result = await live_adapter.send_image_file(chat_id, media_path)- else:- last_result = await live_adapter.send_document(chat_id, media_path)- if not last_result.success:- return {"error": f"Weixin media send failed: {last_result.error}"}-- return {- "success": True,- "platform": "weixin",- "chat_id": chat_id,- "message_id": last_result.message_id if last_result else None,- "context_token_used": bool(context_token),- }-- async with aiohttp.ClientSession(trust_env=gateway_trust_env(), connector=_make_ssl_connector()) as session:+ return await _deliver_direct(live_adapter, chat_id, message, media_files, context_token)+ async with _new_session() as session:adapter = WeixinAdapter(PlatformConfig(enabled=True,token=resolved_token,- extra={- **dict(extra or {}),- "account_id": account_id,- "base_url": base_url,- "cdn_base_url": cdn_base_url,- },+ extra={**dict(extra or {}), "account_id": account_id, "base_url": base_url, "cdn_base_url": cdn_base_url},))- adapter._send_session = session- adapter._session = session- adapter._token = resolved_token- adapter._account_id = account_id- adapter._base_url = base_url- adapter._cdn_base_url = cdn_base_url+ adapter._send_session = adapter._session = session+ adapter._token, adapter._account_id = resolved_token, account_id+ adapter._base_url, adapter._cdn_base_url = base_url, cdn_base_urladapter._token_store = token_store-- last_result: Optional[SendResult] = None- cleaned = adapter.format_message(message)- if cleaned:- last_result = await adapter.send(chat_id, cleaned)- if not last_result.success:- return {"error": f"Weixin send failed: {last_result.error}"}-- for media_path, _is_voice in media_files or []:- ext = Path(media_path).suffix.lower()- if ext in {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"}:- last_result = await adapter.send_image_file(chat_id, media_path)- else:- last_result = await adapter.send_document(chat_id, media_path)- if not last_result.success:- return {"error": f"Weixin media send failed: {last_result.error}"}-- return {- "success": True,- "platform": "weixin",- "chat_id": chat_id,- "message_id": last_result.message_id if last_result else None,- "context_token_used": bool(context_token),- }+ return await _deliver_direct(adapter, chat_id, message, media_files, context_token)diff --git a/gateway/platforms/yuanbao.py b/gateway/platforms/yuanbao.pyindex d36c177794f..1db429ad576 100644--- a/gateway/platforms/yuanbao.py+++ b/gateway/platforms/yuanbao.py@@ -100,9 +100,7 @@ from gateway.session import build_session_keylogger = logging.getLogger(__name__)-# ----------------------------------------------------------------------------# Version / platform constants (used in AUTH_BIND and sign-token headers)-# ---------------------------------------------------------------------------+# Version / platform constants (AUTH_BIND and sign-token headers)try:from hermes_cli import __version__ as _HERMES_VERSIONexcept ImportError:@@ -110,13 +108,9 @@ except ImportError:_APP_VERSION = _HERMES_VERSION_BOT_VERSION = _HERMES_VERSION-_YUANBAO_INSTANCE_ID = str(HERMES_INSTANCE_ID) # single source: yuanbao_proto.HERMES_INSTANCE_ID+_YUANBAO_INSTANCE_ID = str(HERMES_INSTANCE_ID)_OPERATION_SYSTEM = sys.platform-# ----------------------------------------------------------------------------# Module-level constants-# ----------------------------------------------------------------------------DEFAULT_WS_GATEWAY_URL = "wss://bot-wss.yuanbao.tencent.com/wss/connection"DEFAULT_API_DOMAIN = "https://bot.yuanbao.tencent.com"@@ -126,14 +120,9 @@ AUTH_TIMEOUT_SECONDS = 10.0MAX_RECONNECT_ATTEMPTS = 100DEFAULT_SEND_TIMEOUT = 30.0 # WS biz request timeout-# Upper bound on the WS close handshake during teardown (#40383). The-# websockets connection's own close_timeout (5s) blocks until the server-# echoes the close frame; an idle/unresponsive server never replies, stalling-# gateway shutdown by the full timeout. Bounding the close await here keeps-# teardown fast — a responsive server completes the handshake in well under a-# second, so this only caps the pathological hang. Also bounds the reconnect /-# connect-failure cleanup paths that reuse _cleanup_ws(), where a graceful-# close is unnecessary anyway (the socket is being discarded to redial).+# Bound on the WS close handshake at teardown/reconnect: websockets' own close_timeout (5s) waits+# for the server's close echo, which an idle server never sends, stalling shutdown. A responsive+# server finishes well under 1s, so this only caps the pathological hang.WS_CLOSE_TIMEOUT_S = 1.0# Close codes that indicate permanent errors — do NOT reconnect.@@ -142,36 +131,32 @@ NO_RECONNECT_CLOSE_CODES = {4012, 4013, 4014, 4018, 4019, 4021}# Heartbeat timeout threshold — N consecutive missed pongs trigger reconnect.HEARTBEAT_TIMEOUT_THRESHOLD = 2-# Auth error code classification-AUTH_FAILED_CODES = {4001, 4002, 4003} # permanent auth failure, re-sign token-AUTH_RETRYABLE_CODES = {4010, 4011, 4099} # transient, can retry with same token-# Reply Heartbeat configurationREPLY_HEARTBEAT_INTERVAL_S = 2.0 # Send RUNNING every 2 secondsREPLY_HEARTBEAT_TIMEOUT_S = 30.0 # Auto-stop after 30 seconds of inactivity-# Reply-to reference configuration-REPLY_REF_TTL_S = 300.0 # Reference dedup TTL (5 minutes)-# Slow-response hint: push a waiting message when agent produces no data for this duration (seconds)SLOW_RESPONSE_TIMEOUT_S = 120.0SLOW_RESPONSE_MESSAGE = "任务有点复杂,正在努力处理中,请耐心等待..."-# Regex matching Yuanbao resource reference anchors in transcript text:-# [image|ybres:abc123] [file:report.pdf|ybres:xyz789] [voice|ybres:...]-_YB_RES_REF_RE = re.compile(- r"\[(image|voice|video|file(?::[^|\]]*)?)\|ybres:([A-Za-z0-9_\-]+)\]"-)+# Resource anchors in transcript text: [image|ybres:abc] [file:report.pdf|ybres:xyz] [voice|ybres:…]+_YB_RES_REF_RE = re.compile(r"\[(image|voice|video|file(?::[^|\]]*)?)\|ybres:([A-Za-z0-9_\-]+)\]")-# Patched local-media anchors once an inbound resource has been downloaded to the local cache.-# [image: /opt/data/image_cache/img_xxx.bmp]-# [file: report.pdf → /opt/data/.../report.pdf]-# (and any future kind, e.g. [video: /opt/.../clip.mp4])+# Anchors after local download: [image: /path] [file: report.pdf → /path] [video: /path]_YB_LOCAL_MEDIA_RE = re.compile(r"\[(\w+):[^\]]*?(/[^\]]+?)\s*\]")# Media kinds that can be resolved and injected into the model context_RESOLVABLE_MEDIA_KINDS = frozenset({"image", "file", "video"})++def _iter_ybres_refs(matches) -> Iterator[Tuple[str, str, str]]:+ """Turn ``_YB_RES_REF_RE`` matches into ``(rid, kind, filename)`` for resolvable kinds only."""+ for m in matches:+ kind, _, filename = m.group(1).partition(":")+ kind = kind.strip()+ if kind in _RESOLVABLE_MEDIA_KINDS:+ yield m.group(2), kind, filename.strip()+# Strip page indicators like (1/3) appended by BasePlatformAdapter_INDICATOR_RE = re.compile(r'\s*\(\d+/\d+\)$')@@ -180,34 +165,15 @@ OBSERVED_MEDIA_BACKFILL_LOOKBACK = 50# Max number of resource references to resolve per inbound turnOBSERVED_MEDIA_BACKFILL_MAX_RESOLVE_PER_TURN = 12-# Bounded concurrency for inbound media resolve/download.-# - 1 = sequential (legacy behavior, safe rollback knob)-# - 6 = default; aligns with the per-origin HTTP/1.1 ceiling browsers use,-# balances first-token latency vs. backend pressure-# - 12 = upper clamp; matches OBSERVED_MEDIA_BACKFILL_MAX_RESOLVE_PER_TURN-# Configured via config.yaml: platforms.yuanbao.extra.media_resolve_concurrency.+# Inbound media resolve concurrency (config: platforms.yuanbao.extra.media_resolve_concurrency).+# 1 = sequential rollback knob; 6 = browser per-origin HTTP/1.1 ceiling; 12 = backfill cap._DEFAULT_RESOLVE_CONCURRENCY = 6_MIN_RESOLVE_CONCURRENCY = 1_MAX_RESOLVE_CONCURRENCY = 12class MarkdownProcessor:- """Encapsulates all Markdown-related utilities for the Yuanbao platform.-- Provides static methods for:- - Fence detection and streaming merge- - Table row detection and sanitization- - Paragraph-boundary splitting- - Atomic-block extraction and chunk splitting- - Outer markdown fence stripping- - Markdown hint prompt generation- """-- # -- Fence detection ---------------------------------------------------- # All chunking primitives below are thin delegates to the shared- # fence-aware chunker core in gateway.platforms.helpers, which was- # extracted from this class (the richest of the four duplicate- # implementations). The MarkdownProcessor method names are kept for- # the existing call sites and tests.+ """Markdown chunking utilities — thin delegates to the shared fence-aware chunker in+ gateway.platforms.helpers; method names kept for existing call sites and tests."""@staticmethoddef has_unclosed_fence(text: str) -> bool:@@ -232,23 +198,6 @@ class MarkdownProcessor:"""Find the nearest paragraph boundary within max_chars; return (head, tail)."""return _mdchunk.split_at_paragraph_boundary(text, max_chars, len_fn=len_fn)- # -- Atomic block helpers (private) -------------------------------------- @staticmethod- def is_fence_atom(text: str) -> bool:- """Determine whether an atomic block is a code block (starts with ```)."""- return _mdchunk.is_fence_atom(text)-- @staticmethod- def is_table_atom(text: str) -> bool:- """Determine whether an atomic block is a table (first line starts with |)."""- return _mdchunk.is_table_atom(text)-- @staticmethod- def split_into_atoms(text: str) -> list[str]:- """Split text into a list of indivisible "atomic blocks"."""- return _mdchunk.split_markdown_atoms(text)-# -- Core: chunk splitting ---------------------------------------------@classmethod@@ -258,204 +207,43 @@ class MarkdownProcessor:max_chars: int = 4000,len_fn: Optional[Callable[[str], int]] = None,) -> list[str]:- """- Split Markdown text into multiple chunks by max_chars.-- Guarantees (provided by the shared core, prefer_paragraphs mode):- - Each chunk <= max_chars characters (unless a single code block/table itself exceeds the limit)- - Code blocks (```...```) are not split in the middle- - Table rows are not split in the middle (tables output as atomic blocks)- - Split at paragraph boundaries (blank lines, after periods, etc.)- - Small trailing/leading chunks are merged with neighbours when possible- """- return _mdchunk.split_text_fence_aware(- text,- max_chars,- len_fn,- prefer_paragraphs=True,- balance_fences=False,- )-- # -- Block separator inference ------------------------------------------- @classmethod- def infer_block_separator(cls, prev_chunk: str, next_chunk: str) -> str:- """Infer the separator ('\\n' or '\\n\\n') between two split chunks."""- return _mdchunk.infer_block_separator(prev_chunk, next_chunk)-- # -- Streaming fence merge ----------------------------------------------- @classmethod- def merge_block_streaming_fences(cls, chunks: list[str]) -> list[str]:- """Stream-aware fence-conscious chunk merging (see shared core)."""- return _mdchunk.merge_streaming_fences(chunks)-- # -- Outer fence stripping ----------------------------------------------- @staticmethod- def strip_outer_markdown_fence(text: str) -> str:- """- Strip outer Markdown fence.-- When AI reply is entirely wrapped in ```markdown\\n...\\n```, remove the outer fence,- keeping the content. Only strip when the first line is ```markdown (case-insensitive) and the last line is ```.-- Args:- text: Text to process-- Returns:- Text with outer fence stripped (returns original if no match)- """- if not text:- return text-- lines = text.split('\n')- if len(lines) < 3:- return text-- first_line = lines[0].strip()- last_line = lines[-1].strip()-- # First line must be ```markdown (optional language tag md/markdown)- if not re.match(r'^```(?:markdown|md)?\s*$', first_line, re.IGNORECASE):- return text-- # Last line must be plain ```- if last_line != '```':- return text-- # Strip first and last lines- inner = '\n'.join(lines[1:-1])- return inner-- # -- Table sanitization -------------------------------------------------- @staticmethod- def sanitize_markdown_table(text: str) -> str:- """- Table output sanitization.-- Handle common formatting issues in AI-generated Markdown tables:- 1. Remove extra whitespace before/after table rows- 2. Ensure separator rows (|---|---|) are correctly formatted- 3. Remove empty table rows-- Args:- text: Markdown text containing tables-- Returns:- Sanitized text- """- if '|' not in text:- return text-- lines = text.split('\n')- result_lines: list[str] = []-- for line in lines:- stripped = line.strip()-- # Table row processing- if stripped.startswith('|') and stripped.endswith('|'):- # Separator row normalization: | --- | --- | → |---|---|- if re.match(r'^\|[\s\-:]+(\|[\s\-:]+)+\|$', stripped):- cells = stripped.split('|')- normalized = '|'.join(- cell.strip() if cell.strip() else cell- for cell in cells- )- result_lines.append(normalized)- elif stripped == '||' or stripped.replace('|', '').strip() == '':- # Empty table row → skip- continue- else:- result_lines.append(stripped)- else:- result_lines.append(line)-- return '\n'.join(result_lines)-- # -- Markdown hint prompt ------------------------------------------------ @staticmethod- def markdown_hint_system_prompt() -> str:- """- Markdown rendering hint (appended to system prompt).+ """Split Markdown into <= max_chars chunks at paragraph boundaries, never inside a+ code fence or table (an oversized single block may exceed the limit)."""+ return _mdchunk.split_text_fence_aware(text, max_chars, len_fn, prefer_paragraphs=True, balance_fences=False)- Tell AI that Yuanbao platform supports Markdown rendering, including:- - Code blocks (```lang)- - Tables (| col | col |)- - Bold/italic- """- return (- "The current platform supports Markdown rendering. You can use the following formats:\n"- "- Code blocks: ```language\\ncode\\n```\n"- "- Tables: | col1 | col2 |\\n|---|---|\\n| val1 | val2 |\n"- "- Bold: **text** / Italic: *text*\n"- "Please use Markdown formatting when appropriate to improve readability."- )class SignManager:- """Encapsulates all sign-token related logic for the Yuanbao platform.-- Manages token acquisition, caching, signature computation, and- automatic retry. All state (cache, locks) is kept as class-level- attributes so that a single shared client serves the whole process.- """-- # -- Constants ---------------------------------------------------------+ """Sign-token acquisition, caching, signing and retry. All state is class-level so one+ shared client serves the whole process."""TOKEN_PATH = "/api/v5/robotLogic/sign-token"-RETRYABLE_CODE = 10099MAX_RETRIES = 3RETRY_DELAY_S = 1.0-- #: Early refresh margin (seconds), treat as expiring 60s before actual expiry- CACHE_REFRESH_MARGIN_S = 60-- #: HTTP timeout (seconds)+ CACHE_REFRESH_MARGIN_S = 60 # treat as expiring this many seconds earlyHTTP_TIMEOUT_S = 10.0- # -- Class-level shared state -------------------------------------------- # key: app_key → {"token", "bot_id", "expire_ts", ...}- _cache: dict[str, dict[str, Any]] = {}-- # Per-app_key refresh locks — prevents concurrent duplicate sign-token- # requests. Created lazily inside get_refresh_lock() which is only called- # from async context, so the Lock is always bound to the correct loop.- # disconnect() clears this dict to prevent stale locks across reconnects.+ _cache: dict[str, dict[str, Any]] = {} # app_key → {"token", "bot_id", "expire_ts", ...}+ # Per-app_key refresh locks, created lazily from async context so they bind to the running+ # loop; disconnect() clears them to avoid stale locks across reconnects._locks: dict[str, asyncio.Lock] = {}- # -- Internal helpers ---------------------------------------------------@classmethoddef get_refresh_lock(cls, app_key: str) -> asyncio.Lock:- """Return (creating if needed) the per-app_key refresh lock.-- Must only be called from within a running event loop (async context).- """+ """Per-app_key refresh lock (create on demand). Call only from a running event loop."""if app_key not in cls._locks:cls._locks[app_key] = asyncio.Lock()return cls._locks[app_key]@staticmethoddef compute_signature(nonce: str, timestamp: str, app_key: str, app_secret: str) -> str:- """Compute HMAC-SHA256 signature (aligned with TypeScript original).-- plain = nonce + timestamp + app_key + app_secret- signature = HMAC-SHA256(key=app_secret, msg=plain).hexdigest()- """+ """HMAC-SHA256(key=app_secret, msg=nonce+timestamp+app_key+app_secret).hexdigest()."""plain = nonce + timestamp + app_key + app_secretreturn hmac.new(app_secret.encode(), plain.encode(), hashlib.sha256).hexdigest()@staticmethoddef build_timestamp() -> str:- """Build Beijing-time ISO-8601 timestamp (no milliseconds).-- Format: 2006-01-02T15:04:05+08:00- """+ """Beijing-time ISO-8601 timestamp without milliseconds (2006-01-02T15:04:05+08:00)."""bjtime = datetime.now(tz=timezone(timedelta(hours=8)))return bjtime.strftime("%Y-%m-%dT%H:%M:%S+08:00")@@ -471,23 +259,13 @@ class SignManager:@classmethoddef purge_expired(cls) -> int:- """Remove all expired entries from the token cache.-- Returns the number of entries purged. Called lazily from- ``get_token()`` so that stale app_key entries don't accumulate- indefinitely in long-running processes.- """+ """Drop expired token-cache entries (called lazily from get_token); returns count purged."""now = time.time()- expired_keys = [- k for k, v in cls._cache.items()- if now - v.get("expire_ts", 0) > 0- ]+ expired_keys = [k for k, v in cls._cache.items() if now - v.get("expire_ts", 0) > 0]for k in expired_keys:cls._cache.pop(k, None)return len(expired_keys)- # -- Core: fetch --------------------------------------------------------@classmethodasync def fetch(cls,@@ -503,14 +281,12 @@ class SignManager:nonce = secrets.token_hex(16)timestamp = cls.build_timestamp()signature = cls.compute_signature(nonce, timestamp, app_key, app_secret)-payload = {"app_key": app_key,"nonce": nonce,"signature": signature,"timestamp": timestamp,}-headers = {"Content-Type": "application/json","X-AppVersion": _APP_VERSION,@@ -520,24 +296,19 @@ class SignManager:}if route_env:headers["X-Route-Env"] = route_env-logger.info("Sign token request: url=%s%s",url,f" (retry {attempt}/{cls.MAX_RETRIES})" if attempt > 0 else "",)-response = await client.post(url, json=payload, headers=headers)-if response.status_code != 200:body = response.textraise RuntimeError(f"Sign token API returned {response.status_code}: {body[:200]}")-try:result_data: dict[str, Any] = response.json()except Exception as exc:raise ValueError(f"Sign token response parse error: {exc}") from exc-code = result_data.get("code")if code == 0:data = result_data.get("data")@@ -545,7 +316,6 @@ class SignManager:raise ValueError(f"Sign token response missing 'data' field: {result_data}")logger.info("Sign token success: bot_id=%s", data.get("bot_id"))return data-if code == cls.RETRYABLE_CODE and attempt < cls.MAX_RETRIES:logger.warning("Sign token retryable: code=%s, retrying in %ss (attempt=%d/%d)",@@ -556,13 +326,23 @@ class SignManager:)await asyncio.sleep(cls.RETRY_DELAY_S)continue-msg = result_data.get("msg", "")raise RuntimeError(f"Sign token error: code={code}, msg={msg}")-raise RuntimeError("Sign token failed: max retries exceeded")- # -- Public API: get (with cache) --------------------------------------+ @classmethod+ async def _fetch_into_cache(cls, app_key: str, app_secret: str, api_domain: str, route_env: str) -> None:+ data = await cls.fetch(app_key, app_secret, api_domain, route_env)+ duration: int = data.get("duration", 0)+ expire_ts = time.time() + duration if duration > 0 else time.time() + 3600+ cls._cache[app_key] = {+ "token": data.get("token", ""),+ "bot_id": data.get("bot_id", ""),+ "duration": duration,+ "product": data.get("product", ""),+ "source": data.get("source", ""),+ "expire_ts": expire_ts,+ }@classmethodasync def get_token(@@ -572,43 +352,20 @@ class SignManager:api_domain: str,route_env: str = "",) -> dict[str, Any]:- """Get WS auth token (with cache).-- Return directly on cache hit without re-requesting; treat as expiring- 60 seconds before actual expiry, triggering refresh.- """- # Lazily evict stale entries from other app_keys+ """Get WS auth token, served from cache while valid (with CACHE_REFRESH_MARGIN_S)."""cls.purge_expired()-cached = cls._cache.get(app_key)if cached and cls.is_cache_valid(cached):remain = int(cached["expire_ts"] - time.time())logger.info("Using cached token (%ds remaining)", remain)return dict(cached)-async with cls.get_refresh_lock(app_key):cached = cls._cache.get(app_key)if cached and cls.is_cache_valid(cached):return dict(cached)-- data = await cls.fetch(app_key, app_secret, api_domain, route_env)-- duration: int = data.get("duration", 0)- expire_ts = time.time() + duration if duration > 0 else time.time() + 3600-- cls._cache[app_key] = {- "token": data.get("token", ""),- "bot_id": data.get("bot_id", ""),- "duration": duration,- "product": data.get("product", ""),- "source": data.get("source", ""),- "expire_ts": expire_ts,- }-+ await cls._fetch_into_cache(app_key, app_secret, api_domain, route_env)return dict(cls._cache[app_key])- # -- Public API: force refresh ------------------------------------------@classmethodasync def force_refresh(cls,@@ -621,32 +378,16 @@ class SignManager:logger.warning("[force-refresh] Clearing cache and re-signing token: app_key=****%s", app_key[-4:])async with cls.get_refresh_lock(app_key):cls._cache.pop(app_key, None)- data = await cls.fetch(app_key, app_secret, api_domain, route_env)-- duration: int = data.get("duration", 0)- expire_ts = time.time() + duration if duration > 0 else time.time() + 3600-- cls._cache[app_key] = {- "token": data.get("token", ""),- "bot_id": data.get("bot_id", ""),- "duration": duration,- "product": data.get("product", ""),- "source": data.get("source", ""),- "expire_ts": expire_ts,- }-+ await cls._fetch_into_cache(app_key, app_secret, api_domain, route_env)return dict(cls._cache[app_key])from dataclasses import dataclass, field as dc_field+from gateway.platforms._shared import get_scoped_secret as _yb_secret@dataclassclass InboundContext:- """Mutable context flowing through the inbound middleware pipeline.-- Each middleware reads/writes fields on this context. The pipeline- engine passes it to every middleware in registration order.- """+ """Mutable context passed through every inbound middleware in registration order."""adapter: Any # YuanbaoAdapter (forward-ref avoids circular import)raw_frames: list = dc_field(default_factory=list) # Raw bytes frames (debounce-aggregated)@@ -699,25 +440,13 @@ class InboundContext:media_urls: list = dc_field(default_factory=list)media_types: list = dc_field(default_factory=list)- # Populated by ExtractContentMiddleware- link_urls: list = dc_field(default_factory=list)-# Populated by GroupAttributionMiddlewarechannel_prompt: Optional[str] = Noneclass InboundMiddleware(ABC):- """Abstract base class for all inbound pipeline middlewares.-- Subclasses must:- - Set ``name`` as a class-level attribute (used for pipeline registration- and dynamic insertion/removal).- - Implement ``async handle(ctx, next_fn)`` containing the middleware logic.-- Convention:- - Call ``await next_fn()`` to pass control to the next middleware.- - Return without calling ``next_fn`` to **stop** the pipeline.- """+ """Inbound middleware: set class-level ``name`` and implement ``handle(ctx, next_fn)``;+ ``await next_fn()`` continues the pipeline, returning without it stops."""name: str = "" # Override in each subclass@@ -734,64 +463,42 @@ class InboundMiddleware(ABC):class InboundPipeline:- """Onion-model middleware pipeline engine for inbound message processing.-- Inspired by OpenClaw's MessagePipeline (extensions/yuanbao/src/business/- pipeline/engine.ts). Supports named middlewares, conditional guards- (``when``), and ``use_before`` / ``use_after`` / ``remove`` for dynamic- composition.-- Accepts both ``InboundMiddleware`` instances (OOP style) and plain- ``async def(ctx, next_fn)`` callables (functional style) for flexibility.- """+ """Onion-model middleware pipeline: named middlewares, ``when`` guards, use_before/use_after/+ remove. Accepts ``InboundMiddleware`` instances or plain ``async def(ctx, next_fn)`` callables."""def __init__(self) -> None:self._middlewares: list = [] # list of (name, handler, when_fn | None)- # -- Internal helpers ---------------------------------------------------@staticmethoddef _normalize(name_or_mw, handler=None):- """Normalize (name, handler) or (InboundMiddleware,) into (name, callable)."""+ """(InboundMiddleware,) or (name, handler) → (name, callable)."""if isinstance(name_or_mw, InboundMiddleware):return name_or_mw.name, name_or_mw- # Functional style: name is a str, handler is a callablereturn name_or_mw, handler- # -- Registration API ---------------------------------------------------def use(self, name_or_mw, handler=None, when=None) -> "InboundPipeline":- """Append a middleware to the end of the pipeline.-- Accepts either:- - ``pipeline.use(SomeMiddleware())`` — OOP style- - ``pipeline.use("name", some_fn)`` — functional style- """+ """Append ``pipeline.use(SomeMiddleware())`` or ``pipeline.use("name", fn)``."""name, h = self._normalize(name_or_mw, handler)self._middlewares.append((name, h, when))return self- def use_before(self, target: str, name_or_mw, handler=None, when=None) -> "InboundPipeline":- """Insert a middleware before *target* (by name). Appends if not found."""+ def _insert_relative(self, target: str, offset: int, name_or_mw, handler, when) -> "InboundPipeline":name, h = self._normalize(name_or_mw, handler)idx = next((i for i, (n, _, _) in enumerate(self._middlewares) if n == target), None)entry = (name, h, when)if idx is None:self._middlewares.append(entry)else:- self._middlewares.insert(idx, entry)+ self._middlewares.insert(idx + offset, entry)return self+ def use_before(self, target: str, name_or_mw, handler=None, when=None) -> "InboundPipeline":+ """Insert a middleware before *target* (by name). Appends if not found."""+ return self._insert_relative(target, 0, name_or_mw, handler, when)+def use_after(self, target: str, name_or_mw, handler=None, when=None) -> "InboundPipeline":"""Insert a middleware after *target* (by name). Appends if not found."""- name, h = self._normalize(name_or_mw, handler)- idx = next((i for i, (n, _, _) in enumerate(self._middlewares) if n == target), None)- entry = (name, h, when)- if idx is None:- self._middlewares.append(entry)- else:- self._middlewares.insert(idx + 1, entry)- return self+ return self._insert_relative(target, 1, name_or_mw, handler, when)def remove(self, name: str) -> "InboundPipeline":"""Remove a middleware by name."""@@ -803,8 +510,6 @@ class InboundPipeline:"""Return ordered list of registered middleware names (for testing)."""return [n for n, _, _ in self._middlewares]- # -- Execution ----------------------------------------------------------async def execute(self, ctx: InboundContext) -> None:"""Run all middlewares in order. Each middleware receives ``(ctx, next_fn)``."""chain = self._middlewares@@ -815,7 +520,6 @@ class InboundPipeline:while index < len(chain):name, handler, when_fn = chain[index]index += 1- # Conditional guard: skip when returns Falseif when_fn is not None and not when_fn(ctx):continuetry:@@ -824,27 +528,17 @@ class InboundPipeline:logger.error("[InboundPipeline] middleware [%s] error", name, exc_info=True)raisereturn- # End of chain — nothing more to do-await next_fn()-class DecodeMiddleware(InboundMiddleware):- """Decode raw inbound frames from JSON or Protobuf into ctx.push.- Encapsulates JSON push parsing (aligned with TS decodeFromContent)- and Protobuf decoding via ``decode_inbound_push``.- """- name = "decode"+class DecodeMiddleware(InboundMiddleware):+ """Decode raw inbound frames (JSON or protobuf via ``decode_inbound_push``) into ctx.push."""- # -- JSON push parsing -------------------------------------------------+ name = "decode"@staticmethoddef convert_json_msg_body(raw_body: list) -> list:- """Normalize raw JSON msg_body array to [{"msg_type": str, "msg_content": dict}].-- Compatible with both PascalCase (MsgType/MsgContent) and- snake_case (msg_type/msg_content) naming.- """+ """Normalize JSON msg_body (PascalCase or snake_case keys) to [{"msg_type", "msg_content"}]."""result = []for item in raw_body or []:if not isinstance(item, dict):@@ -860,39 +554,24 @@ class DecodeMiddleware(InboundMiddleware):return result@staticmethod- def parse_json_push(raw_json: dict) -> dict | None:- """Convert JSON-format push to a dict with the same structure as- ``decode_inbound_push``.+ def json_sender_fields(raw_json: dict) -> Tuple[str, str]:+ """(from_account, group_code) accepting both Tencent IM PascalCase and internal snake_case keys."""+ from_account = raw_json.get("from_account", "") or raw_json.get("From_Account", "")+ group_code = raw_json.get("group_code", "") or raw_json.get("GroupId", "") or raw_json.get("group_id", "")+ return from_account, group_code- Supports standard callback format (callback_command + from_account +- msg_body) and legacy format fields (GroupId, MsgSeq, MsgKey, MsgBody,- etc.).- """+ @staticmethod+ def parse_json_push(raw_json: dict) -> dict | None:+ """JSON push → dict shaped like ``decode_inbound_push`` output; accepts both the callback+ format (callback_command/from_account/msg_body) and legacy keys (GroupId/MsgSeq/MsgKey/MsgBody)."""if not raw_json:return None-- # Tencent IM callback format uses PascalCase (From_Account, To_Account, MsgBody).- # Internal format uses snake_case (from_account, to_account, msg_body).- # Support both.- from_account = (- raw_json.get("from_account", "")- or raw_json.get("From_Account", "")- )- group_code = (- raw_json.get("group_code", "")- or raw_json.get("GroupId", "")- or raw_json.get("group_id", "")- )- msg_body_raw = (- raw_json.get("msg_body", [])- or raw_json.get("MsgBody", [])- )+ from_account, group_code = DecodeMiddleware.json_sender_fields(raw_json)+ msg_body_raw = (raw_json.get("msg_body", []) or raw_json.get("MsgBody", []))msg_body = DecodeMiddleware.convert_json_msg_body(msg_body_raw)-# Recall callbacks may have neither from_account nor msg_body.if not from_account and not msg_body and not raw_json.get("callback_command"):return None-return {"callback_command": raw_json.get("callback_command", ""),"from_account": from_account,@@ -909,15 +588,12 @@ class DecodeMiddleware(InboundMiddleware):"trace_id": (raw_json.get("log_ext") or {}).get("trace_id", "") if isinstance(raw_json.get("log_ext"), dict) else "",}- # -- Pipeline handler ---------------------------------------------------def _decode_single(self, adapter, data: bytes) -> tuple:"""Decode a single raw frame into (push_dict, decoded_via) or (None, '')."""try:conn_json = json.loads(data.decode("utf-8"))except Exception:conn_json = None-if isinstance(conn_json, dict):push = self.parse_json_push(conn_json)if push:@@ -929,17 +605,14 @@ class DecodeMiddleware(InboundMiddleware):push = Noneif push:return push, "protobuf"-return None, ""async def handle(self, ctx: InboundContext, next_fn) -> None:data_list = ctx.raw_framesif not data_list:return # Stop pipeline — nothing to decode-merged_push = Nonedecoded_via = ""-for data in data_list:push, via = self._decode_single(ctx.adapter, data)if not push:@@ -948,17 +621,12 @@ class DecodeMiddleware(InboundMiddleware):ctx.adapter.name, data.hex()[:128] if data else "(empty)",)continue-if merged_push is None:- # First valid push becomes the basemerged_push = pushdecoded_via = via- logger.info(- "[%s] Frame decoded (via=%s): len=%d",- ctx.adapter.name, via, len(data),- )+ logger.info("[%s] Frame decoded (via=%s): len=%d", ctx.adapter.name, via, len(data))else:- # Subsequent pushes: merge msg_body into the base with a+ # Subsequent pushes: append msg_body to the base, newline-separated.extra_body = push.get("msg_body", [])if extra_body:_sep = {"msg_type": "TIMTextElem", "msg_content": {"text": "\n"}}@@ -967,13 +635,10 @@ class DecodeMiddleware(InboundMiddleware):"[%s] Merged %d extra msg_body elements from aggregated push",ctx.adapter.name, len(extra_body),)-if not merged_push:return # Stop pipeline-ctx.push = merged_pushctx.decoded_via = decoded_via-logger.info("[%s] Push decoded (via=%s): from=%s group=%s msg_id=%s msg_types=%s",ctx.adapter.name, ctx.decoded_via,@@ -983,7 +648,6 @@ class DecodeMiddleware(InboundMiddleware):[e.get("msg_type", "") for e in ctx.push.get("msg_body", [])],)logger.debug("[%s] Push payload: %s", ctx.adapter.name, ctx.push)-await next_fn()@@ -1017,19 +681,12 @@ class DedupMiddleware(InboundMiddleware):class RecallGuardMiddleware(InboundMiddleware):- """Intercept Group.CallbackAfterRecallMsg / C2C.CallbackAfterMsgWithDraw.-- Branch A: message in transcript (observed, not yet consumed) → redact content- Branch B: message not in transcript → append system note- Branch C: message currently being processed → silent interrupt + delayed redact- """+ """Recall callbacks (Group.CallbackAfterRecallMsg / C2C.CallbackAfterMsgWithDraw).+ A: in transcript → redact; B: not in transcript → system note; C: being processed → interrupt + delayed redact."""name = "recall_guard"- _RECALL_COMMANDS = frozenset({- "Group.CallbackAfterRecallMsg",- "C2C.CallbackAfterMsgWithDraw",- })+ _RECALL_COMMANDS = frozenset({"Group.CallbackAfterRecallMsg", "C2C.CallbackAfterMsgWithDraw"})_REDACTED = "[This message was recalled/withdrawn by the sender; original content removed]"async def handle(self, ctx: InboundContext, next_fn) -> None:@@ -1051,26 +708,21 @@ class RecallGuardMiddleware(InboundMiddleware):def _handle_recall(self, ctx: InboundContext, cmd: str) -> None:adapter = ctx.adapterpush = ctx.push or {}-if cmd == "Group.CallbackAfterRecallMsg":seq_list = push.get("recall_msg_seq_list") or []else:mid = push.get("msg_id") or ""seq = push.get("msg_seq")seq_list = [{"msg_id": mid, "msg_seq": seq}] if (mid or seq) else []-if not seq_list:logger.debug("[%s] Recall callback with empty seq_list, skipping", adapter.name)return-group_code = (push.get("group_code") or "").strip()from_account = (push.get("from_account") or "").strip()-for seq_entry in seq_list:recalled_id = seq_entry.get("msg_id") or str(seq_entry.get("msg_seq") or "")if not recalled_id:continue-matched_sk = self._find_processing_session(adapter, recalled_id)if matched_sk is not None:self._interrupt_for_recall(adapter, matched_sk, recalled_id, group_code, from_account)@@ -1103,7 +755,6 @@ class RecallGuardMiddleware(InboundMiddleware):f"\"The message has been recalled.\" in the "f"language the user was using.")-synth_event = MessageEvent(text=recall_text,message_type=MessageType.TEXT,@@ -1116,9 +767,7 @@ class RecallGuardMiddleware(InboundMiddleware):active_event = adapter._active_sessions.get(session_key)if active_event is not None:active_event.set()-logger.info("[%s] Recall interrupt: msg_id=%s session=%s", adapter.name, recalled_id, session_key[:30])-# The interrupted turn will persist the recalled content *after* our# interrupt — schedule a delayed redaction to clean it up.recalled_text = adapter._processing_msg_texts.get(session_key, "")@@ -1156,7 +805,6 @@ class RecallGuardMiddleware(InboundMiddleware):logger.warning("[%s] Recall redact failed: %s", adapter.name, exc)returnlogger.debug("[%s] Recall redact: content not found after polling, session %s", adapter.name, session_key[:30])-task = asyncio.create_task(_redact())adapter._background_tasks.add(task)task.add_done_callback(adapter._background_tasks.discard)@@ -1174,22 +822,12 @@ class RecallGuardMiddleware(InboundMiddleware):except Exception as exc:logger.warning("[%s] Recall: failed to resolve session: %s", adapter.name, exc)return-- # Load transcript from canonical store (state.db). Since PR #29278- # added a ``platform_message_id`` column to the messages table and- # ``append_to_transcript`` wires the incoming dict's ``message_id``- # into it, ``load_transcript`` returns rows with ``message_id`` set- # for any message that was observed with one — Branch A1 (exact id- # match) is the canonical path again.try:transcript = store.load_transcript(sid)except Exception as exc:logger.warning("[%s] Recall: failed to load transcript: %s", adapter.name, exc)return-- # Branch A1: exact platform message_id match. Authoritative when the- # row was persisted with a platform_message_id (observed group- # messages and any inbound message whose adapter carried a msg_id).+ # A1: exact platform message_id match (rows persisted with a platform_message_id).target = Nonebranch_label = ""for entry in transcript:@@ -1197,10 +835,8 @@ class RecallGuardMiddleware(InboundMiddleware):target = entrybranch_label = "branch A1: id match"break- # Branch A2: content-match fallback for messages that lack an exact- # platform id on the row — e.g. agent-processed @bot messages- # (run.py doesn't carry msg_id through) or older rows persisted- # before the platform_message_id column existed.+ # A2: content-match fallback for rows without a platform id (agent-processed @bot+ # messages — run.py doesn't carry msg_id through — or pre-column rows).if target is None and recalled_content:for entry in transcript:if entry.get("role") == "user" and entry.get("content") == recalled_content:@@ -1215,7 +851,6 @@ class RecallGuardMiddleware(InboundMiddleware):except Exception as exc:logger.warning("[%s] Recall: rewrite_transcript failed: %s", adapter.name, exc)return-# Branch B: not found in transcript → append system notestore.append_to_transcript(sid, {"role": "system",@@ -1261,34 +896,8 @@ class ChatRoutingMiddleware(InboundMiddleware):await next_fn()-def _yb_secret(name: str, default: Optional[str] = None) -> Optional[str]:- """Resolve a per-profile ``YUANBAO_*`` / gateway setting honoring the- active secret scope (#93522).-- Under ``gateway.multiplex_profiles`` every secondary profile is- constructed inside ``_profile_runtime_scope`` (``gateway/run.py``) and- its ``.env`` lives in that scope — raw ``os.getenv`` misses it and- leaks the default profile's values instead. The primary/active profile- is constructed without a scope and legitimately owns ``os.environ``,- so fall back to it there (same canonical shape as QQ's- ``_resolve_qq_secret``).- """- from agent.secret_scope import UnscopedSecretError, get_secret-- try:- val = get_secret(name, default)- except UnscopedSecretError:- val = os.getenv(name)- return val if val is not None else default--class AccessPolicy:- """Platform-level DM / Group access control policy.-- Encapsulates the allow/deny logic so that both inbound middleware- and outbound ``send_dm`` can share the same rules without reaching- into adapter internals.- """+ """DM / group access rules shared by inbound middleware and outbound ``send_dm``."""def __init__(self,@@ -1307,42 +916,30 @@ class AccessPolicy:return Truereturn (_yb_secret("YUANBAO_ALLOW_ALL_USERS", "") or "").lower() in {"true", "1", "yes"}+ def _evaluate(self, policy: str, allow_from: list[str], principal: str, *, pairing: bool) -> bool:+ """Shared allow/deny rule; *pairing* is the verdict for the "pairing" policy."""+ if policy == "allowlist":+ return principal in allow_from+ if policy == "pairing":+ return pairing+ if policy == "open":+ return self._open_dm_opted_in()+ return False # "disabled" or unknown+def is_dm_allowed(self, sender_id: str) -> bool:"""Strict DM authorization — pairing does not imply access."""- if self._dm_policy == "disabled":- return False- if self._dm_policy == "allowlist":- return sender_id.strip() in self._dm_allow_from- if self._dm_policy == "open":- return self._open_dm_opted_in()- return False+ return self._evaluate(self._dm_policy, self._dm_allow_from, sender_id.strip(), pairing=False)def is_dm_intake_allowed(self, sender_id: str) -> bool:"""Whether a DM may reach gateway intake (pairing handshake path)."""principal = str(sender_id or "").strip()if not principal:return False- if self._dm_policy == "disabled":- return False- if self._dm_policy == "allowlist":- return principal in self._dm_allow_from- if self._dm_policy == "pairing":- return True- if self._dm_policy == "open":- return self._open_dm_opted_in()- return False+ return self._evaluate(self._dm_policy, self._dm_allow_from, principal, pairing=True)def is_group_allowed(self, group_code: str) -> bool:"""Platform-level group chat inbound filter (open / allowlist / disabled)."""- if self._group_policy == "disabled":- return False- if self._group_policy == "allowlist":- return group_code.strip() in self._group_allow_from- if self._group_policy == "pairing":- return False- if self._group_policy == "open":- return self._open_dm_opted_in()- return False+ return self._evaluate(self._group_policy, self._group_allow_from, group_code.strip(), pairing=False)@propertydef dm_policy(self) -> str:@@ -1368,28 +965,20 @@ class AccessGuardMiddleware(InboundMiddleware):adapter.name, ctx.from_account, policy.dm_policy,)return # Stop pipeline- elif ctx.chat_type == "group":- if not policy.is_group_allowed(ctx.group_code):- logger.debug(- "[%s] Group %s blocked by group_policy=%s",- adapter.name, ctx.group_code, policy.group_policy,- )- return # Stop pipeline+ elif ctx.chat_type == "group" and not policy.is_group_allowed(ctx.group_code):+ logger.debug(+ "[%s] Group %s blocked by group_policy=%s",+ adapter.name, ctx.group_code, policy.group_policy,+ )+ return # Stop pipelineawait next_fn()class AutoSetHomeMiddleware(InboundMiddleware):- """Auto-designate the first inbound conversation as Yuanbao home channel.-- Triggers when no home channel is configured, or when an existing group-chat- home is superseded by the first DM (direct > group upgrade).- Silent: writes config.yaml and env, no user-facing message.-- Runs after :class:`BuildSourceMiddleware` and :class:`GroupAtGuardMiddleware`- so unaddressed group traffic is dropped before home-channel persistence.- Only senders that pass strict authorization (allowlist / explicit open- opt-in / pairing-store approval) may claim ``YUANBAO_HOME_CHANNEL``.- Intake-only pairing forwards must not claim ``YUANBAO_HOME_CHANNEL``.+ """Silently designate the first inbound conversation as home channel (config.yaml + env);+ a group home is upgraded by the first DM. Runs after GroupAtGuard so unaddressed group traffic+ never claims it; only strictly-authorized senders (allowlist / open opt-in / pairing-approved)+ may — intake-only pairing forwards must not."""name = "auto-sethome"@@ -1408,11 +997,9 @@ class AutoSetHomeMiddleware(InboundMiddleware):try:from hermes_constants import get_hermes_homefrom hermes_cli.config import atomic_config_write, read_user_config_raw-_home = get_hermes_home()config_path = _home / "config.yaml"- # Write-back round-trip: raw read is correct (merged- # defaults must not be persisted to the user's file).+ # Raw read: merged defaults must not be persisted to the user's file.user_config: dict = read_user_config_raw(config_path)user_config["YUANBAO_HOME_CHANNEL"] = ctx.chat_idatomic_config_write(config_path, user_config)@@ -1421,12 +1008,29 @@ class AutoSetHomeMiddleware(InboundMiddleware):"[%s] Auto-sethome: designated %s (%s) as Yuanbao home channel",adapter.name, ctx.chat_id, ctx.chat_name,)- # Silent auto-sethome: no user-facing message, only logexcept Exception as e:logger.warning("[%s] Auto-sethome failed: %s", adapter.name, e)await next_fn()+def _iter_custom_elems(msg_body: list) -> Iterator[Tuple[Any, dict]]:+ """Yield ``(custom, content)`` for each TIMCustomElem whose ``data`` parses as JSON (any type)."""+ for elem in msg_body or []:+ if not isinstance(elem, dict) or elem.get("msg_type") != "TIMCustomElem":+ continue+ content = elem.get("msg_content", {}) or {}+ if not isinstance(content, dict):+ continue+ data_str = content.get("data", "")+ if not data_str:+ continue+ try:+ custom = json.loads(data_str)+ except (json.JSONDecodeError, TypeError):+ continue+ yield custom, content++class ExtractContentMiddleware(InboundMiddleware):"""Extract raw text and media refs from msg_body."""@@ -1469,14 +1073,7 @@ class ExtractContentMiddleware(InboundMiddleware):@staticmethoddef _parse_resource_id(url: str) -> str:- """Extract resourceId from Yuanbao resource URL query parameters.-- Args:- url: Resource URL (e.g., https://...?resourceId=abc123)-- Returns:- Resource ID string, or empty string if not found- """+ """resourceId from a Yuanbao resource URL's query string, or ""."""if not url:return ""try:@@ -1486,41 +1083,34 @@ class ExtractContentMiddleware(InboundMiddleware):except Exception:return ""+ @staticmethod+ def _pick_image_url(content: dict) -> str:+ """URL of the medium image (index 1), falling back to index 0, else ""."""+ arr = content.get("image_info_array")+ if not isinstance(arr, list):+ arr = []+ image_info = None+ if len(arr) > 1 and isinstance(arr[1], dict):+ image_info = arr[1]+ elif len(arr) > 0 and isinstance(arr[0], dict):+ image_info = arr[0]+ return str((image_info or {}).get("url") or "").strip()+@classmethoddef _extract_text(cls, msg_body: list) -> str:- """Extract plain text content from MsgBody.-- - TIMTextElem -> text field- - TIMImageElem -> "[image]" / "[image|ybres:RID]"- - TIMFileElem -> "[file: {filename}]" / "[file:{name}|ybres:RID]"- - TIMSoundElem -> "[voice]" / "[voice|ybres:RID]"- - TIMVideoFileElem -> "[video]" / "[video|ybres:RID]"- - TIMFaceElem -> "[emoji: {name}]" or "[emoji]"- - TIMCustomElem -> try to extract data field, otherwise "[custom message]"- - Multiple elems joined with spaces- """+ """Plain text from MsgBody: text elems verbatim; media as ``[kind|ybres:RID]`` / ``[kind]``+ (file: ``[file:{name}|ybres:RID]``); TIMFaceElem ``[emoji: name]``; custom elems by+ elem_type. Parts are space-joined."""parts: list[str] = []for elem in msg_body:elem_type: str = elem.get("msg_type", "")content: dict = elem.get("msg_content", {})-if elem_type == "TIMTextElem":text = content.get("text", "")if text:parts.append(text)elif elem_type == "TIMImageElem":- # Extract resourceId from image_info_array URL- image_info_array = content.get("image_info_array")- if not isinstance(image_info_array, list):- image_info_array = []- image_info = None- # Prefer medium image (index 1), fallback to index 0- if len(image_info_array) > 1 and isinstance(image_info_array[1], dict):- image_info = image_info_array[1]- elif len(image_info_array) > 0 and isinstance(image_info_array[0], dict):- image_info = image_info_array[0]- image_url = str((image_info or {}).get("url") or "").strip()- rid = cls._parse_resource_id(image_url)+ rid = cls._parse_resource_id(cls._pick_image_url(content))parts.append(f"[image|ybres:{rid}]" if rid else "[image]")elif elem_type == "TIMFileElem":filename = content.get("file_name", content.get("fileName", content.get("filename", "")))@@ -1530,44 +1120,13 @@ class ExtractContentMiddleware(InboundMiddleware):parts.append(f"[file:{filename}|ybres:{rid}]" if filename else f"[file|ybres:{rid}]")else:parts.append(f"[file: {filename}]" if filename else "[file]")- elif elem_type == "TIMSoundElem":- sound_url = str(content.get("url") or "").strip()- rid = cls._parse_resource_id(sound_url)- parts.append(f"[voice|ybres:{rid}]" if rid else "[voice]")- elif elem_type == "TIMVideoFileElem":- video_url = str(content.get("url") or "").strip()- rid = cls._parse_resource_id(video_url)- parts.append(f"[video|ybres:{rid}]" if rid else "[video]")+ elif elem_type in ("TIMSoundElem", "TIMVideoFileElem"):+ kind = "voice" if elem_type == "TIMSoundElem" else "video"+ rid = cls._parse_resource_id(str(content.get("url") or "").strip())+ parts.append(f"[{kind}|ybres:{rid}]" if rid else f"[{kind}]")elif elem_type == "TIMCustomElem":- data_val = content.get("data", "")- if data_val:- try:- custom = json.loads(data_val)- if not isinstance(custom, dict):- parts.append("[unsupported message type]")- continue- ctype = custom.get("elem_type")- if ctype == 1002:- parts.append(custom.get("text", "[mention]"))- elif ctype == 1010:- parts.append(cls._format_shared_link(custom))- elif ctype == 1007:- text = cls._format_link_understanding(custom)- if text:- parts.append(text)- else:- parts.append("[unsupported message type]")- elif ctype == 1009:- # WeChat forwarded chat record: use the truncated summary text.- parts.append(custom.get("text", "[chat record]"))- else:- parts.append("[unsupported message type]")- except (json.JSONDecodeError, TypeError):- parts.append(data_val)- else:- parts.append("[unsupported message type]")+ parts.append(cls._custom_elem_text(content.get("data", "")))elif elem_type == "TIMFaceElem":- # Sticker/emoji: extract name from data JSONraw_data = content.get("data", "")face_name = ""if raw_data:@@ -1580,14 +1139,36 @@ class ExtractContentMiddleware(InboundMiddleware):elif elem_type:# Unknown element type — include type as placeholderparts.append(f"[{elem_type}]")-return " ".join(parts) if parts else ""+ _UNSUPPORTED = "[unsupported message type]"++ @classmethod+ def _custom_elem_text(cls, data_val: str) -> str:+ """Text for a TIMCustomElem by elem_type: 1002 mention, 1010 share card, 1007 link card,+ 1009 forwarded chat-record summary; malformed JSON is passed through verbatim."""+ if not data_val:+ return cls._UNSUPPORTED+ try:+ custom = json.loads(data_val)+ except (json.JSONDecodeError, TypeError):+ return data_val+ if not isinstance(custom, dict):+ return cls._UNSUPPORTED+ ctype = custom.get("elem_type")+ if ctype == 1002:+ return custom.get("text", "[mention]")+ if ctype == 1010:+ return cls._format_shared_link(custom)+ if ctype == 1007:+ return cls._format_link_understanding(custom) or cls._UNSUPPORTED+ if ctype == 1009:+ return custom.get("text", "[chat record]")+ return cls._UNSUPPORTED+@staticmethoddef _rewrite_slash_command(text: str) -> str:- """Normalize input text: strip whitespace and convert full-width slash- (Chinese input method) to ASCII slash so commands are recognized correctly.- """+ """Strip and convert a leading full-width slash (Chinese IME) to ASCII so commands match."""text = text.strip()if text.startswith('\uff0f'): # Full-width slashtext = '/' + text[1:]@@ -1595,11 +1176,7 @@ class ExtractContentMiddleware(InboundMiddleware):@staticmethoddef _extract_inbound_media_refs(msg_body: list) -> List[Dict[str, str]]:- """Extract inbound image/file references from TIM msg_body.-- Return example:- [{"kind": "image", "url": "https://..."}, {"kind": "file", "url": "...", "name": "a.pdf"}]- """+ """Inbound image/file refs: ``[{"kind": "image", "url": ...}, {"kind": "file", "url": ..., "name": ...}]``."""refs: List[Dict[str, str]] = []for elem in msg_body or []:if not isinstance(elem, dict):@@ -1608,22 +1185,11 @@ class ExtractContentMiddleware(InboundMiddleware):content = elem.get("msg_content", {}) or {}if not isinstance(content, dict):continue-if msg_type == "TIMImageElem":- # Prefer medium image (index 1), fallback to index 0.- image_info_array = content.get("image_info_array")- if not isinstance(image_info_array, list):- image_info_array = []- image_info = None- if len(image_info_array) > 1 and isinstance(image_info_array[1], dict):- image_info = image_info_array[1]- elif len(image_info_array) > 0 and isinstance(image_info_array[0], dict):- image_info = image_info_array[0]- image_url = str((image_info or {}).get("url") or "").strip()+ image_url = ExtractContentMiddleware._pick_image_url(content)if image_url:refs.append({"kind": "image", "url": image_url})continue-if msg_type == "TIMFileElem":file_url = str(content.get("url") or "").strip()file_name = (@@ -1638,77 +1204,22 @@ class ExtractContentMiddleware(InboundMiddleware):refs.append(ref)return refs- @staticmethod- def _extract_link_urls(msg_body: list) -> list:- """Extract link URLs from share-card (1010) and link-understanding (1007) custom elems."""- urls: list[str] = []- for elem in msg_body or []:- if not isinstance(elem, dict) or elem.get("msg_type") != "TIMCustomElem":- continue- data_str = (elem.get("msg_content") or {}).get("data", "")- if not data_str:- continue- try:- custom = json.loads(data_str)- except (json.JSONDecodeError, TypeError):- continue- if not isinstance(custom, dict):- continue- ctype = custom.get("elem_type")- if ctype == 1010:- link = custom.get("link")- if link and isinstance(link, str):- urls.append(link)- elif ctype == 1007:- content = custom.get("content")- if content:- try:- parsed = json.loads(content)- link = parsed.get("link") if isinstance(parsed, dict) else None- if link and isinstance(link, str):- urls.append(link)- except (json.JSONDecodeError, TypeError):- pass- return urls-@staticmethoddef _extract_forwarded_records(msg_body: list, user_id: str = "") -> Optional[dict]:- """Extract ForwardMsgData from ext_map for elem_type 1009 (WeChat forward).-- The detailed chat-record payload lives in ``msg_content.ext_map``- (protobuf field 999, ``map<string, string>``):- - key format: ``wexin_forward_msg_[forward_msg_id]_[userid]``- - value: a **base64-encoded protobuf** ``ForwardMsgData`` (NOT JSON).- Decode with base64 then ``decode_forward_msg_data`` to recover the- ``sub_type`` / ``nick_name`` / ``msg`` structure.-- Matching strategy: take the first ``wexin_forward_msg_`` entry whose- decoded payload is a valid ``ForwardMsgData`` (``sub_type == 1``).+ """ForwardMsgData for elem_type 1009 (WeChat forward), or None.- Returns the parsed ``ForwardMsgData`` dict or ``None``.+ Payload lives in ``msg_content.ext_map`` (pb field 999) under keys+ ``wexin_forward_msg_[id]_[userid]``; values are base64 protobuf (NOT JSON).+ First entry decoding to ``sub_type == 1`` wins."""- for elem in msg_body or []:- if not isinstance(elem, dict) or elem.get("msg_type") != "TIMCustomElem":- continue- content = elem.get("msg_content", {}) or {}- if not isinstance(content, dict):- continue- data_str = content.get("data", "")- if not data_str:- continue- try:- custom = json.loads(data_str)- except (json.JSONDecodeError, TypeError):- continue+ for custom, content in _iter_custom_elems(msg_body):if not (isinstance(custom, dict) and custom.get("elem_type") == 1009):continue-ext_map = content.get("ext_map") or {}if not isinstance(ext_map, dict) or not ext_map:return Nonedef _parse_value(value):- # ext_map values are base64-encoded ForwardMsgData protobuf.if not isinstance(value, str) or not value:return Nonetry:@@ -1719,21 +1230,17 @@ class ExtractContentMiddleware(InboundMiddleware):if isinstance(data, dict) and data.get("sub_type") == 1:return datareturn None-- # Take the first valid wexin_forward_msg_ entry.for key, value in ext_map.items():if not key.startswith("wexin_forward_msg_"):continueparsed = _parse_value(value)if parsed is not None:return parsed-return Noneasync def handle(self, ctx: InboundContext, next_fn) -> None:ctx.raw_text = self._rewrite_slash_command(self._extract_text(ctx.msg_body))ctx.media_refs = self._extract_inbound_media_refs(ctx.msg_body)- ctx.link_urls = self._extract_link_urls(ctx.msg_body)ctx.forwarded_records = self._extract_forwarded_records(ctx.msg_body, ctx.from_account)await next_fn()@@ -1763,28 +1270,17 @@ class PlaceholderFilterMiddleware(InboundMiddleware):class OwnerCommandMiddleware(InboundMiddleware):- """Detect bot-owner slash commands in group chat.-- Identifies in-group allowlisted slash commands and determines sender identity.- Owner commands skip @Bot detection; non-owner attempts are rejected.- """+ """Bot-owner slash commands in groups: allowlisted commands skip @Bot; non-owner attempts are rejected."""name = "owner-command"- # Slash command allowlist that bot owner can execute in group without @BotALLOWLIST: frozenset = frozenset({"/new", "/reset", "/retry", "/undo", "/stop","/approve", "/deny", "/bg","/btw", "/queue", "/q",})- @staticmethod- def _rewrite_slash_command(text: str) -> str:- """Normalize full-width slash to ASCII slash and strip whitespace."""- text = text.strip()- if text.startswith('\uff0f'): # Full-width slash- text = '/' + text[1:]- return text+ _rewrite_slash_command = staticmethod(ExtractContentMiddleware._rewrite_slash_command)@classmethoddef _detect_owner_command(@@ -1795,24 +1291,13 @@ class OwnerCommandMiddleware(InboundMiddleware):chat_type: str,from_account: str,) -> Tuple[Optional[str], Optional[str], bool]:- """Identify allowlisted slash commands and determine sender identity.-- Returns (cmd, cmd_line, is_owner):- - (None, None, False): Not an allowlisted command- - (cmd, cmd_line, True): Owner match- - (cmd, cmd_line, False): Allowlisted command but sender is not owner- """+ """→ (cmd, cmd_line, is_owner); (None, None, False) when not an allowlisted command."""if chat_type != "group" or not cls.ALLOWLIST:return None, None, False-# Extract TIMTextElem: only do command recognition with exactly one text segment- text_elems = [- e for e in (msg_body or [])- if e.get("msg_type") == "TIMTextElem"- ]+ text_elems = [e for e in (msg_body or []) if e.get("msg_type") == "TIMTextElem"]if len(text_elems) != 1:return None, None, False-text = (text_elems[0].get("msg_content") or {}).get("text", "")cmd_line = cls._rewrite_slash_command(text)if not cmd_line.startswith("/"):@@ -1820,11 +1305,8 @@ class OwnerCommandMiddleware(InboundMiddleware):cmd = cmd_line.split(maxsplit=1)[0].lower()if cmd not in cls.ALLOWLIST:return None, None, False-- # Sender identity check: bot owner <-> push.from_account == push.bot_owner_id.- # The allowlisted commands (/approve, /deny, /stop, /reset, ...) are- # privileged — leaking them to non-owners lets any group member approve- # a dangerous tool call, kill the owner's task, or wipe session state.+ # Owner ⇔ push.from_account == push.bot_owner_id. These commands are privileged+ # (/approve, /stop, /reset…) — a non-owner must never be able to run them.owner_id = str((push or {}).get("bot_owner_id") or "").strip()is_owner = bool(owner_id) and owner_id == from_accountreturn cmd, cmd_line, is_owner@@ -1838,7 +1320,6 @@ class OwnerCommandMiddleware(InboundMiddleware):from_account=ctx.from_account,)if matched_cmd and not is_owner:- # Non-owner tried an owner-only command — reject and stoplogger.info("[%s] Reject non-owner slash command: chat=%s from=%s cmd=%s",adapter.name, ctx.chat_id, ctx.from_account, matched_cmd,@@ -1848,7 +1329,6 @@ class OwnerCommandMiddleware(InboundMiddleware):name=f"yuanbao-owner-cmd-denial-{matched_cmd}",))return # Stop pipeline-if matched_cmd and is_owner and cmd_line:logger.info("[%s] Bot owner slash command: chat=%s from=%s cmd=%s",@@ -1878,56 +1358,30 @@ class BuildSourceMiddleware(InboundMiddleware):class GroupAtGuardMiddleware(InboundMiddleware):- """In group chat, observe non-@bot messages; only reply on @Bot.-- Owner commands skip @Bot detection (owner doesn't need to @Bot).- """+ """Group chat: observe non-@bot messages into the transcript; only @Bot (or owner commands) proceed."""name = "group-at-guard"@staticmethod- def _is_at_bot(msg_body: list, bot_id: Optional[str]) -> bool:- """Detect whether the message @Bot.-- AT element format: TIMCustomElem, msg_content.data is a JSON string:- {"elem_type": 1002, "text": "@xxx", "user_id": "<botId>"}- Considered @Bot when elem_type == 1002 and user_id == bot_id.- """+ def _iter_bot_mentions(msg_body: list, bot_id: Optional[str]) -> Iterator[dict]:+ """Yield @bot elems: TIMCustomElem whose data JSON has elem_type 1002 and user_id == bot_id."""if not bot_id:- return False- for elem in msg_body:- if elem.get("msg_type") != "TIMCustomElem":- continue- data_str = (elem.get("msg_content") or {}).get("data", "")- if not data_str:- continue- try:- custom = json.loads(data_str)- except (json.JSONDecodeError, TypeError):- continue+ return+ for custom, _content in _iter_custom_elems(msg_body):if custom.get("elem_type") == 1002 and custom.get("user_id") == bot_id:- return True- return False+ yield custom- @staticmethod- def _extract_bot_mention_text(msg_body: list, bot_id: Optional[str]) -> str:- """Extract the display text used to @-mention this bot (e.g. ``@yuanbao-bot``)."""- if not bot_id:- return ""- for elem in msg_body:- if elem.get("msg_type") != "TIMCustomElem":- continue- data_str = (elem.get("msg_content") or {}).get("data", "")- if not data_str:- continue- try:- custom = json.loads(data_str)- except (json.JSONDecodeError, TypeError):- continue- if custom.get("elem_type") == 1002 and custom.get("user_id") == bot_id:- mention_text = str(custom.get("text") or "").strip()- if mention_text:- return mention_text+ @classmethod+ def _is_at_bot(cls, msg_body: list, bot_id: Optional[str]) -> bool:+ return any(True for _ in cls._iter_bot_mentions(msg_body, bot_id))++ @classmethod+ def _extract_bot_mention_text(cls, msg_body: list, bot_id: Optional[str]) -> str:+ """Display text used to @-mention this bot (e.g. ``@yuanbao-bot``), or ""."""+ for custom in cls._iter_bot_mentions(msg_body, bot_id):+ mention_text = str(custom.get("text") or "").strip()+ if mention_text:+ return mention_textreturn ""@staticmethod@@ -1953,13 +1407,8 @@ class GroupAtGuardMiddleware(InboundMiddleware):msg_id: Optional[str] = None,forwarded_records: Optional[dict] = None,) -> None:- """Write a group message into the session transcript without triggering the agent.-- This allows the model to see the full group conversation when it is- eventually invoked via @bot. Messages are stored with ``role: "user"``- in the format ``[nickname|user_id]\\n<content>`` so the model- can distinguish participants and their user ids.- """+ """Record a group message as ``role: user`` ``[nickname|user_id]\\n<content>`` without+ invoking the agent, so later @bot turns see the full conversation."""store = getattr(adapter, "_session_store", None)if not store:return@@ -1982,10 +1431,7 @@ class GroupAtGuardMiddleware(InboundMiddleware):}if msg_id:entry["message_id"] = msg_id- store.append_to_transcript(- session_entry.session_id,- entry,- )+ store.append_to_transcript(session_entry.session_id, entry)except Exception as exc:logger.warning("[%s] Failed to observe group message: %s", adapter.name, exc)@@ -2007,17 +1453,9 @@ class GroupAtGuardMiddleware(InboundMiddleware):class GroupAttributionMiddleware(InboundMiddleware):- """Tag group @bot messages with [nickname|user_id] attribution and channel_prompt.-- For group messages that pass the @bot guard (i.e. the bot is mentioned),- this middleware:- - Builds a per-turn channel_prompt so the model knows its identity and- the attribution scheme.- - Rewrites ctx.raw_text to ``[nickname|user_id]\\n<content>`` to match- the observed-history format.- - Suppresses the runner's default ``[user_name]`` shared-thread prefix- by clearing ``source.user_name``.- """+ """Group @bot turns: build channel_prompt, rewrite raw_text to ``[nickname|user_id]\\n<content>``+ (matches observed-history format) and clear ``source.user_name`` to suppress the runner's+ ``[user_name]`` prefix."""name = "group-attribution"@@ -2030,21 +1468,25 @@ class GroupAttributionMiddleware(InboundMiddleware):user_id_label = ctx.from_account or "unknown"nickname_label = ctx.sender_nickname or ctx.from_account or "unknown"ctx.raw_text = f"[{nickname_label}|{user_id_label}]\n{ctx.raw_text}"- # Suppress runner's default ``[user_name]`` shared-thread prefix so- # the text the model sees matches the observed-history format.if ctx.source is not None:ctx.source = dataclasses.replace(ctx.source, user_name=None)await next_fn()class YuanbaoMessageType(Enum):- """Yuanbao-local message subtypes; coerced back to :class:`MessageType`- before leaving the adapter (see :class:`DispatchMiddleware`)."""+ """Yuanbao-local subtypes; coerced back to MessageType in DispatchMiddleware."""- # WeChat forwarded chat records (TIMCustomElem, elem_type 1009).CHAT_RECORD = "chat_record"+_ELEM_MESSAGE_TYPES = {+ "TIMImageElem": MessageType.PHOTO,+ "TIMSoundElem": MessageType.VOICE,+ "TIMVideoFileElem": MessageType.VIDEO,+ "TIMFileElem": MessageType.DOCUMENT,+}++class ClassifyMessageTypeMiddleware(InboundMiddleware):"""Determine MessageType from text content and msg_body elements."""@@ -2052,23 +1494,14 @@ class ClassifyMessageTypeMiddleware(InboundMiddleware):@staticmethoddef _classify(text: str, msg_body: list):- """Classify message type based on text and msg_body.-- Returns a base :class:`MessageType`, or a yuanbao-local- :class:`YuanbaoMessageType` for platform-specific subtypes.- """+ """MessageType (or yuanbao-local YuanbaoMessageType) from text and msg_body."""if text.startswith("/"):return MessageType.COMMANDfor elem in msg_body:etype = elem.get("msg_type", "")- if etype == "TIMImageElem":- return MessageType.PHOTO- if etype == "TIMSoundElem":- return MessageType.VOICE- if etype == "TIMVideoFileElem":- return MessageType.VIDEO- if etype == "TIMFileElem":- return MessageType.DOCUMENT+ mapped = _ELEM_MESSAGE_TYPES.get(etype)+ if mapped is not None:+ return mappedif etype == "TIMCustomElem":data_str = (elem.get("msg_content") or {}).get("data", "")try:@@ -2090,37 +1523,27 @@ class QuoteContextMiddleware(InboundMiddleware):name = "quote-context"def _extract_quote_context(self, cloud_custom_data: str) -> Tuple[Optional[str], Optional[str]]:- """Extract quote text context, mapping to MessageEvent.reply_to_*.- """+ """(quote_id, quote_text) from cloud_custom_data → MessageEvent.reply_to_*."""if not cloud_custom_data:return None, Nonetry:parsed = json.loads(cloud_custom_data)except (json.JSONDecodeError, TypeError):return None, None-quote = parsed.get("quote") if isinstance(parsed, dict) else Noneif not isinstance(quote, dict):return None, None-quote_id = str(quote.get("id") or "").strip() or Nonedesc = str(quote.get("desc") or "").strip()sender = str(quote.get("sender_nickname") or quote.get("sender_id") or "").strip()quote_text = (f"{sender}: {desc}" if sender else desc) if desc else None-return quote_id, quote_textasync def _extract_media_refs_from_transcript(self, ctx: InboundContext) -> List[Tuple[str, str, str]]:- """Look up the quoted message in the transcript history and return any- ``[kind|ybres:RID]`` anchors found in its content as- ``(rid, kind, filename)`` tuples.-- Returns ``[]`` when ``ctx.reply_to_message_id`` is unset, when the- transcript store / source is unavailable, or when the quoted message- carries no resolvable media anchors.- """+ """``(rid, kind, filename)`` for ybres anchors in the quoted transcript message; [] when+ there is no reply_to id, no store/source, or no resolvable anchors."""if ctx.reply_to_message_id is None:return []adapter = ctx.adapter@@ -2137,13 +1560,7 @@ class QuoteContextMiddleware(InboundMiddleware):continue_content = msg.get("content", "")if isinstance(_content, str) and "|ybres:" in _content:- for m in _YB_RES_REF_RE.finditer(_content):- head = m.group(1)- rid = m.group(2)- kind, _, filename = head.partition(":")- kind = kind.strip()- if kind in _RESOLVABLE_MEDIA_KINDS:- media_refs.append((rid, kind, filename.strip()))+ media_refs.extend(_iter_ybres_refs(_YB_RES_REF_RE.finditer(_content)))breakexcept Exception as exc:logger.warning(@@ -2159,22 +1576,10 @@ class QuoteContextMiddleware(InboundMiddleware):class ForwardedRecordsParseMiddleware(InboundMiddleware):- """Deep-parse WeChat forwarded chat records (elem_type 1009) for dispatch.-- Activates when a full ``ForwardMsgData`` dict is available on the current- turn, carried by the current message (``ctx.forwarded_records``).- Resolves media to ``[kind|ybres:RID]``- placeholders, appends downloadable refs to ``ctx.media_refs`` (for- :class:`MediaResolveMiddleware`), and rewrites ``ctx.raw_text``.-- Group @bot turns *without* a forward on the current message rely on the- eagerly-rendered summaries that :class:`GroupAtGuardMiddleware` writes to- the transcript at observe time — there is no run-time summary fallback- here.-- On any failure the middleware leaves ``ctx.raw_text`` untouched- (graceful degradation, design §2.8).- """+ """Deep-parse WeChat forwarded chat records (elem_type 1009) on ``ctx.forwarded_records``:+ render media as ``[kind|ybres:RID]``, append refs to ``ctx.media_refs`` and rewrite raw_text.+ No run-time fallback for earlier forwards — GroupAtGuard already rendered summaries at observe+ time. On any failure raw_text is left untouched."""name = "forwarded-records-parse"@@ -2184,16 +1589,12 @@ class ForwardedRecordsParseMiddleware(InboundMiddleware):await self._send_loading_heartbeat(ctx)ctx.raw_text = self.build_forward_text(ctx.forwarded_records, ctx=ctx, is_dispatch=True)except Exception as exc:- # Degrade gracefully: leave ctx.raw_text as-is.logger.warning("[%s] forwarded-records deep parse failed: %s",getattr(ctx.adapter, "name", "yuanbao"), exc,)-await next_fn()- # -- Heartbeat ----------------------------------------------------------@staticmethodasync def _send_loading_heartbeat(ctx: InboundContext) -> None:"""Best-effort RUNNING heartbeat so the user sees a loading bubble."""@@ -2204,32 +1605,22 @@ class ForwardedRecordsParseMiddleware(InboundMiddleware):except Exception:pass- # -- Record rendering helpers ------------------------------------------@classmethoddef _media_marker(cls, media: dict, plain_text: str = "",) -> Tuple[str, Optional[Dict[str, str]]]:- """Render one ``msgContent.multimedia`` entry as a textual marker.-- Returns ``(marker, ref)``. Downloadable media emits a- ``[kind|ybres:RID]`` marker and a ``ctx.media_refs`` ref dict when a- usable RID/URL is present; otherwise a plain ``[kind] name`` marker- and ``ref=None``.- """+ """One ``multimedia`` entry → ``(marker, ref)``: ``[kind|ybres:RID]`` + media_refs dict when a+ RID/URL is usable, else a plain ``[kind] name`` marker and ``ref=None``."""media_type = (media.get("type", "") or media.get("doc_type", "")).strip().lower()url = str(media.get("url") or "").strip()media_id = str(media.get("media_id") or "").strip()file_name = str(media.get("file_name") or "").strip()- # media_id is directly usable as a ybres RID (design §2.10.9);- # fall back to parsing the resourceId out of the URL.+ # media_id is directly usable as a ybres RID; else parse resourceId from the URL.rid = media_id or ExtractContentMiddleware._parse_resource_id(url)-if media_type == "image":if url and rid:return f"[image|ybres:{rid}] {file_name}".rstrip(), {"kind": "image", "url": url}return f"[image] {file_name or plain_text}".rstrip(), None-if media_type in ("file", "document", "code"):if url and rid:ref: Dict[str, str] = {"kind": "file", "url": url}@@ -2237,44 +1628,30 @@ class ForwardedRecordsParseMiddleware(InboundMiddleware):ref["name"] = file_namereturn f"[file|ybres:{rid}] {file_name}".rstrip(), refreturn f"[file] {file_name}".rstrip(), None-- if media_type == "url":- # Link share (e.g. WeChat article) — keep URL for the agent.+ if media_type == "url": # link share (e.g. WeChat article) — keep URL for the agentlink_title = file_name or str(media.get("title") or "")return f"[link] {link_title} {url}".rstrip(), None-if media_type == "video":if url and rid:return f"[video|ybres:{rid}] {file_name}".rstrip(), {"kind": "video", "url": url}return f"[video] {file_name or url}".rstrip(), None-return f"[{media_type or 'media'}] {url or file_name}".rstrip(), None- # Per-record combined-text cap; record count is NOT capped (design §2.10.3).- FORWARD_MSG_TEXT_MAX_CHARS = 1000+ FORWARD_MSG_TEXT_MAX_CHARS = 1000 # per-record text cap; record count is NOT capped@classmethoddef _walk_forward_msgs(cls,forward_data: dict,) -> Iterator[Tuple[str, str, List[Dict[str, str]]]]:- """Walk ``ForwardMsgData['msg']`` and yield ``(sender, body, refs)``.-- Per-record dispatch over ``msgContent`` (text / multimedia / nested- forward / fallback); ``body`` is capped at- :attr:`FORWARD_MSG_TEXT_MAX_CHARS`. Media goes through- :meth:`_media_marker`, always building full ``[kind|ybres:RID]``- markers; ``refs`` holds that record's downloadable ``ctx.media_refs``- entries in textual order — the order PatchAnchorsMiddleware relies on- (design §2.10.6). Headers / footers are the caller's job.- """+ """Yield ``(sender, body, refs)`` per ``ForwardMsgData['msg']`` record; body capped at+ FORWARD_MSG_TEXT_MAX_CHARS. ``refs`` keeps textual order — PatchAnchorsMiddleware relies on it."""for msg in (forward_data.get("msg") if isinstance(forward_data, dict) else None) or []:if not isinstance(msg, dict):continuesender = msg.get("sender", "")plain_text = msg.get("plainText", "")msg_contents = msg.get("msgContent", []) or []-refs: List[Dict[str, str]] = []if not msg_contents:rendered = plain_text@@ -2283,43 +1660,32 @@ class ForwardedRecordsParseMiddleware(InboundMiddleware):for mc in msg_contents:if not isinstance(mc, dict):continue- mc_type = mc.get("type", 0) # EnumMsgContentType- if mc_type == 1: # TEXT+ mc_type = mc.get("type", 0) # EnumMsgContentType: 1 TEXT, 2 MULTIMEDIA, 3 nested FORWARD+ if mc_type == 1:parts.append(mc.get("text", ""))- elif mc_type == 2: # MULTIMEDIA+ elif mc_type == 2:for media in mc.get("multimedia", []) or []:if isinstance(media, dict):- marker, ref = cls._media_marker(- media, plain_text,- )+ marker, ref = cls._media_marker(media, plain_text)parts.append(marker)if ref is not None:refs.append(ref)- elif mc_type == 3: # nested FORWARD_MSG (design §2.10.10)+ elif mc_type == 3:parts.append("[嵌套聊天记录]")else:if plain_text:parts.append(plain_text)rendered = " ".join(p for p in parts if p) or plain_text-if len(rendered) > cls.FORWARD_MSG_TEXT_MAX_CHARS:rendered = rendered[: cls.FORWARD_MSG_TEXT_MAX_CHARS] + "…(已截断)"yield sender, rendered, refs- # -- Prompt builders ----------------------------------------------------@classmethoddef build_forward_text(cls, forward_data: dict, *, ctx: InboundContext, is_dispatch: bool,) -> str:- """Render ``ForwardMsgData`` into forward text.-- Body lines are ``发送人:正文`` with full ``[kind|ybres:RID]`` media- markers preserved. When ``is_dispatch`` is true, refs are appended to- ``ctx.media_refs`` for downstream resolution and a ``用户附言:- {ctx.raw_text}`` footer is added; observed callers skip both since- no later middleware runs.- """+ """Render ``ForwardMsgData`` as ``发送人:正文`` lines with media markers. When ``is_dispatch``,+ refs go to ``ctx.media_refs`` and a ``用户附言:`` footer is added (observe-time callers skip both)."""nickname = ctx.sender_nickname or "用户"lines = [f"当前用户的昵称为{nickname}", "以下为用户的聊天记录"]for sender, body, refs in cls._walk_forward_msgs(forward_data):@@ -2413,14 +1779,12 @@ class MediaResolveMiddleware(InboundMiddleware):resource_id = resource_id.strip()if not resource_id:raise RuntimeError("missing resource_id")-token_data = await adapter._get_cached_token()token = str(token_data.get("token") or "").strip()source = str(token_data.get("source") or "web").strip() or "web"bot_id = str(token_data.get("bot_id") or adapter._bot_id or adapter._app_key).strip()if not token or not bot_id:raise RuntimeError("missing token or bot_id for resource download")-api_url = f"{adapter._api_domain}/api/resource/v1/download"headers = {"Content-Type": "application/json",@@ -2428,7 +1792,6 @@ class MediaResolveMiddleware(InboundMiddleware):"X-Token": token,"X-Source": source,}-async with httpx.AsyncClient(timeout=15.0, follow_redirects=True) as client:for attempt in range(2):resp = await client.get(api_url, params={"resourceId": resource_id}, headers=headers)@@ -2446,7 +1809,6 @@ class MediaResolveMiddleware(InboundMiddleware):headers["X-Token"] = tokenheaders["X-Source"] = sourcecontinue-resp.raise_for_status()payload = resp.json()code = payload.get("code")@@ -2459,7 +1821,6 @@ class MediaResolveMiddleware(InboundMiddleware):if real_url:return real_urlraise RuntimeError("resource/v1/download missing url/realUrl")-raise RuntimeError("resource/v1/download did not return a URL")@staticmethod@@ -2475,13 +1836,11 @@ class MediaResolveMiddleware(InboundMiddleware):parsed = urllib.parse.urlparse(url)except Exception:return url-query = urllib.parse.parse_qs(parsed.query)resource_ids = query.get("resourceId") or query.get("resourceid") or []resource_id = str(resource_ids[0]).strip() if resource_ids else ""if not resource_id:return url-try:return await MediaResolveMiddleware._fetch_resource_url(adapter, resource_id)except Exception:@@ -2507,7 +1866,6 @@ class MediaResolveMiddleware(InboundMiddleware):adapter.name, resource_id, hit[0],)return hit-try:file_bytes, content_type = await media_download_url(fetch_url, max_size_mb=adapter.MEDIA_MAX_SIZE_MB,@@ -2518,7 +1876,6 @@ class MediaResolveMiddleware(InboundMiddleware):adapter.name, kind, log_tag, exc,)return None-if kind == "image":ext = cls._guess_image_ext_from_url(fetch_url)try:@@ -2534,7 +1891,6 @@ class MediaResolveMiddleware(InboundMiddleware):mime = content_type if content_type.startswith("image/") else "image/jpeg"cls._put_cached_resource(resource_id, local_path, mime)return local_path, mime-if kind == "video":# Yuanbao video resources carry no reliable extension; default to mp4.local_path = cache_video_from_bytes(file_bytes)@@ -2543,7 +1899,6 @@ class MediaResolveMiddleware(InboundMiddleware):)cls._put_cached_resource(resource_id, local_path, mime)return local_path, mime-# kind == "file"if not file_name:parsed = urllib.parse.urlparse(fetch_url)@@ -2551,10 +1906,7 @@ class MediaResolveMiddleware(InboundMiddleware):try:local_path = cache_document_from_bytes(file_bytes, file_name)except Exception as exc:- logger.warning(- "[%s] inbound file cache failed: %s err=%s",- adapter.name, log_tag, exc,- )+ logger.warning("[%s] inbound file cache failed: %s err=%s", adapter.name, log_tag, exc)return Nonemime = guess_mime_type(file_name) or content_type or "application/octet-stream"cls._put_cached_resource(resource_id, local_path, mime)@@ -2587,69 +1939,61 @@ class MediaResolveMiddleware(InboundMiddleware):if rid and cls._append_cached_resource(adapter, rid, media_urls, media_types):continueactive.append((kind, url, filename, rid or ""))-if not active:return media_urls, media_types+ async def _resolve_one(kind: str, url: str, filename: str, rid: str) -> Optional[Tuple[str, str]]:+ try:+ fetch_url = await cls._resolve_download_url(adapter, url)+ except Exception as exc:+ logger.warning(+ "[%s] inbound media resolve failed: kind=%s url=%s err=%s",+ adapter.name, kind, url, exc,+ )+ return None+ return await cls._download_and_cache(+ adapter, fetch_url=fetch_url, kind=kind, file_name=filename or None,+ log_tag=f"placeholder_url={url[:80]}", resource_id=rid,+ )++ def _crash_msg(item, result):+ kind, url, _filename, _rid = item+ return "[%s] inbound media resolve crashed: kind=%s url=%s err=%s", (adapter.name, kind, url[:80], result)+ await cls._gather_resolve(adapter, active, _resolve_one, _crash_msg, "media", media_urls, media_types)+ return media_urls, media_types++ @staticmethod+ async def _gather_resolve(adapter, active, resolve_one, crash_msg, scope, out_paths, out_mimes) -> None:+ """Run *resolve_one(*item)* over *active* under bounded concurrency; append successes in input order.++ ``return_exceptions=True`` isolates per-item failures; a batch summary log line with+ stable fields (concurrency vs elapsed_ms) is emitted for offline aggregation.+ """semaphore = asyncio.Semaphore(adapter.media_resolve_concurrency)- async def _resolve_one(- kind: str, url: str, filename: str, rid: str,- ) -> Optional[Tuple[str, str]]:+ async def _guarded(item):async with semaphore:- try:- fetch_url = await cls._resolve_download_url(adapter, url)- except Exception as exc:- logger.warning(- "[%s] inbound media resolve failed: kind=%s url=%s err=%s",- adapter.name, kind, url, exc,- )- return None- return await cls._download_and_cache(- adapter,- fetch_url=fetch_url,- kind=kind,- file_name=filename or None,- log_tag=f"placeholder_url={url[:80]}",- resource_id=rid,- )-+ return await resolve_one(*item)_t0 = time.monotonic()- results = await asyncio.gather(- *(_resolve_one(kind, url, filename, rid)- for kind, url, filename, rid in active),- return_exceptions=True,- )+ results = await asyncio.gather(*(_guarded(item) for item in active), return_exceptions=True)_elapsed_ms = int((time.monotonic() - _t0) * 1000)-_failed = 0- for (kind, url, _filename, _rid), result in zip(active, results):+ for item, result in zip(active, results):if isinstance(result, BaseException):- logger.warning(- "[%s] inbound media resolve crashed: kind=%s url=%s err=%s",- adapter.name, kind, url[:80], result,- )+ fmt, args = crash_msg(item, result)+ logger.warning(fmt, *args)_failed += 1continueif result is None:_failed += 1continue- local_path, mime = result- media_urls.append(local_path)- media_types.append(mime)-- # Batch summary: keep fields stable for offline aggregation- # (concurrency vs elapsed_ms is the core knob-tuning view).+ path, mime = result+ out_paths.append(path)+ out_mimes.append(mime)logger.info(- "[%s] media resolve batch: scope=media concurrency=%d total=%d ok=%d failed=%d elapsed_ms=%d",- adapter.name,- adapter.media_resolve_concurrency,- len(active),- len(media_urls),- _failed,- _elapsed_ms,+ "[%s] media resolve batch: scope=%s concurrency=%d total=%d ok=%d failed=%d elapsed_ms=%d",+ adapter.name, scope, adapter.media_resolve_concurrency, len(active), len(out_paths), _failed, _elapsed_ms,)- return media_urls, media_types@classmethodasync def _resolve_ybres_refs(@@ -2659,14 +2003,8 @@ class MediaResolveMiddleware(InboundMiddleware):*,log_prefix: str,) -> Tuple[List[str], List[str]]:- """Resolve ``(rid, kind, filename)`` ybres tuples to local paths.-- Runs with bounded concurrency (``adapter.media_resolve_concurrency``)- so cold-start turns with many anchors don't pay ``N × (RPC + download)``- sequentially. Output order matches input; per-rid failures are isolated.- """- # Pre-filter resolvable kinds, preserving input order.- # Cache-hit refs are served immediately and excluded from the gather.+ """Resolve ``(rid, kind, filename)`` ybres tuples to local paths (bounded concurrency,+ input order preserved, per-rid failures isolated). Cache hits are served without a fetch."""media_paths: List[str] = []mimes: List[str] = []active: List[Tuple[str, str, str]] = []@@ -2679,67 +2017,28 @@ class MediaResolveMiddleware(InboundMiddleware):if not active:return media_paths, mimes- semaphore = asyncio.Semaphore(adapter.media_resolve_concurrency)-async def _resolve_one(rid: str, kind: str, filename: str) -> Optional[Tuple[str, str]]:- async with semaphore:- try:- fresh_url = await cls._fetch_resource_url(adapter, rid)- except Exception as exc:- logger.warning(- "[%s] %s resolve failed: rid=%s kind=%s err=%s",- adapter.name, log_prefix, rid, kind, exc,- )- return None- return await cls._download_and_cache(- adapter,- fetch_url=fresh_url,- kind=kind,- file_name=filename or None,- log_tag=f"{log_prefix} rid={rid}",- resource_id=rid,- )-- # return_exceptions=True isolates per-coroutine failures.- _t0 = time.monotonic()- results = await asyncio.gather(- *(_resolve_one(rid, kind, filename) for rid, kind, filename in active),- return_exceptions=True,- )- _elapsed_ms = int((time.monotonic() - _t0) * 1000)-- _failed = 0- for (rid, kind, filename), result in zip(active, results):- if isinstance(result, BaseException):+ try:+ fresh_url = await cls._fetch_resource_url(adapter, rid)+ except Exception as exc:logger.warning(- "[%s] %s resolve crashed: rid=%s kind=%s err=%s",- adapter.name, log_prefix, rid, kind, result,+ "[%s] %s resolve failed: rid=%s kind=%s err=%s",+ adapter.name, log_prefix, rid, kind, exc,)- _failed += 1- continue- if result is None:- _failed += 1- continue- path, mime = result- media_paths.append(path)- mimes.append(mime)+ return None+ return await cls._download_and_cache(+ adapter, fetch_url=fresh_url, kind=kind, file_name=filename or None,+ log_tag=f"{log_prefix} rid={rid}", resource_id=rid,+ )- # Batch summary: stable fields for offline aggregation.- logger.info(- "[%s] media resolve batch: scope=ybres concurrency=%d total=%d ok=%d failed=%d elapsed_ms=%d",- adapter.name,- adapter.media_resolve_concurrency,- len(active),- len(media_paths),- _failed,- _elapsed_ms,- )+ def _crash_msg(item, result):+ rid, kind, _filename = item+ return "[%s] %s resolve crashed: rid=%s kind=%s err=%s", (adapter.name, log_prefix, rid, kind, result)+ await cls._gather_resolve(adapter, active, _resolve_one, _crash_msg, "ybres", media_paths, mimes)return media_paths, mimes@classmethod- async def _collect_observed_media(- cls, adapter, source,- ) -> Tuple[List[str], List[str]]:+ async def _collect_observed_media(cls, adapter, source) -> Tuple[List[str], List[str]]:"""Resolve recent observed image/file anchors from transcript into ``(local_paths, mimes)``."""store = getattr(adapter, "_session_store", None)if not store:@@ -2748,21 +2047,12 @@ class MediaResolveMiddleware(InboundMiddleware):session_entry = store.get_or_create_session(source)history = store.load_transcript(session_entry.session_id)except Exception as exc:- logger.warning(- "[%s] Observed-media hydration setup failed: %s",- adapter.name, exc,- )+ logger.warning("[%s] Observed-media hydration setup failed: %s", adapter.name, exc)return [], []if not history:return [], []-- # Walk the most recent LOOKBACK messages newest→oldest so that when we- # hit the per-turn resolve cap we keep the *latest* media references,- # not the oldest ones in the window. Within a single message, also- # iterate matches in reverse so the last-added image wins on ties.- # Final ``order`` is reversed back to chronological (old→new) before- # handing off to ``_resolve_ybres_refs`` so downstream prompt insertion- # preserves natural reading order.+ # Walk newest→oldest (matches within a message too) so the per-turn cap keeps the+ # *latest* refs; ``order`` is reversed back to chronological before resolving.window = history[-OBSERVED_MEDIA_BACKFILL_LOOKBACK:]order: List[Tuple[str, str, str]] = [] # (rid, kind, filename)seen: set = set()@@ -2770,59 +2060,32 @@ class MediaResolveMiddleware(InboundMiddleware):content = msg.get("content")if not isinstance(content, str) or "|ybres:" not in content:continue- matches = list(_YB_RES_REF_RE.finditer(content))- for m in reversed(matches):- head = m.group(1) # "image" | "file:<name>" | "voice" | "video"- rid = m.group(2)- kind, _, filename = head.partition(":")- kind = kind.strip()- if kind not in _RESOLVABLE_MEDIA_KINDS:- continue+ for rid, kind, filename in _iter_ybres_refs(reversed(list(_YB_RES_REF_RE.finditer(content)))):if rid in seen:continueseen.add(rid)- order.append((rid, kind, filename.strip()))+ order.append((rid, kind, filename))if len(order) >= OBSERVED_MEDIA_BACKFILL_MAX_RESOLVE_PER_TURN:breakif len(order) >= OBSERVED_MEDIA_BACKFILL_MAX_RESOLVE_PER_TURN:break-- # Restore chronological order (oldest→newest) for downstream resolution.order.reverse()-if not order:return [], []-- return await cls._resolve_ybres_refs(- adapter, order, log_prefix="observed-media",- )+ return await cls._resolve_ybres_refs(adapter, order, log_prefix="observed-media")@classmethodasync def _resolve_quote_media(cls, adapter, quote_media_refs: List[Tuple[str, str, str]],) -> Tuple[List[str], List[str]]:- """Resolve media anchors carried by the quoted message.-- ``quote_media_refs`` is a list of ``(rid, kind, filename)`` tuples- produced by :class:`QuoteContextMiddleware` from the transcript.- """- return await cls._resolve_ybres_refs(- adapter, quote_media_refs, log_prefix="quote",- )+ """Resolve ``(rid, kind, filename)`` anchors of the quoted message (from QuoteContextMiddleware)."""+ return await cls._resolve_ybres_refs(adapter, quote_media_refs, log_prefix="quote")@staticmethoddef _collect_quote_local_media(ctx: InboundContext) -> Tuple[List[str], List[str]]:- """Private-chat fallback for recovering already-local quoted media.-- Only already-local media is handled here: by the time a turn is cached,- ``PatchAnchorsMiddleware`` has rewritten resolved ``|ybres:`` anchors to- ``[image: /path]`` / ``[file: name → /path]``. Unresolved anchors are an- original-turn resolution failure and belong to that turn's handling, not- this quote fallback — so no re-download happens here.-- Returns ``(local_paths, mimes)`` for media already downloaded to the- local cache on its original turn, ready to inject as-is.- """+ """DM quote fallback: ``(local_paths, mimes)`` for media PatchAnchorsMiddleware already+ rewrote to ``[image: /path]`` / ``[file: name → /path]`` on the original turn. Unresolved+ anchors were that turn's failure — no re-download here."""paths: List[str] = []mimes: List[str] = []rid_key = ctx.reply_to_message_id@@ -2834,8 +2097,6 @@ class MediaResolveMiddleware(InboundMiddleware):text = cache.get(rid_key)if not isinstance(text, str) or not text:return paths, mimes-- # Already-local media paths written by PatchAnchorsMiddleware.seen: set = set()for m in _YB_LOCAL_MEDIA_RE.finditer(text):kind = (m.group(1) or "").strip().lower()@@ -2850,16 +2111,12 @@ class MediaResolveMiddleware(InboundMiddleware):)paths.append(path)mimes.append(mime)-return paths, mimesasync def handle(self, ctx: InboundContext, next_fn) -> None:- # NOTE: Reaching this middleware in a group chat implies the message has- # @-mentioned the bot (or is an owner command). GroupAtGuardMiddleware- # short-circuits non-@bot group messages earlier in the pipeline, so we- # don't need to re-check @bot status here before downloading media.+ # In groups only @bot / owner-command turns reach here (GroupAtGuard short-circuits the+ # rest), so media download and observed-media hydration need no @bot re-check.adapter = ctx.adapter-urls: List[str] = []types: List[str] = []seen: set = set()@@ -2872,28 +2129,19 @@ class MediaResolveMiddleware(InboundMiddleware):seen.add(u)urls.append(u)types.append(m)-# 1) Media carried by the current message itself.own_pairs = await self._resolve_media_urls(adapter, ctx.media_refs)own_count = sum(1 for u in own_pairs[0] if u)_add_unique_pairs(own_pairs)-- # 2) Second source — quoted media takes priority; otherwise fall back- # to observed-media backfill in groups only (DMs already had their- # media resolved on the turn it was sent).+ # 2) Quoted media takes priority; else observed-media backfill in groups only (DM media+ # was already resolved on its own turn).if ctx.reply_to_message_id is not None:if ctx.quote_media_refs:_add_unique_pairs(await self._resolve_quote_media(adapter, ctx.quote_media_refs))else:- # DM quote fallback: no transcript message_id match (DM user rows- # carry no platform message_id), so recover already-local media- # from the adapter msg cache. Patched on its original turn — no- # re-download needed, inject as-is.+ # DM rows carry no platform message_id → recover already-local media from the msg cache._add_unique_pairs(self._collect_quote_local_media(ctx))elif ctx.chat_type == "group":- # Group chats: only @-bot turns reach this middleware- # (see GroupAtGuardMiddleware note at top of handle()),- # so unconditional observed-media hydration is safe here.try:_add_unique_pairs(await self._collect_observed_media(adapter, ctx.source))except Exception as exc:@@ -2901,14 +2149,10 @@ class MediaResolveMiddleware(InboundMiddleware):"[%s] observed-image hydration raised, continuing anyway: %s",adapter.name, exc,)-ctx.media_urls = urlsctx.media_types = types-- # Re-check placeholder after media resolution.- # Use ``own_count`` (not ``len(urls)``) to preserve the original- # semantics: a placeholder text accompanied only by quote/observed- # media (i.e. no fresh attachment of its own) is still skippable.+ # Re-check placeholder using ``own_count``: placeholder text with only quote/observed+ # media (no fresh attachment of its own) is still skippable.if PlaceholderFilterMiddleware.is_skippable_placeholder(ctx.raw_text, own_count):logger.debug("[%s] Skip placeholder after media download: %r", adapter.name, ctx.raw_text)return # Stop pipeline@@ -2916,17 +2160,9 @@ class MediaResolveMiddleware(InboundMiddleware):class PatchAnchorsMiddleware(InboundMiddleware):- """Replace ``[kind|ybres:RID]`` anchors in ``ctx.raw_text`` with local paths.-- Runs after :class:`MediaResolveMiddleware` so that ``ctx.media_urls`` /- ``ctx.media_types`` are already populated with downloaded resources- (own media + quote media or group-observed media). The transcript- written downstream then records usable local paths for the model- instead of opaque ``ybres:`` references.-- Only resolved media (paths starting with ``/``) are substituted; any- anchor without a corresponding local resource is left untouched.- """+ """Replace ``[kind|ybres:RID]`` anchors in raw_text with the local paths MediaResolveMiddleware+ produced, so the transcript records usable paths. Only resolved media (paths starting with+ ``/``) are substituted; other anchors stay untouched."""name = "patch-anchors"@@ -2953,11 +2189,7 @@ class PatchAnchorsMiddleware(InboundMiddleware):replacement = f"[video: {u}]"else:continue- patched = (- patched[: anchor_match.start()]- + replacement- + patched[anchor_match.end():]- )+ patched = patched[: anchor_match.start()] + replacement + patched[anchor_match.end():]return patchedasync def handle(self, ctx: InboundContext, next_fn) -> None:@@ -2972,7 +2204,6 @@ class DispatchMiddleware(InboundMiddleware):async def handle(self, ctx: InboundContext, next_fn) -> None:adapter = ctx.adapter-_sk = build_session_key(ctx.source,group_sessions_per_user=adapter.config.extra.get("group_sessions_per_user", True),@@ -2985,9 +2216,7 @@ class DispatchMiddleware(InboundMiddleware):message_type=(MessageType.DOCUMENTif any(mt.startswith(("application/", "text/")) for mt in ctx.media_types)- # Coerce yuanbao-local subtypes (e.g. CHAT_RECORD) back to a- # base MessageType: chat records are deep-parsed into a text- # prompt, so TEXT is the right kind for downstream routing.+ # yuanbao-local subtypes (CHAT_RECORD) are deep-parsed into text → TEXT downstreamelse ctx.msg_type if isinstance(ctx.msg_type, MessageType)else MessageType.TEXT),@@ -3010,7 +2239,6 @@ class DispatchMiddleware(InboundMiddleware):for k in list(cache)[:len(cache) - 200]:del cache[k]await adapter.handle_message(event)-if ctx.chat_type == "group":is_new = _sk not in adapter._group_queuesqueue = adapter._group_queues.setdefault(_sk, asyncio.Queue())@@ -3020,22 +2248,18 @@ class DispatchMiddleware(InboundMiddleware):adapter.name, queue.qsize(), (_sk or "")[:50],)if is_new:- consumer = asyncio.create_task(- self._consume_group_queue(adapter, _sk),- name=f"yuanbao-group-consumer-{(_sk or '')[:30]}",- )- adapter._inbound_tasks.add(consumer)- consumer.add_done_callback(adapter._inbound_tasks.discard)+ self._track_inbound(adapter, self._consume_group_queue(adapter, _sk),+ f"yuanbao-group-consumer-{(_sk or '')[:30]}")else:- task = asyncio.create_task(- _dispatch_inbound_event(),- name=f"yuanbao-inbound-{ctx.msg_id or 'unknown'}",- )- adapter._inbound_tasks.add(task)- task.add_done_callback(adapter._inbound_tasks.discard)-+ self._track_inbound(adapter, _dispatch_inbound_event(), f"yuanbao-inbound-{ctx.msg_id or 'unknown'}")await next_fn()+ @staticmethod+ def _track_inbound(adapter, coro, name: str) -> None:+ task = asyncio.create_task(coro, name=name)+ adapter._inbound_tasks.add(task)+ task.add_done_callback(adapter._inbound_tasks.discard)+@staticmethodasync def _consume_group_queue(adapter: "YuanbaoAdapter", session_key: str) -> None:"""Drain the group queue one dispatch at a time, waiting for each to finish."""@@ -3064,13 +2288,8 @@ class DispatchMiddleware(InboundMiddleware):class InboundPipelineBuilder:- """Factory for building InboundPipeline instances.+ """Assembles the default Yuanbao inbound pipeline (order matters)."""- Separates pipeline assembly (business knowledge) from the pipeline engine- (InboundPipeline) so the engine stays generic and reusable.- """-- # Default middleware sequence for Yuanbao inbound message processing._DEFAULT_MIDDLEWARES: list[type] = [DecodeMiddleware,ExtractFieldsMiddleware,@@ -3102,16 +2321,9 @@ class InboundPipelineBuilder:pipeline.use(mw_cls())return pipeline+class ConnectionManager:- """Manages the WebSocket connection lifecycle for YuanbaoAdapter.-- Responsibilities:- - Opening and closing the WebSocket- - AUTH_BIND handshake- - Heartbeat (ping/pong) loop- - Receive loop (frame dispatch)- - Reconnect with exponential backoff- """+ """WebSocket lifecycle: open/close, AUTH_BIND, ping/pong heartbeat, receive loop, backoff reconnect."""def __init__(self, adapter: "YuanbaoAdapter") -> None:self._adapter = adapter@@ -3124,24 +2336,14 @@ class ConnectionManager:self._consecutive_hb_timeouts: int = 0self._reconnect_attempts: int = 0self._reconnecting: bool = False- # Debounce buffer for aggregating multi-part inbound messages- self._inbound_buffer: Dict[str, list] = {} # key -> [raw_data_frames, ...]- self._inbound_timers: Dict[str, asyncio.TimerHandle] = {} # key -> timer-- # -- Properties --------------------------------------------------------+ # Debounce buffer aggregating multi-part inbound messages: sender key -> frames / timer+ self._inbound_buffer: Dict[str, list] = {}+ self._inbound_timers: Dict[str, asyncio.TimerHandle] = {}@propertydef ws(self):return self._ws- @property- def connect_id(self) -> Optional[str]:- return self._connect_id-- @property- def reconnect_attempts(self) -> int:- return self._reconnect_attempts-@propertydef is_connected(self) -> bool:if self._ws is None:@@ -3156,95 +2358,44 @@ class ConnectionManager:return Falsereturn False- # -- Open / Close -------------------------------------------------------async def open(self) -> bool:- """Open WebSocket connection: sign-token → WS connect → AUTH_BIND → start loops.-- Returns True on success, False on failure.- """+ """sign-token → WS connect → AUTH_BIND → start loops. Returns True on success."""adapter = self._adapter-if not WEBSOCKETS_AVAILABLE:msg = "Yuanbao startup failed: 'websockets' package not installed"adapter._set_fatal_error("yuanbao_missing_dependency", msg, retryable=True)logger.warning("[%s] %s. Run: pip install websockets", adapter.name, msg)return False-if not adapter._app_key or not adapter._app_secret:- msg = (- "Yuanbao startup failed: "- "YUANBAO_APP_ID and YUANBAO_APP_SECRET are required"- )+ msg = "Yuanbao startup failed: YUANBAO_APP_ID and YUANBAO_APP_SECRET are required"adapter._set_fatal_error("yuanbao_missing_credentials", msg, retryable=False)logger.error("[%s] %s", adapter.name, msg)return False-- # Idempotency guard- if self._ws is not None:- try:- open_attr = getattr(self._ws, "open", None)- if open_attr is True or (callable(open_attr) and open_attr()):- logger.debug("[%s] Already connected, skipping connect()", adapter.name)- return True- except Exception:- pass-- # Acquire platform-scoped lock to prevent duplicate connections- if not adapter._acquire_platform_lock(- 'yuanbao-app-key', adapter._app_key, 'Yuanbao app key'- ):+ if self.is_connected:+ logger.debug("[%s] Already connected, skipping connect()", adapter.name)+ return True+ if not adapter._acquire_platform_lock('yuanbao-app-key', adapter._app_key, 'Yuanbao app key'):return False-try:- # Step 1: Get sign tokenlogger.info("[%s] Fetching sign token from %s", adapter.name, adapter._api_domain)token_data = await SignManager.get_token(adapter._app_key, adapter._app_secret, adapter._api_domain,route_env=adapter._route_env,)-- # Update bot_id if returned by sign-token API- if token_data.get("bot_id"):- adapter._bot_id = str(token_data["bot_id"])-- # Step 2: Open WebSocket connection (disable built-in ping/pong)+ self._apply_bot_id(token_data)logger.info("[%s] Connecting to %s", adapter.name, adapter._ws_url)- self._ws = await asyncio.wait_for(- websockets.connect( # type: ignore[attr-defined]- adapter._ws_url,- ping_interval=None,- ping_timeout=None,- close_timeout=5,- ),- timeout=CONNECT_TIMEOUT_SECONDS,- )-- # Step 3: Authenticate (AUTH_BIND + wait for BIND_ACK)- authed = await self._authenticate(token_data)- if not authed:- await self._cleanup_ws()+ if not await self._dial(token_data):return False-- # Step 4: Start background tasksself._reconnect_attempts = 0adapter._mark_connected()adapter._loop = asyncio.get_running_loop()- self._heartbeat_task = asyncio.create_task(- self._heartbeat_loop(), name=f"yuanbao-heartbeat-{self._connect_id}"- )- self._recv_task = asyncio.create_task(- self._receive_loop(), name=f"yuanbao-recv-{self._connect_id}"- )+ self._start_loops(cancel_existing=False)logger.info("[%s] Connected. connectId=%s botId=%s",adapter.name, self._connect_id, adapter._bot_id,)-YuanbaoAdapter.set_active(adapter)-return True-except asyncio.TimeoutError:logger.error("[%s] Connection timed out", adapter.name)await self._cleanup_ws()@@ -3256,55 +2407,65 @@ class ConnectionManager:adapter._release_platform_lock()return False- async def close(self) -> None:- """Cancel background tasks, fail pending futures, and close the WebSocket."""+ def _apply_bot_id(self, token_data: dict) -> None:+ """Adopt bot_id returned by the sign-token API, if any."""+ if token_data.get("bot_id"):+ self._adapter._bot_id = str(token_data["bot_id"])++ async def _dial(self, token_data: dict) -> bool:+ """Open the WS (built-in ping/pong disabled) and run AUTH_BIND; cleans up on auth failure."""+ self._ws = await asyncio.wait_for(+ websockets.connect( # type: ignore[attr-defined]+ self._adapter._ws_url, ping_interval=None, ping_timeout=None, close_timeout=5,+ ),+ timeout=CONNECT_TIMEOUT_SECONDS,+ )+ if not await self._authenticate(token_data):+ await self._cleanup_ws()+ return False+ return True- if self._heartbeat_task:- self._heartbeat_task.cancel()- try:- await self._heartbeat_task- except asyncio.CancelledError:- pass- self._heartbeat_task = None+ _LOOPS = (("_heartbeat_task", "_heartbeat_loop", "heartbeat"), ("_recv_task", "_receive_loop", "recv"))- if self._recv_task:- self._recv_task.cancel()- try:- await self._recv_task- except asyncio.CancelledError:- pass- self._recv_task = None+ def _start_loops(self, *, cancel_existing: bool) -> None:+ """(Re)start the heartbeat and receive loops for the current connect_id."""+ for attr, coro_name, tag in self._LOOPS:+ old = getattr(self, attr)+ if cancel_existing and old and not old.done():+ old.cancel()+ setattr(self, attr, asyncio.create_task(+ getattr(self, coro_name)(), name=f"yuanbao-{tag}-{self._connect_id}",+ ))- # Fail any pending ACK futures+ async def close(self) -> None:+ """Cancel background tasks, fail pending futures, and close the WebSocket."""+ for attr, _coro_name, _tag in self._LOOPS:+ task = getattr(self, attr)+ if task:+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+ setattr(self, attr, None)disc_exc = RuntimeError("YuanbaoAdapter disconnected")for fut in self._pending_acks.values():if not fut.done():fut.set_exception(disc_exc)self._pending_acks.clear()-- # Clear refresh locks to avoid stale locks from a previous event loop- SignManager.clear_locks()-+ SignManager.clear_locks() # avoid stale locks bound to a previous event loopawait self._cleanup_ws()- # -- Authentication -----------------------------------------------------async def _authenticate(self, token_data: dict) -> bool:- """Send AUTH_BIND and read frames until BIND_ACK is received.-- Returns True on success, False on failure/timeout.- """+ """Send AUTH_BIND and read frames until BIND_ACK; False on failure/timeout."""adapter = self._adapterif self._ws is None:return False-token = token_data.get("token", "")uid = adapter._bot_id or token_data.get("bot_id", "")source = token_data.get("source") or "bot"route_env = adapter._route_env or token_data.get("route_env", "") or ""-msg_id = str(uuid.uuid4())-auth_bytes = encode_auth_bind(biz_id="ybBot",uid=uid,@@ -3318,7 +2479,6 @@ class ConnectionManager:)await self._ws.send(auth_bytes)logger.debug("[%s] AUTH_BIND sent (msg_id=%s uid=%s)", adapter.name, msg_id, uid)-try:_loop = asyncio.get_running_loop()deadline = _loop.time() + AUTH_TIMEOUT_SECONDS@@ -3327,20 +2487,16 @@ class ConnectionManager:if remaining <= 0:logger.error("[%s] AUTH_BIND timeout waiting for BIND_ACK", adapter.name)return False-raw = await asyncio.wait_for(self._ws.recv(), timeout=remaining)if not isinstance(raw, (bytes, bytearray)):continue-try:msg = decode_conn_msg(bytes(raw))except Exception:continue-head = msg.get("head", {})cmd_type = head.get("cmd_type", -1)cmd = head.get("cmd", "")-if cmd_type == CMD_TYPE["Response"] and cmd == "auth-bind":connect_id = self._extract_connect_id(msg)if connect_id:@@ -3350,7 +2506,6 @@ class ConnectionManager:else:logger.error("[%s] BIND_ACK missing connectId", adapter.name)return False-except asyncio.TimeoutError:logger.error("[%s] AUTH_BIND timeout", adapter.name)return False@@ -3358,6 +2513,14 @@ class ConnectionManager:logger.error("[%s] AUTH_BIND error: %s", adapter.name, exc, exc_info=True)return False+ def _pop_pending(self, msg_id: str) -> Optional[asyncio.Future]:+ """Pop the not-yet-done future registered for *msg_id*, if any."""+ if msg_id and msg_id in self._pending_acks:+ fut = self._pending_acks.pop(msg_id)+ if not fut.done():+ return fut+ return None+def _extract_connect_id(self, decoded_msg: dict) -> Optional[str]:"""Extract connectId from decoded BIND_ACK message."""data: bytes = decoded_msg.get("data", b"")@@ -3379,8 +2542,6 @@ class ConnectionManager:logger.warning("[%s] Failed to extract connectId: %s", self._adapter.name, exc)return None- # -- Heartbeat ----------------------------------------------------------async def _heartbeat_loop(self) -> None:"""Send HEARTBEAT (ping) every 30s; trigger reconnect after threshold misses."""adapter = self._adapter@@ -3420,8 +2581,6 @@ class ConnectionManager:except asyncio.CancelledError:pass- # -- Receive loop -------------------------------------------------------async def _receive_loop(self) -> None:"""Read WS frames and dispatch by cmd_type."""adapter = self._adapter@@ -3458,50 +2617,38 @@ class ConnectionManager:except Exception as exc:logger.debug("[%s] Failed to decode frame: %s", adapter.name, exc)return-head = msg.get("head", {})cmd_type = head.get("cmd_type", -1)cmd = head.get("cmd", "")msg_id = head.get("msg_id", "")need_ack = head.get("need_ack", False)data: bytes = msg.get("data", b"")-# HEARTBEAT_ACKif cmd_type == CMD_TYPE["Response"] and cmd == "ping":logger.debug("[%s] HEARTBEAT_ACK received (msg_id=%s)", adapter.name, msg_id)if self._pending_pong is not None and not self._pending_pong.done():self._pending_pong.set_result(True)- elif msg_id and msg_id in self._pending_acks:- fut = self._pending_acks.pop(msg_id)- if not fut.done():+ else:+ fut = self._pop_pending(msg_id)+ if fut is not None:fut.set_result(True)return-- # Fire-and-forget heartbeat ACKs — server always responds but callers don't- # wait on these; silently discard to avoid "Unmatched Response" noise.- if cmd_type == CMD_TYPE["Response"] and cmd in {- "send_group_heartbeat",- "send_private_heartbeat",- }:+ # Fire-and-forget heartbeat ACKs: nobody awaits them; discard to avoid "Unmatched" noise.+ if cmd_type == CMD_TYPE["Response"] and cmd in {"send_group_heartbeat", "send_private_heartbeat"}:logger.debug("[%s] Heartbeat ACK received: cmd=%s msg_id=%s", adapter.name, cmd, msg_id)return-# Response to an outbound RPC callif cmd_type == CMD_TYPE["Response"]:if msg_id and msg_id in self._pending_acks:- fut = self._pending_acks.pop(msg_id)- if not fut.done():+ fut = self._pop_pending(msg_id)+ if fut is not None:result = {"head": head}if data:result["data"] = datafut.set_result(result)else:- logger.debug(- "[%s] Unmatched Response: cmd=%s msg_id=%s",- adapter.name, cmd, msg_id,- )+ logger.debug("[%s] Unmatched Response: cmd=%s msg_id=%s", adapter.name, cmd, msg_id)return-# Server-initiated Pushif cmd_type == CMD_TYPE["Push"]:logger.info("[%s] Push received: cmd=%s msg_id=%s data_len=%d", adapter.name, cmd, msg_id, len(data))@@ -3511,99 +2658,60 @@ class ConnectionManager:await self._ws.send(ack_bytes)except Exception as ack_exc:logger.debug("[%s] Failed to send PushAck: %s", adapter.name, ack_exc)-if msg_id and msg_id in self._pending_acks:- fut = self._pending_acks.pop(msg_id)- if not fut.done():+ fut = self._pop_pending(msg_id)+ if fut is not None:try:- decoded = decode_inbound_push(data) if data else {"head": head}- fut.set_result(decoded)+ fut.set_result(decode_inbound_push(data) if data else {"head": head})except Exception as exc:fut.set_exception(exc)return-- # Genuine inbound message — dispatch to AI- if data:+ if data: # genuine inbound message — dispatch to AIlogger.info("[%s] WS received inbound push, decoding and dispatching: cmd=%s, data_len=%d",adapter.name, cmd, len(data),)self._push_to_inbound(data)return-logger.debug("[%s] Ignoring frame: cmd_type=%d cmd=%s msg_id=%s",adapter.name, cmd_type, cmd, msg_id,)- # -- Inbound dispatch ----------------------------------------------------_DEBOUNCE_WINDOW: float = 1.5 # seconds to wait for companion messagesdef _extract_sender_key(self, raw_data: bytes) -> str:- """Lightweight decode to extract sender key for debounce grouping.-- Returns 'from_account:group_code' or a fallback unique key.- """+ """Debounce key 'from_account:group_code' (JSON or protobuf), else a unique fallback."""try:parsed = json.loads(raw_data.decode("utf-8"))if isinstance(parsed, dict):- from_account = (- parsed.get("from_account", "")- or parsed.get("From_Account", "")- )- group_code = (- parsed.get("group_code", "")- or parsed.get("GroupId", "")- or parsed.get("group_id", "")- )+ from_account, group_code = DecodeMiddleware.json_sender_fields(parsed)if from_account:return f"{from_account}:{group_code}"except Exception:pass- # Protobuf: try decode_inbound_push for sender infotry:push = decode_inbound_push(raw_data)if push:return f"{push.get('from_account', '')}:{push.get('group_code', '')}"except Exception:pass- # Fallback: unique key (no aggregation)return f"__unknown_{id(raw_data)}"def _push_to_inbound(self, raw_data: bytes) -> None:- """Debounced inbound dispatch.-- Buffers raw frames from the same sender within a short time window,- then dispatches all buffered data as a single aggregated pipeline- execution. This merges multi-part messages (e.g. image + text sent- as separate WS pushes) into one pipeline run.- """+ """Debounced dispatch: frames from one sender within _DEBOUNCE_WINDOW run as ONE pipeline+ execution, merging multi-part messages (e.g. image + text pushed separately)."""key = self._extract_sender_key(raw_data)-- # Cancel existing timer for this key (reset debounce window)existing_timer = self._inbound_timers.pop(key, None)if existing_timer:existing_timer.cancel()-- # Append to buffer- if key not in self._inbound_buffer:- self._inbound_buffer[key] = []- self._inbound_buffer[key].append(raw_data)-+ self._inbound_buffer.setdefault(key, []).append(raw_data)logger.debug("[%s] Debounce: buffered frame for key=%s, count=%d",self._adapter.name, key, len(self._inbound_buffer[key]),)-- # Schedule flush after debounce windowloop = asyncio.get_running_loop()- timer = loop.call_later(- self._DEBOUNCE_WINDOW,- self._flush_inbound_buffer,- key,- )- self._inbound_timers[key] = timer+ self._inbound_timers[key] = loop.call_later(self._DEBOUNCE_WINDOW, self._flush_inbound_buffer, key)def _flush_inbound_buffer(self, key: str) -> None:"""Flush the debounce buffer for a given key — execute the pipeline."""@@ -3611,54 +2719,31 @@ class ConnectionManager:data_list = self._inbound_buffer.pop(key, [])if not data_list:return-adapter = self._adapterlogger.info("[%s] Debounce flush: key=%s, aggregated %d frames",adapter.name, key, len(data_list),)-ctx = InboundContext(adapter=adapter, raw_frames=data_list)-adapter._track_task(asyncio.create_task(- adapter._inbound_pipeline.execute(ctx),- name=f"yuanbao-pipeline-{key}",+ adapter._inbound_pipeline.execute(ctx), name=f"yuanbao-pipeline-{key}",))- # -- Send business request ----------------------------------------------async def send_biz_request(- self,- encoded_conn_msg: bytes,- req_id: str,- timeout: float = DEFAULT_SEND_TIMEOUT,+ self, encoded_conn_msg: bytes, req_id: str, timeout: float = DEFAULT_SEND_TIMEOUT,) -> dict:- """Send a business-layer request and wait for the response.-- 1. Register a Future in pending_acks[req_id]- 2. Send encoded_conn_msg (bytes) to WS- 3. asyncio.wait_for(future, timeout)- 4. Clean up pending_acks on timeout/exception- """+ """Send a business request and await its response future (pending_acks[req_id]), cleaning up on exit."""if self._ws is None:raise RuntimeError("Not connected")-loop = asyncio.get_running_loop()future: asyncio.Future = loop.create_future()self._pending_acks[req_id] = futuretry:await self._ws.send(encoded_conn_msg)- result = await asyncio.wait_for(asyncio.shield(future), timeout=timeout)- return result- except asyncio.TimeoutError:- raise- except Exception:- raise+ return await asyncio.wait_for(asyncio.shield(future), timeout=timeout)finally:self._pending_acks.pop(req_id, None)- # -- Reconnect ----------------------------------------------------------def schedule_reconnect(self) -> None:"""Schedule a reconnect only if running and not already reconnecting."""if self._adapter._running and not self._reconnecting:@@ -3686,65 +2771,32 @@ class ConnectionManager:adapter.name, attempt + 1, MAX_RECONNECT_ATTEMPTS, wait,)await asyncio.sleep(wait)-await self._cleanup_ws()-try:token_data = await SignManager.force_refresh(adapter._app_key, adapter._app_secret, adapter._api_domain,route_env=adapter._route_env,)- if token_data.get("bot_id"):- adapter._bot_id = str(token_data["bot_id"])-- self._ws = await asyncio.wait_for(- websockets.connect( # type: ignore[attr-defined]- adapter._ws_url,- ping_interval=None,- ping_timeout=None,- close_timeout=5,- ),- timeout=CONNECT_TIMEOUT_SECONDS,- )-- authed = await self._authenticate(token_data)- if not authed:+ self._apply_bot_id(token_data)+ if not await self._dial(token_data):logger.warning("[%s] Re-auth failed on attempt %d", adapter.name, attempt + 1)- await self._cleanup_ws()continue-self._reconnect_attempts = 0self._consecutive_hb_timeouts = 0adapter._mark_connected()-- if self._heartbeat_task and not self._heartbeat_task.done():- self._heartbeat_task.cancel()- self._heartbeat_task = asyncio.create_task(- self._heartbeat_loop(),- name=f"yuanbao-heartbeat-{self._connect_id}",- )-- if self._recv_task and not self._recv_task.done():- self._recv_task.cancel()- self._recv_task = asyncio.create_task(- self._receive_loop(),- name=f"yuanbao-recv-{self._connect_id}",- )-+ self._start_loops(cancel_existing=True)logger.info("[%s] Reconnected on attempt %d. connectId=%s",adapter.name, attempt + 1, self._connect_id,)YuanbaoAdapter.set_active(adapter)return True-except asyncio.TimeoutError:logger.warning("[%s] Reconnect attempt %d timed out", adapter.name, attempt + 1)except Exception as exc:logger.warning("[%s] Reconnect attempt %d failed: %s", adapter.name, attempt + 1, exc)-logger.error("[%s] Giving up after %d reconnect attempts", adapter.name, MAX_RECONNECT_ATTEMPTS)@@ -3752,18 +2804,14 @@ class ConnectionManager:return Falseasync def _cleanup_ws(self) -> None:- """Close and clear the WebSocket connection, bounded by- ``WS_CLOSE_TIMEOUT_S`` so an unresponsive server can't stall teardown- (see the constant's definition for the full rationale)."""+ """Close and clear the WS, bounded by WS_CLOSE_TIMEOUT_S so an unresponsive server can't stall teardown."""ws = self._wsself._ws = Noneif ws is not None:try:await asyncio.wait_for(ws.close(), timeout=WS_CLOSE_TIMEOUT_S)except asyncio.TimeoutError:- # Server never echoed the close frame within the bound; drop the- # connection. websockets force-closes the transport on cancel,- # and at shutdown the loop is tearing down anyway.+ # No close-frame echo in time; websockets force-closes the transport on cancel.logger.debug("[%s] WS close handshake exceeded %.1fs — dropping connection",self._adapter.name, WS_CLOSE_TIMEOUT_S,@@ -3772,25 +2820,12 @@ class ConnectionManager:passclass MediaSendHandler(ABC):- """Abstract base class for media send strategies.-- Subclasses implement:- - acquire_file(): how to obtain file bytes (download URL / read local)- - build_msg_body(): how to build TIMxxxElem from upload result-- The shared flow (check ws → cancel notifier → validate → COS upload- → lock → dispatch) is handled by the base handle() template method.- """+ """Media send strategy: subclasses provide acquire_file() and build_msg_body(); handle() runs+ the shared flow (check ws → cancel notifier → validate → COS upload → lock → dispatch)."""@abstractmethod- async def acquire_file(- self, adapter: "YuanbaoAdapter", **kwargs: Any,- ) -> Tuple[bytes, str, str]:- """Return (file_bytes, filename, content_type).-- Raises:- ValueError: when file cannot be acquired (not found, empty, etc.)- """+ async def acquire_file(self, adapter: "YuanbaoAdapter", **kwargs: Any) -> Tuple[bytes, str, str]:+ """Return (file_bytes, filename, content_type); raise ValueError when unobtainable."""@abstractmethoddef build_msg_body(self, upload_result: dict, **kwargs: Any) -> list:@@ -3811,48 +2846,25 @@ class MediaSendHandler(ABC):"""Template method: shared media send flow."""conn = adapter._connectionsender = adapter._outbound.sender-if conn.ws is None:return SendResult(success=False, error="Not connected", retryable=True)-adapter._outbound.cancel_slow_notifier(chat_id)-try:- # 1. Acquire file bytes- file_bytes, filename, content_type = await self.acquire_file(- adapter, **kwargs,- )-- # 2. Validate (only for handlers that upload to COS; stickers use- # TIMFaceElem and legitimately carry no file bytes, so skipping- # validate_media here avoids a spurious "Empty file: sticker").+ file_bytes, filename, content_type = await self.acquire_file(adapter, **kwargs)if self.needs_cos_upload():- validation_err = MessageSender.validate_media(- file_bytes, filename, adapter.MEDIA_MAX_SIZE_MB,- )+ # Stickers (TIMFaceElem) carry no bytes — validating them would yield "Empty file".+ validation_err = MessageSender.validate_media(file_bytes, filename, adapter.MEDIA_MAX_SIZE_MB)if validation_err:return SendResult(success=False, error=validation_err)-- if self.needs_cos_upload():- file_uuid = md5_hex(file_bytes)-- # 3. Get COS upload credentialstoken_data = await adapter._get_cached_token()- token: str = token_data.get("token", "")- bot_id: str = (- token_data.get("bot_id", "") or adapter._bot_id or ""- )-credentials = await get_cos_credentials(app_key=adapter._app_key,api_domain=adapter._api_domain,- token=token,+ token=token_data.get("token", ""),filename=filename,- bot_id=bot_id,+ bot_id=token_data.get("bot_id", "") or adapter._bot_id or "",route_env=adapter._route_env,)-- # 4. Upload to COSupload_result = await upload_to_cos(file_bytes=file_bytes,filename=filename,@@ -3861,46 +2873,41 @@ class MediaSendHandler(ABC):bucket=credentials["bucketName"],region=credentials["region"],)-- # 5. Build MsgBody- # Remove keys already passed explicitly to avoid "multiple values" TypeError- fwd_kwargs = {- k: v for k, v in kwargs.items()- if k not in {"file_uuid", "filename", "content_type"}- }+ # Drop keys passed explicitly below to avoid "multiple values" TypeError.+ fwd_kwargs = {k: v for k, v in kwargs.items() if k not in {"file_uuid", "filename", "content_type"}}msg_body = self.build_msg_body(- upload_result,- file_uuid=file_uuid,- filename=filename,- content_type=content_type,- **fwd_kwargs,+ upload_result, file_uuid=md5_hex(file_bytes), filename=filename,+ content_type=content_type, **fwd_kwargs,)else:- # Non-COS media (e.g. sticker): build MsgBody directlymsg_body = self.build_msg_body({}, **kwargs)-- # 6. Append caption if providedif caption:- msg_body.append(- {"msg_type": "TIMTextElem", "msg_content": {"text": caption}},- )-- # 7. Lock + dispatch+ msg_body.append({"msg_type": "TIMTextElem", "msg_content": {"text": caption}})gc = kwargs.get("group_code", "")return await sender.dispatch_msg_body(chat_id, msg_body, reply_to, group_code=gc)-except ValueError as ve:return SendResult(success=False, error=str(ve))except Exception as exc:- handler_name = type(self).__name__- logger.error(- "[%s] %s.handle() failed: %s",- adapter.name, handler_name, exc, exc_info=True,- )+ logger.error("[%s] %s.handle() failed: %s", adapter.name, type(self).__name__, exc, exc_info=True)return SendResult(success=False, error=str(exc) or type(exc).__name__)-class ImageUrlHandler(MediaSendHandler):+class _ImageHandler(MediaSendHandler):+ """Shared TIMImageElem body builder for image handlers."""++ def build_msg_body(self, upload_result, **kwargs):+ return build_image_msg_body(+ url=upload_result["url"],+ uuid=kwargs["file_uuid"],+ filename=kwargs["filename"],+ size=upload_result["size"],+ width=upload_result.get("width", 0),+ height=upload_result.get("height", 0),+ mime_type=kwargs["content_type"],+ )+++class ImageUrlHandler(_ImageHandler):"""Strategy: send image from a URL (download → COS → TIMImageElem)."""async def acquire_file(self, adapter, **kwargs):@@ -3915,19 +2922,8 @@ class ImageUrlHandler(MediaSendHandler):filename = os.path.basename(image_url.split("?")[0]) or "image.jpg"return file_bytes, filename, content_type- def build_msg_body(self, upload_result, **kwargs):- return build_image_msg_body(- url=upload_result["url"],- uuid=kwargs["file_uuid"],- filename=kwargs["filename"],- size=upload_result["size"],- width=upload_result.get("width", 0),- height=upload_result.get("height", 0),- mime_type=kwargs["content_type"],- )--class ImageFileHandler(MediaSendHandler):+class ImageFileHandler(_ImageHandler):"""Strategy: send image from a local file path (read → COS → TIMImageElem)."""async def acquire_file(self, adapter, **kwargs):@@ -3941,43 +2937,6 @@ class ImageFileHandler(MediaSendHandler):content_type = guess_mime_type(filename) or "image/jpeg"return file_bytes, filename, content_type- def build_msg_body(self, upload_result, **kwargs):- return build_image_msg_body(- url=upload_result["url"],- uuid=kwargs["file_uuid"],- filename=kwargs["filename"],- size=upload_result["size"],- width=upload_result.get("width", 0),- height=upload_result.get("height", 0),- mime_type=kwargs["content_type"],- )---class FileUrlHandler(MediaSendHandler):- """Strategy: send file from a URL (download → COS → TIMFileElem)."""-- async def acquire_file(self, adapter, **kwargs):- file_url: str = kwargs["file_url"]- logger.info("[%s] FileUrlHandler: downloading %s", adapter.name, file_url)- file_bytes, content_type = await media_download_url(- file_url, max_size_mb=adapter.MEDIA_MAX_SIZE_MB,- )- filename = kwargs.get("filename")- if not filename:- path_part = file_url.split("?")[0]- filename = os.path.basename(path_part) or "file"- if not content_type or content_type == "application/octet-stream":- content_type = guess_mime_type(filename) or "application/octet-stream"- return file_bytes, filename, content_type-- def build_msg_body(self, upload_result, **kwargs):- return build_file_msg_body(- url=upload_result["url"],- filename=kwargs["filename"],- uuid=kwargs["file_uuid"],- size=upload_result["size"],- )-class DocumentHandler(MediaSendHandler):"""Strategy: send local file/document (read → COS → TIMFileElem)."""@@ -4009,8 +2968,7 @@ class StickerHandler(MediaSendHandler):return Falseasync def acquire_file(self, adapter, **kwargs):- # Sticker does not need file bytes; return dummy values- return b"", "sticker", "application/octet-stream"+ return b"", "sticker", "application/octet-stream" # no file bytes neededdef build_msg_body(self, upload_result, **kwargs):from gateway.platforms.yuanbao_sticker import (@@ -4021,7 +2979,6 @@ class StickerHandler(MediaSendHandler):)sticker_name = kwargs.get("sticker_name")face_index = kwargs.get("face_index")-if sticker_name is not None:sticker = get_sticker_by_name(sticker_name)if sticker is None:@@ -4033,166 +2990,67 @@ class StickerHandler(MediaSendHandler):sticker = get_random_sticker()return build_sticker_msg_body(sticker)-class GroupQueryService:- """Encapsulates all group query operations (both low-level WS calls and- higher-level AI-tool-facing wrappers).- Responsibilities:- - Low-level WS encode/decode for group info and member list queries- - Chat-id parsing, error wrapping and result filtering for AI tools- - Member cache population on the adapter- """+class GroupQueryService:+ """Low-level WS group queries (group info, member list); populates adapter._member_cache."""def __init__(self, adapter: "YuanbaoAdapter") -> None:self._adapter = adapter- # ------------------------------------------------------------------- # Low-level WS query methods- # -------------------------------------------------------------------- async def query_group_info_raw(self, group_code: str) -> Optional[dict]:- """Query group info via WS (group name, owner, member count, etc.).-- Returns:- Decoded dict or None on failure.- """+ async def _ws_query(self, label: str, group_code: str, encoded: bytes, decode_rsp, empty: dict) -> Optional[dict]:+ """Send an encoded group query over WS; return decoded biz payload, *empty* when none, None on failure."""adapter = self._adapterif adapter._connection.ws is None:return None- encoded = encode_query_group_info(group_code)- from gateway.platforms.yuanbao_proto import decode_conn_msg as _decode- decoded = _decode(encoded)- req_id = decoded["head"]["msg_id"]+ req_id = decode_conn_msg(encoded)["head"]["msg_id"]try:response = await adapter._connection.send_biz_request(encoded, req_id=req_id)- head = response.get("head", {})- status = head.get("status", 0)+ status = response.get("head", {}).get("status", 0)if status != 0:- logger.warning("[%s] query_group_info failed: status=%d", adapter.name, status)+ logger.warning("[%s] %s failed: status=%d", adapter.name, label, status)return Nonebiz_data = response.get("data", b"") or response.get("body", b"")if biz_data and isinstance(biz_data, bytes):- return decode_query_group_info_rsp(biz_data)- return {"group_code": group_code}+ return decode_rsp(biz_data)+ return emptyexcept asyncio.TimeoutError:- logger.warning("[%s] query_group_info timeout: group=%s", adapter.name, group_code)+ logger.warning("[%s] %s timeout: group=%s", adapter.name, label, group_code)return Noneexcept Exception as exc:- logger.warning("[%s] query_group_info failed: %s", adapter.name, exc)+ logger.warning("[%s] %s failed: %s", adapter.name, label, exc)return None+ async def query_group_info_raw(self, group_code: str) -> Optional[dict]:+ """Query group info via WS (name, owner, member count…); None on failure."""+ return await self._ws_query(+ "query_group_info", group_code, encode_query_group_info(group_code),+ decode_query_group_info_rsp, {"group_code": group_code},+ )+async def get_group_member_list_raw(self, group_code: str, offset: int = 0, limit: int = 200) -> Optional[dict]:- """Query group member list via WS.-- Returns:- Decoded dict or None on failure. Also populates adapter._member_cache.- """- adapter = self._adapter- if adapter._connection.ws is None:- return None- encoded = encode_get_group_member_list(group_code, offset=offset, limit=limit)- from gateway.platforms.yuanbao_proto import decode_conn_msg as _decode- decoded = _decode(encoded)- req_id = decoded["head"]["msg_id"]- try:- response = await adapter._connection.send_biz_request(encoded, req_id=req_id)- head = response.get("head", {})- status = head.get("status", 0)- if status != 0:- logger.warning("[%s] get_group_member_list failed: status=%d", adapter.name, status)- return None- biz_data = response.get("data", b"") or response.get("body", b"")- if biz_data and isinstance(biz_data, bytes):- result = decode_get_group_member_list_rsp(biz_data)- else:- result = {"members": [], "next_offset": 0, "is_complete": True}- if result and result.get("members"):- adapter._member_cache[group_code] = (time.time(), result["members"])- return result- except asyncio.TimeoutError:- logger.warning("[%s] get_group_member_list timeout: group=%s", adapter.name, group_code)- return None- except Exception as exc:- logger.warning("[%s] get_group_member_list failed: %s", adapter.name, exc)- return None-- # ------------------------------------------------------------------- # AI-tool-facing wrappers (chat_id parsing + filtering)- # -------------------------------------------------------------------- async def query_group_info(self, chat_id: str) -> dict:- """AI tool: Query current group info.-- No parameters needed (group_code extracted from session context).- Returns group name, owner, member count, etc.- """- if not chat_id.startswith("group:"):- return {"error": "This command is only available in group chats"}- group_code = chat_id[len("group:"):]- result = await self.query_group_info_raw(group_code)- if result is None:- return {"error": "Failed to query group info"}+ """Query group member list via WS; None on failure. Populates adapter._member_cache."""+ result = await self._ws_query(+ "get_group_member_list", group_code,+ encode_get_group_member_list(group_code, offset=offset, limit=limit),+ decode_get_group_member_list_rsp, {"members": [], "next_offset": 0, "is_complete": True},+ )+ if result and result.get("members"):+ self._adapter._member_cache[group_code] = (time.time(), result["members"])return result- async def query_session_members(- self,- chat_id: str,- action: str = "list_all",- name: Optional[str] = None,- ) -> dict:- """AI tool: Query group member list.-- Args:- chat_id: Chat ID (extracted from session context)- action: 'find' (search by name) | 'list_bots' (list bots) | 'list_all' (list all)- name: Search keyword when action='find'- Returns:- {"members": [...], "total": int, "mentionHint": str}- """- if not chat_id.startswith("group:"):- return {"error": "This command is only available in group chats"}- group_code = chat_id[len("group:"):]- result = await self.get_group_member_list_raw(group_code)- if result is None:- return {"error": "Failed to query group members"}-- members = result.get("members", [])-- if action == "find" and name:- query = name.lower()- members = [- m for m in members- if query in (m.get("nickname", "") or "").lower()- or query in (m.get("name_card", "") or "").lower()- or query in (m.get("user_id", "") or "").lower()- ]- elif action == "list_bots":- members = [m for m in members if "bot" in (m.get("nickname", "") or "").lower()]-- # Construct mentionHint- mention_hint = ""- if members and len(members) <= 10:- names = [m.get("name_card") or m.get("nickname") or m.get("user_id", "") for m in members]- mention_hint = "Mention with @name: " + ", ".join(names)-- return {- "members": members[:50], # Limit return count- "total": len(members),- "mentionHint": mention_hint,- }+def _cancel_all(tasks: Dict[str, asyncio.Task]) -> None:+ """Cancel every unfinished task in *tasks* and clear the dict."""+ for task in list(tasks.values()):+ if not task.done():+ task.cancel()+ tasks.clear()class HeartbeatManager:- """Manages reply heartbeat (RUNNING / FINISH) lifecycle.-- Responsibilities:- - Periodic RUNNING heartbeat sender (every 2s)- - Auto-FINISH after 30s inactivity- - Explicit stop with optional FINISH signal- """+ """Reply heartbeat lifecycle: RUNNING every 2s, auto-FINISH after 30s idle, explicit stop."""def __init__(self, adapter: "YuanbaoAdapter") -> None:self._adapter = adapter@@ -4207,18 +3065,12 @@ class HeartbeatManager:returntry:if chat_id.startswith("group:"):- group_code = chat_id[len("group:"):]encoded = encode_send_group_heartbeat(- from_account=adapter._bot_id,- group_code=group_code,- heartbeat=heartbeat_val,+ from_account=adapter._bot_id, group_code=chat_id[len("group:"):], heartbeat=heartbeat_val,)else:- to_account = chat_id.removeprefix("direct:")encoded = encode_send_private_heartbeat(- from_account=adapter._bot_id,- to_account=to_account,- heartbeat=heartbeat_val,+ from_account=adapter._bot_id, to_account=chat_id.removeprefix("direct:"), heartbeat=heartbeat_val,)await conn.ws.send(encoded)status_name = "RUNNING" if heartbeat_val == WS_HEARTBEAT_RUNNING else "FINISH"@@ -4235,40 +3087,27 @@ class HeartbeatManager:conn = adapter._connectionif conn.ws is None or not adapter._bot_id:return-+ self._reply_hb_last_active[chat_id] = time.time()existing = self._reply_heartbeat_tasks.get(chat_id)if existing and not existing.done():- self._reply_hb_last_active[chat_id] = time.time()return-- self._reply_hb_last_active[chat_id] = time.time()-- task = asyncio.create_task(- self._worker(chat_id),- name=f"yuanbao-reply-hb-{chat_id}",+ self._reply_heartbeat_tasks[chat_id] = asyncio.create_task(+ self._worker(chat_id), name=f"yuanbao-reply-hb-{chat_id}",)- self._reply_heartbeat_tasks[chat_id] = taskasync def _worker(self, chat_id: str) -> None:- """Background coroutine: send RUNNING heartbeat every 2s.- 30s without renewal -> send FINISH and exit.- """+ """Send RUNNING every 2s; after 30s without renewal (or WS loss) send FINISH and exit."""try:await self.send_heartbeat_once(chat_id, WS_HEARTBEAT_RUNNING)-while True:await asyncio.sleep(REPLY_HEARTBEAT_INTERVAL_S)-last_active = self._reply_hb_last_active.get(chat_id, 0)if time.time() - last_active > REPLY_HEARTBEAT_TIMEOUT_S:break-conn = self._adapter._connectionif conn.ws is None:break-await self.send_heartbeat_once(chat_id, WS_HEARTBEAT_RUNNING)-except asyncio.CancelledError:cancelled = Trueexcept Exception:@@ -4277,10 +3116,7 @@ class HeartbeatManager:cancelled = Falsefinally:if not cancelled:- try:- await self.send_heartbeat_once(chat_id, WS_HEARTBEAT_FINISH)- except Exception:- pass+ await self.send_heartbeat_once(chat_id, WS_HEARTBEAT_FINISH)self._reply_heartbeat_tasks.pop(chat_id, None)self._reply_hb_last_active.pop(chat_id, None)@@ -4294,26 +3130,16 @@ class HeartbeatManager:except asyncio.CancelledError:passif send_finish:- try:- await self.send_heartbeat_once(chat_id, WS_HEARTBEAT_FINISH)- except Exception:- pass+ await self.send_heartbeat_once(chat_id, WS_HEARTBEAT_FINISH)async def close(self) -> None:"""Cancel all reply heartbeat tasks."""- for task in list(self._reply_heartbeat_tasks.values()):- if not task.done():- task.cancel()- self._reply_heartbeat_tasks.clear()+ _cancel_all(self._reply_heartbeat_tasks)self._reply_hb_last_active.clear()class SlowResponseNotifier:- """Manages delayed 'please wait' notifications for slow agent responses.-- Starts a timer per chat_id; if the agent hasn't replied within- SLOW_RESPONSE_TIMEOUT_S seconds, sends a courtesy message.- """+ """Per-chat timer that sends a courtesy 'please wait' after SLOW_RESPONSE_TIMEOUT_S without a reply."""def __init__(self, adapter: "YuanbaoAdapter", sender: "MessageSender") -> None:self._adapter = adapter@@ -4323,11 +3149,7 @@ class SlowResponseNotifier:async def start(self, chat_id: str) -> None:"""Start a delayed task that notifies the user when the agent is slow."""self.cancel(chat_id)- task = asyncio.create_task(- self._notifier(chat_id),- name=f"yuanbao-slow-resp-{chat_id}",- )- self._tasks[chat_id] = task+ self._tasks[chat_id] = asyncio.create_task(self._notifier(chat_id), name=f"yuanbao-slow-resp-{chat_id}")async def _notifier(self, chat_id: str) -> None:"""Wait SLOW_RESPONSE_TIMEOUT_S, then push a 'please wait' message."""@@ -4351,22 +3173,12 @@ class SlowResponseNotifier:async def close(self) -> None:"""Cancel all slow-response tasks."""- for task in list(self._tasks.values()):- if not task.done():- task.cancel()- self._tasks.clear()+ _cancel_all(self._tasks)class MessageSender:- """Core message sending dispatcher for YuanbaoAdapter.-- Responsibilities:- - Per-chat-id lock management (serial send ordering)- - Text chunk sending with retry- - C2C / Group message encoding and dispatch- - Media send helpers (image, file, sticker, document)- - Direct send helper (text + media, used by send_message tool)- """+ """Outbound dispatcher: per-chat locks (serial ordering), chunked text with retry, C2C/group+ encoding, media handler strategies, and send_direct for the send_message tool."""IMAGE_EXTS: ClassVar[frozenset] = frozenset({".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"})CHAT_DICT_MAX_SIZE: ClassVar[int] = 1000 # Max distinct chat IDs in _chat_locks@@ -4374,28 +3186,16 @@ class MessageSender:def __init__(self, adapter: "YuanbaoAdapter") -> None:self._adapter = adapterself._chat_locks: collections.OrderedDict[str, asyncio.Lock] = collections.OrderedDict()-- # Optional hooks injected by OutboundManager for coordination- self._on_send_start: Optional[Callable[[str], Any]] = None # cancel slow-notifier- self._on_send_finish: Optional[Callable[[str], Any]] = None # send FINISH heartbeat-- # Media send handlers (strategy pattern)+ # Hooks injected by OutboundManager: cancel slow-notifier / send FINISH heartbeat+ self._on_send_start: Optional[Callable[[str], Any]] = None+ self._on_send_finish: Optional[Callable[[str], Any]] = Noneself._media_handlers: Dict[str, MediaSendHandler] = {"image_url": ImageUrlHandler(),"image_file": ImageFileHandler(),- "file_url": FileUrlHandler(),"document": DocumentHandler(),"sticker": StickerHandler(),}- # -- Media handler registry ----------------------------------------------- def register_handler(self, name: str, handler: MediaSendHandler) -> None:- """Register (or replace) a named media send handler."""- self._media_handlers[name] = handler-- # -- Chat lock ----------------------------------------------------------def get_chat_lock(self, chat_id: str) -> asyncio.Lock:"""Return (or create) a per-chat-id lock with safe LRU eviction."""if chat_id in self._chat_locks:@@ -4413,26 +3213,17 @@ class MessageSender:self._chat_locks[chat_id] = asyncio.Lock()return self._chat_locks[chat_id]- # -- Text send ----------------------------------------------------------async def send_text(- self,- chat_id: str,- content: str,- reply_to: Optional[str] = None,- group_code: str = "",+ self, chat_id: str, content: str, reply_to: Optional[str] = None, group_code: str = "",) -> "SendResult":"""Send text message with auto-chunking and per-chat-id ordering guarantee."""adapter = self._adapterconn = adapter._connectionif conn.ws is None:return SendResult(success=False, error="Not connected", retryable=True)-if self._on_send_start:self._on_send_start(chat_id)-- lock = self.get_chat_lock(chat_id)- async with lock:+ async with self.get_chat_lock(chat_id):content_to_send = self.strip_cron_wrapper(content)chunks = self.truncate_message(content_to_send, adapter.MAX_TEXT_CHUNK)logger.info(@@ -4445,9 +3236,7 @@ class MessageSender:result = await self.send_text_chunk(chat_id, chunk, r_to, group_code=group_code)if not result.success:return result-- # Notify outbound coordinator that send is complete (e.g. FINISH heartbeat)- if self._on_send_finish:+ if self._on_send_finish: # e.g. FINISH heartbeattry:await self._on_send_finish(chat_id)except Exception:@@ -4455,63 +3244,35 @@ class MessageSender:return SendResult(success=True)async def send_media(- self,- chat_id: str,- handler_name: str,- reply_to: Optional[str] = None,- caption: Optional[str] = None,- **kwargs: Any,+ self, chat_id: str, handler_name: str, reply_to: Optional[str] = None,+ caption: Optional[str] = None, **kwargs: Any,) -> "SendResult":"""Dispatch media send to the named handler strategy."""handler = self._media_handlers.get(handler_name)if handler is None:- return SendResult(- success=False,- error=f"Unknown media handler: {handler_name!r}",- )- return await handler.handle(- self._adapter, chat_id,- reply_to=reply_to, caption=caption, **kwargs,- )-- # -- Direct send (text + media, used by send_message tool) -------------+ return SendResult(success=False, error=f"Unknown media handler: {handler_name!r}")+ return await handler.handle(self._adapter, chat_id, reply_to=reply_to, caption=caption, **kwargs)async def send_direct(- self,- chat_id: str,- message: str,- media_files: Optional[List[Tuple[str, bool]]] = None,+ self, chat_id: str, message: str, media_files: Optional[List[Tuple[str, bool]]] = None,) -> Dict[str, Any]:- """Send text + media via Yuanbao (used by the ``send_message`` tool).-- Unlike Weixin which creates a fresh adapter per call, Yuanbao reuses- the running gateway adapter (persistent WebSocket). Logic mirrors- send_weixin_direct: send text first, then iterate media_files by- extension.- """+ """send_message tool entry: text first, then each media file by extension, on the running adapter."""adapter = self._adapterlast_result: Optional["SendResult"] = None-- # 1. Send textif message.strip():last_result = await adapter.send(chat_id, message)if not last_result.success:return {"error": f"Yuanbao send failed: {last_result.error}"}-- # 2. Iterate media_files, dispatch by file extensionfor media_path, _is_voice in media_files or []:ext = Path(media_path).suffix.lower()if ext in self.IMAGE_EXTS:last_result = await adapter.send_image_file(chat_id, media_path)else:last_result = await adapter.send_document(chat_id, media_path)-if not last_result.success:return {"error": f"Yuanbao media send failed: {last_result.error}"}-if last_result is None:return {"error": "No deliverable text or media remained after processing"}-return {"success": True,"platform": "yuanbao",@@ -4520,33 +3281,17 @@ class MessageSender:}async def dispatch_msg_body(- self,- chat_id: str,- msg_body: list,- reply_to: Optional[str] = None,- group_code: str = "",+ self, chat_id: str, msg_body: list, reply_to: Optional[str] = None, group_code: str = "",) -> "SendResult":"""Lock + dispatch an arbitrary MsgBody to C2C or group."""- lock = self.get_chat_lock(chat_id)- async with lock:- if chat_id.startswith("group:"):- grp = chat_id[len("group:"):]- result = await self.send_group_msg_body(grp, msg_body, reply_to)- else:- to_account = chat_id.removeprefix("direct:")- result = await self.send_c2c_msg_body(to_account, msg_body, group_code=group_code)-+ async with self.get_chat_lock(chat_id):+ result = await self._send_msg_body(chat_id, msg_body, reply_to, group_code)if result.get("success"):return SendResult(success=True, message_id=result.get("msg_key"))return SendResult(success=False, error=result.get("error", "Unknown error"))async def send_text_chunk(- self,- chat_id: str,- text: str,- reply_to: Optional[str] = None,- retry: int = 3,- group_code: str = "",+ self, chat_id: str, text: str, reply_to: Optional[str] = None, retry: int = 3, group_code: str = "",) -> "SendResult":"""Send a single text chunk with retry (exponential backoff: 1s, 2s, 4s)."""adapter = self._adapter@@ -4554,15 +3299,12 @@ class MessageSender:for attempt in range(retry):try:if chat_id.startswith("group:"):- grp = chat_id[len("group:"):]- raw = await self.send_group_message(grp, text, reply_to)+ msg_body = self._build_msg_body_with_mentions(text, chat_id[len("group:"):])else:- to_account = chat_id.removeprefix("direct:")- raw = await self.send_c2c_message(to_account, text, group_code=group_code)-+ msg_body = [{"msg_type": "TIMTextElem", "msg_content": {"text": text}}]+ raw = await self._send_msg_body(chat_id, msg_body, reply_to, group_code)if raw.get("success"):return SendResult(success=True, message_id=raw.get("msg_key"))-last_error = raw.get("error", "Unknown error")logger.warning("[%s] send_text_chunk attempt %d/%d failed: %s",@@ -4574,38 +3316,26 @@ class MessageSender:"[%s] send_text_chunk attempt %d/%d exception: %s",adapter.name, attempt + 1, retry, last_error,)-if attempt < retry - 1:await asyncio.sleep(2 ** attempt)-logger.error("[%s] send_text_chunk max retries (%d) exceeded. Last error: %s",adapter.name, retry, last_error,)return SendResult(success=False, error=f"Max retries exceeded: {last_error}")- # -- C2C / Group message ------------------------------------------------- async def send_c2c_message(self, to_account: str, text: str, group_code: str = "") -> dict:- """Send C2C text message, return {success: bool, msg_key: str}."""- msg_body = [{"msg_type": "TIMTextElem", "msg_content": {"text": text}}]- return await self.send_c2c_msg_body(to_account, msg_body, group_code=group_code)-- async def send_group_message(- self,- group_code: str,- text: str,- reply_to: Optional[str] = None,- ) -> dict:- """Send group text message, auto-converting @nickname to TIMCustomElem."""- msg_body = self._build_msg_body_with_mentions(text, group_code)- return await self.send_group_msg_body(group_code, msg_body, reply_to)+ async def _send_msg_body(self, chat_id: str, msg_body: list, reply_to: Optional[str], group_code: str) -> dict:+ """Route a MsgBody to group (``group:<code>``) or C2C (``direct:<account>`` / bare account)."""+ if chat_id.startswith("group:"):+ return await self.send_group_msg_body(chat_id[len("group:"):], msg_body, reply_to)+ return await self.send_c2c_msg_body(chat_id.removeprefix("direct:"), msg_body, group_code=group_code)- # @mention pattern: (whitespace or start) + @ + nickname + (whitespace or end)+ # @nickname bounded by whitespace / line edges_AT_USER_RE = re.compile(r'(?:(?<=\s)|(?<=^))@(\S+?)(?=\s|$)', re.MULTILINE)def _build_msg_body_with_mentions(self, text: str, group_code: str) -> list:"""Parse @nickname patterns and build mixed TIMTextElem + TIMCustomElem msg_body."""+ members: list = []cached = self._adapter._member_cache.get(group_code)if cached:ts, member_list = cached@@ -4613,19 +3343,14 @@ class MessageSender:members = member_listelse:del self._adapter._member_cache[group_code]- members = []- else:- members = []if not members:return [{"msg_type": "TIMTextElem", "msg_content": {"text": text}}]-nickname_to_uid = {}for m in members:nick = m.get("nickname") or m.get("nick_name") or ""uid = m.get("user_id") or ""if nick and uid:nickname_to_uid[nick.lower()] = (nick, uid)-msg_body: list = []last_idx = 0for match in self._AT_USER_RE.finditer(text):@@ -4634,7 +3359,6 @@ class MessageSender:seg = text[last_idx:start].strip()if seg:msg_body.append({"msg_type": "TIMTextElem", "msg_content": {"text": seg}})-nickname = match.group(1)entry = nickname_to_uid.get(nickname.lower())if entry:@@ -4647,56 +3371,35 @@ class MessageSender:})else:msg_body.append({"msg_type": "TIMTextElem", "msg_content": {"text": f"@{nickname}"}})-last_idx = match.end()-if last_idx < len(text):tail = text[last_idx:].strip()if tail:msg_body.append({"msg_type": "TIMTextElem", "msg_content": {"text": tail}})-if not msg_body:msg_body.append({"msg_type": "TIMTextElem", "msg_content": {"text": text}})-return msg_bodyasync def send_c2c_msg_body(self, to_account: str, msg_body: list, group_code: str = "") -> dict:"""Send C2C message with arbitrary MsgBody."""- adapter = self._adapterreq_id = f"c2c_{next_seq_no()}"encoded = encode_send_c2c_message(- to_account=to_account,- msg_body=msg_body,- from_account=adapter._bot_id or "",- msg_id=req_id,- group_code=group_code,+ to_account=to_account, msg_body=msg_body, from_account=self._adapter._bot_id or "",+ msg_id=req_id, group_code=group_code,)- return await self._dispatch_encoded(adapter, encoded, req_id)+ return await self._dispatch_encoded(self._adapter, encoded, req_id)- async def send_group_msg_body(- self,- group_code: str,- msg_body: list,- reply_to: Optional[str] = None,- ) -> dict:+ async def send_group_msg_body(self, group_code: str, msg_body: list, reply_to: Optional[str] = None) -> dict:"""Send group message with arbitrary MsgBody."""- adapter = self._adapterreq_id = f"grp_{next_seq_no()}"encoded = encode_send_group_message(- group_code=group_code,- msg_body=msg_body,- from_account=adapter._bot_id or "",- msg_id=req_id,- ref_msg_id=reply_to or "",+ group_code=group_code, msg_body=msg_body, from_account=self._adapter._bot_id or "",+ msg_id=req_id, ref_msg_id=reply_to or "",)- return await self._dispatch_encoded(adapter, encoded, req_id)-- # -- Common dispatch helper --------------------------------------------+ return await self._dispatch_encoded(self._adapter, encoded, req_id)@staticmethod- async def _dispatch_encoded(- adapter: "YuanbaoAdapter", encoded: bytes, req_id: str,- ) -> dict:+ async def _dispatch_encoded(adapter: "YuanbaoAdapter", encoded: bytes, req_id: str) -> dict:"""Send pre-encoded bytes via WS and return a normalised result dict."""try:response = await adapter._connection.send_biz_request(encoded, req_id=req_id)@@ -4706,17 +3409,9 @@ class MessageSender:except Exception as exc:return {"success": False, "error": str(exc)}- # -- Media validation ----------------------------------------------------@staticmethod- def validate_media(- file_bytes: Optional[bytes], filename: str, max_size_mb: int = 20- ) -> Optional[str]:- """Media pre-validation: check file validity before sending/uploading.-- Returns:- Error description (str) if validation fails, otherwise None.- """+ def validate_media(file_bytes: Optional[bytes], filename: str, max_size_mb: int = 20) -> Optional[str]:+ """Pre-upload check; returns an error description or None."""if file_bytes is None or len(file_bytes) == 0:return f"Empty file: {filename}"max_bytes = max_size_mb * 1024 * 1024@@ -4725,80 +3420,43 @@ class MessageSender:return f"File too large: {filename} ({size_mb:.1f}MB > {max_size_mb}MB)"return None- # -- Text truncation (table-aware) ---------------------------------------@staticmethoddef truncate_message(- content: str,- max_length: int = 4000,- len_fn: Optional[Callable[[str], int]] = None,+ content: str, max_length: int = 4000, len_fn: Optional[Callable[[str], int]] = None,) -> List[str]:- """- Split a long message into chunks with table-awareness.-- Delegates core splitting to ``MarkdownProcessor.chunk_markdown_text``- and strips page indicators like ``(1/3)`` from the output.-- Falls back to ``BasePlatformAdapter.truncate_message`` for non-table- content and for overall text that fits in a single chunk.- """+ """Table/fence-aware chunking via MarkdownProcessor, stripping ``(1/3)`` page indicators."""_len = len_fn or lenif _len(content) <= max_length:return [content]-- # Delegate to MarkdownProcessor for table/fence-aware chunking- chunks = MarkdownProcessor.chunk_markdown_text(- content, max_length, len_fn=len_fn,- )-- # Strip page indicators like (1/3) that BasePlatformAdapter may add+ chunks = MarkdownProcessor.chunk_markdown_text(content, max_length, len_fn=len_fn)chunks = [_INDICATOR_RE.sub('', c) for c in chunks]-return chunks if chunks else [content]- # -- Cron wrapper stripping ----------------------------------------------@staticmethoddef strip_cron_wrapper(content: str) -> str:"""Strip scheduler cron header/footer wrapper for cleaner Yuanbao output."""if not content.startswith("Cronjob Response: "):return content-divider = "\n-------------\n\n"footer_prefix = '\n\nTo stop or manage this job, send me a new message (e.g. "stop reminder 'divider_pos = content.find(divider)footer_pos = content.rfind(footer_prefix)if divider_pos < 0 or footer_pos < 0 or footer_pos <= divider_pos:return content-header = content[:divider_pos]if "\n(job_id: " not in header:return content-body_start = divider_pos + len(divider)body = content[body_start:footer_pos].strip()return body or content- # -- Cleanup on disconnect ----------------------------------------------async def close(self) -> None:- """Release chat locks (no-op for now; placeholder for future cleanup)."""self._chat_locks.clear()class OutboundManager:- """Outbound coordinator that orchestrates sending, heartbeat and slow-response.-- Composes:- - MessageSender — core text/media sending- - HeartbeatManager — reply heartbeat (RUNNING / FINISH) lifecycle- - SlowResponseNotifier — delayed 'please wait' notifications-- YuanbaoAdapter holds a single ``_outbound: OutboundManager`` and delegates- all outbound operations through it.- """+ """Composes MessageSender, HeartbeatManager and SlowResponseNotifier and wires their coordination hooks."""- # Expose class-level constants from MessageSender for backward compatibilityCHAT_DICT_MAX_SIZE: ClassVar[int] = MessageSender.CHAT_DICT_MAX_SIZEdef __init__(self, adapter: "YuanbaoAdapter") -> None:@@ -4806,75 +3464,30 @@ class OutboundManager:self.sender: MessageSender = MessageSender(adapter)self.heartbeat: HeartbeatManager = HeartbeatManager(adapter)self.slow_notifier: SlowResponseNotifier = SlowResponseNotifier(adapter, self.sender)-- # Wire coordination hooks into MessageSenderself.sender._on_send_start = self._handle_send_startself.sender._on_send_finish = self._handle_send_finish- # -- Coordination hooks -------------------------------------------------def _handle_send_start(self, chat_id: str) -> None:- """Called by MessageSender before sending: cancel slow-response notifier."""+ """Before a send: cancel the slow-response notifier."""self.slow_notifier.cancel(chat_id)async def _handle_send_finish(self, chat_id: str) -> None:- """Called by MessageSender after sending: send FINISH heartbeat."""+ """After a send: FINISH heartbeat."""await self.heartbeat.send_heartbeat_once(chat_id, WS_HEARTBEAT_FINISH)- # -- Delegated public API (used by YuanbaoAdapter) ----------------------- async def send_text(- self, chat_id: str, content: str, reply_to: Optional[str] = None,- group_code: str = "",- ) -> "SendResult":- """Send text message with auto-chunking."""- return await self.sender.send_text(chat_id, content, reply_to, group_code=group_code)-- async def send_media(- self, chat_id: str, handler_name: str, **kwargs: Any,- ) -> "SendResult":- """Dispatch media send to the named handler strategy."""- return await self.sender.send_media(chat_id, handler_name, **kwargs)-- async def send_direct(- self, chat_id: str, message: str,- media_files: Optional[List[Tuple[str, bool]]] = None,- ) -> Dict[str, Any]:- """Send text + media (used by send_message tool)."""- return await self.sender.send_direct(chat_id, message, media_files)-- async def start_typing(self, chat_id: str) -> None:- """Start reply heartbeat (RUNNING)."""- await self.heartbeat.start(chat_id)-- async def stop_typing(self, chat_id: str, send_finish: bool = False) -> None:- """Stop reply heartbeat."""- await self.heartbeat.stop(chat_id, send_finish=send_finish)-async def start_slow_notifier(self, chat_id: str) -> None:- """Start slow-response notifier."""await self.slow_notifier.start(chat_id)def cancel_slow_notifier(self, chat_id: str) -> None:- """Cancel slow-response notifier."""self.slow_notifier.cancel(chat_id)def get_chat_lock(self, chat_id: str) -> asyncio.Lock:- """Proxy to MessageSender.get_chat_lock for backward compatibility."""return self.sender.get_chat_lock(chat_id)@propertydef _chat_locks(self) -> collections.OrderedDict:- """Proxy to MessageSender._chat_locks for backward compatibility."""return self.sender._chat_locks- @staticmethod- def validate_media(- file_bytes: Optional[bytes], filename: str, max_size_mb: int = 20,- ) -> Optional[str]:- """Proxy to MessageSender.validate_media."""- return MessageSender.validate_media(file_bytes, filename, max_size_mb)-async def close(self) -> None:"""Shut down all sub-managers."""await self.sender.close()@@ -4889,9 +3502,6 @@ class YuanbaoAdapter(BasePlatformAdapter):MAX_TEXT_CHUNK: int = 4000 # Yuanbao single message character limitsplits_long_messages = True # send() auto-chunks via truncate_message(MAX_TEXT_CHUNK)MEDIA_MAX_SIZE_MB: int = 50 # Max media file size in MB for upload validation- REPLY_REF_MAX_ENTRIES: ClassVar[int] = 500 # Max capacity of reference dedup dict-- # -- Active instance registry (class-level singleton) -------------------_active_instance: ClassVar[Optional["YuanbaoAdapter"]] = None@@ -4907,8 +3517,6 @@ class YuanbaoAdapter(BasePlatformAdapter):def __init__(self, config: PlatformConfig, **kwargs: Any) -> None:super().__init__(config, Platform.YUANBAO)-- # Credentials / endpoints from config.extra (populated by config.py from env/yaml)_extra = config.extra or {}self._app_key: str = (_extra.get("app_id") or "").strip()self._app_secret: str = (_extra.get("app_secret") or "").strip()@@ -4916,130 +3524,59 @@ class YuanbaoAdapter(BasePlatformAdapter):self._ws_url: str = (_extra.get("ws_url") or DEFAULT_WS_GATEWAY_URL).strip()self._api_domain: str = (_extra.get("api_domain") or DEFAULT_API_DOMAIN).rstrip("/")self._route_env: str = (_extra.get("route_env") or "").strip()-- # Bounded concurrency for inbound media resolve/download.- # See _DEFAULT_RESOLVE_CONCURRENCY for rationale; clamped to [min, max]- # so a misconfigured value cannot hammer the resource backend nor- # accidentally drop below sequential behavior.+ # Media resolve concurrency clamped to [min, max] so a bad config can't hammer the backend.try:_raw_concurrency = int(_extra.get("media_resolve_concurrency", _DEFAULT_RESOLVE_CONCURRENCY))except (TypeError, ValueError):_raw_concurrency = _DEFAULT_RESOLVE_CONCURRENCY- self.media_resolve_concurrency: int = max(- _MIN_RESOLVE_CONCURRENCY,- min(_MAX_RESOLVE_CONCURRENCY, _raw_concurrency),- )-- # Core managers (UML composition)+ self.media_resolve_concurrency: int = max(_MIN_RESOLVE_CONCURRENCY, min(_MAX_RESOLVE_CONCURRENCY, _raw_concurrency))self._connection: ConnectionManager = ConnectionManager(self)self._outbound: OutboundManager = OutboundManager(self)-- # Inbound dispatch tasks — tracked so disconnect() can cancel them- self._inbound_tasks: set[asyncio.Task] = set()-- # Set of background tasks — prevent GC from collecting fire-and-forget tasks- self._background_tasks: set[asyncio.Task] = set()-- # Member cache: group_code -> (updated_ts, [{"user_id":..., "nickname":..., ...}, ...])- # Populated by get_group_member_list(), used by @mention resolution.- # Entries older than MEMBER_CACHE_TTL_S are treated as stale.+ self._inbound_tasks: set[asyncio.Task] = set() # cancelled by disconnect()+ self._background_tasks: set[asyncio.Task] = set() # keeps fire-and-forget tasks alive+ # group_code -> (updated_ts, members); used by @mention resolution, stale after MEMBER_CACHE_TTL_Sself._member_cache: Dict[str, Tuple[float, list]] = {}- self.MEMBER_CACHE_TTL_S: float = 300.0 # 5 minutes-- # Inbound message deduplication (WS reconnect / network jitter)- self._dedup = MessageDeduplicator(ttl_seconds=300)-- # Group chat sequential dispatch queue (session_key → asyncio.Queue).- self._group_queues: Dict[str, asyncio.Queue] = {}-- # Recall support: track which msg_id is being processed per session_key- # so RecallGuardMiddleware can detect "currently processing" messages.+ self.MEMBER_CACHE_TTL_S: float = 300.0+ self._dedup = MessageDeduplicator(ttl_seconds=300) # WS reconnect / network jitter+ self._group_queues: Dict[str, asyncio.Queue] = {} # session_key → sequential dispatch queue+ # Recall support: msg_id/text being processed per session_key (RecallGuardMiddleware), plus a+ # bounded msg_id → content cache for content-match redaction when rows lack a message_id.self._processing_msg_ids: Dict[str, str] = {}self._processing_msg_texts: Dict[str, str] = {}- # Bounded cache of msg_id → attributed content for recent messages.- # Used by _patch_transcript as content-match fallback when transcript- # entries lack a message_id field (agent-processed @bot messages).self._msg_content_cache: Dict[str, str] = {}- # Reply-to dedup: inbound_msg_id -> expire_ts- # ------------------------------------------------------------------- # Access control policy (DM / Group) — scoped reads (#93522)- # ------------------------------------------------------------------- dm_policy: str = (- _extra.get("dm_policy")- or _yb_secret("YUANBAO_DM_POLICY")- or "pairing"- ).strip().lower()-- _dm_allow_from_raw: str = (- _extra.get("dm_allow_from")- or _yb_secret("YUANBAO_DM_ALLOW_FROM", "")- )- dm_allow_from: list[str] = [x.strip() for x in _dm_allow_from_raw.split(",") if x.strip()]-- group_policy: str = (- _extra.get("group_policy")- or _yb_secret("YUANBAO_GROUP_POLICY")- or "pairing"- ).strip().lower()-- _group_allow_from_raw: str = (- _extra.get("group_allow_from")- or _yb_secret("YUANBAO_GROUP_ALLOW_FROM", "")- )- group_allow_from: list[str] = [x.strip() for x in _group_allow_from_raw.split(",") if x.strip()]-+ def _policy(kind: str) -> tuple[str, list[str]]:+ policy = (_extra.get(f"{kind}_policy") or _yb_secret(f"YUANBAO_{kind.upper()}_POLICY") or "pairing").strip().lower()+ raw = _extra.get(f"{kind}_allow_from") or _yb_secret(f"YUANBAO_{kind.upper()}_ALLOW_FROM", "")+ return policy, [x.strip() for x in raw.split(",") if x.strip()]+ dm_policy, dm_allow_from = _policy("dm")+ group_policy, group_allow_from = _policy("group")self._access_policy = AccessPolicy(- dm_policy=dm_policy,- dm_allow_from=dm_allow_from,- group_policy=group_policy,- group_allow_from=group_allow_from,+ dm_policy=dm_policy, dm_allow_from=dm_allow_from,+ group_policy=group_policy, group_allow_from=group_allow_from,)-- # Group query service (AI tool backing)self._group_query = GroupQueryService(self)-- # Inbound message processing pipeline (middleware pattern)self._inbound_pipeline: InboundPipeline = InboundPipelineBuilder.build()-- # ------------------------------------------------------------------- # Auto-sethome: first user to message the bot becomes the owner.- # If no home channel is configured, the first conversation will be- # automatically set as the home channel. When the existing home- # channel is a group chat (group:xxx), it stays eligible for- # upgrade — the first DM will override it with direct:xxx.- # ------------------------------------------------------------------+ # Auto-sethome stays open when no home is set or the home is a group (upgradable by first DM)._existing_home = os.getenv("YUANBAO_HOME_CHANNEL") or (config.home_channel.chat_id if config.home_channel else "")self._auto_sethome_done: bool = bool(_existing_home) and not _existing_home.startswith("group:")- # ------------------------------------------------------------------- # Task tracking helper- # -------------------------------------------------------------------def _track_task(self, task: asyncio.Task) -> asyncio.Task:"""Register a fire-and-forget task so it won't be GC'd prematurely."""self._background_tasks.add(task)task.add_done_callback(self._background_tasks.discard)return task- # ------------------------------------------------------------------- # Abstract method implementations- # -------------------------------------------------------------------@propertydef enforces_own_access_policy(self) -> bool:"""Yuanbao gates DM/group access at intake via dm_policy/group_policy."""return Truedef _sender_may_designate_home(self, ctx: InboundContext) -> bool:- """True when the sender may persist ``YUANBAO_HOME_CHANNEL``.-- Intake-only pairing forwards are excluded until the sender is on the- strict allowlist, has explicit open-world opt-in, or is approved in the- pairing store.- """+ """Sender may persist YUANBAO_HOME_CHANNEL: strict allowlist, open opt-in, or pairing-approved+ (intake-only pairing forwards are excluded)."""policy: AccessPolicy = self._access_policysender = str(ctx.from_account or "").strip()if not sender:@@ -5049,7 +3586,6 @@ class YuanbaoAdapter(BasePlatformAdapter):return Trueif policy.dm_policy == "pairing":from gateway.pairing import PairingStore-return PairingStore().is_approved(Platform.YUANBAO.value, sender)return Falseif ctx.chat_type == "group":@@ -5064,78 +3600,51 @@ class YuanbaoAdapter(BasePlatformAdapter):return Falseasync def connect(self, *, is_reconnect: bool = False) -> bool:- """Connect to Yuanbao WS gateway and authenticate.-- Delegates to ConnectionManager.open().- """ok = await self._connection.open()if ok:- # Plugin-registered native handlers (ctx.register_platform_handler).- self._wire_plugin_handlers(None)+ self._wire_plugin_handlers(None) # plugin-registered native handlersreturn okasync def disconnect(self) -> None:"""Cancel background tasks and close the WebSocket connection."""if YuanbaoAdapter._active_instance is self:YuanbaoAdapter.set_active(None)-self._running = Falseself._mark_disconnected()self._release_platform_lock()-- # Delegate to managersawait self._connection.close()await self._outbound.close()-- # Cancel all in-flight inbound dispatch tasksfor task in list(self._inbound_tasks):if not task.done():task.cancel()self._inbound_tasks.clear()-self._group_queues.clear()-logger.info("[%s] Disconnected", self.name)async def send(- self,- chat_id: str,- content: str,- reply_to: Optional[str] = None,- metadata: Optional[Dict[str, Any]] = None,- group_code: str = "",+ self, chat_id: str, content: str, reply_to: Optional[str] = None,+ metadata: Optional[Dict[str, Any]] = None, group_code: str = "",) -> SendResult:- """Send text message with auto-chunking. Delegates to OutboundManager."""- return await self._outbound.send_text(chat_id, content, reply_to, group_code=group_code)+ return await self._outbound.sender.send_text(chat_id, content, reply_to, group_code=group_code)async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:- """Return basic chat metadata derived from the chat_id prefix.-- chat_id conventions:- "group:<group_code>" → group chat- "direct:<account>" → C2C / direct message (default)-- TODO (T06): fetch real chat name/member-count from Yuanbao API.- """+ """Chat metadata from the chat_id prefix (``group:`` → group, else dm)."""if chat_id.startswith("group:"):return {"name": chat_id, "type": "group"}return {"name": chat_id, "type": "dm"}async def send_typing(self, chat_id: str, metadata: Optional[dict] = None) -> None:- """Send "typing" status heartbeat (RUNNING). Delegates to OutboundManager."""+ """Start the RUNNING heartbeat."""try:- await self._outbound.start_typing(chat_id)+ await self._outbound.heartbeat.start(chat_id)except Exception:passasync def stop_typing(self, chat_id: str) -> None:- """Stop the RUNNING heartbeat loop without sending FINISH immediately.-- FINISH is sent by send() after actual message delivery to ensure correct ordering:- RUNNING... -> message arrives -> FINISH.- """+ """Stop RUNNING without FINISH — send() emits FINISH after delivery so ordering is+ RUNNING… → message → FINISH."""try:- await self._outbound.stop_typing(chat_id, send_finish=False)+ await self._outbound.heartbeat.stop(chat_id, send_finish=False)except Exception:pass@@ -5147,52 +3656,24 @@ class YuanbaoAdapter(BasePlatformAdapter):await super()._process_message_background(event, session_key)finally:self._outbound.cancel_slow_notifier(chat_id)- # Clear the RecallGuard tracking entries for this message only if- # our msg_id is still current. A concurrent pending message may- # have already overwritten the entry in _dispatch_inbound_event- # while we were running; in that case the drain task owns it and- # we must not clear it. Id-less events (internal/synthetic- # messages, pushes without a msg_id) never wrote a tracking entry- # in _dispatch_inbound_event, so they must never pop either — the- # entry they see belongs to a concurrently-queued id-bearing- # message whose drain task still needs it for recall matching.+ # Clear RecallGuard tracking only if our msg_id is still current: a concurrent message+ # may have overwritten it (the drain task then owns it), and id-less events never+ # wrote one, so they must never pop another message's entry.msg_id = event.message_idif msg_id and self._processing_msg_ids.get(session_key) == msg_id:self._processing_msg_ids.pop(session_key, None)self._processing_msg_texts.pop(session_key, None)- # ------------------------------------------------------------------- # Group query (delegate to GroupQueryService)- # -------------------------------------------------------------------async def query_group_info(self, group_code: str) -> Optional[dict]:- """Query group info (delegates to GroupQueryService)."""return await self._group_query.query_group_info_raw(group_code)- async def get_group_member_list(- self, group_code: str, offset: int = 0, limit: int = 200- ) -> Optional[dict]:- """Query group member list (delegates to GroupQueryService)."""+ async def get_group_member_list(self, group_code: str, offset: int = 0, limit: int = 200) -> Optional[dict]:return await self._group_query.get_group_member_list_raw(group_code, offset=offset, limit=limit)- # ------------------------------------------------------------------- # DM active private chat + access control- # -------------------------------------------------------------------- DM_MAX_CHARS = 10000 # DM text limit+ DM_MAX_CHARS = 10000async def send_dm(self, user_id: str, text: str, group_code: str = "") -> SendResult:- """- Actively send C2C private chat message.-- Args:- user_id: Target user ID- text: Message text (limit 10000 characters)- group_code: Source group code (for group-originated DM context)-- Returns:- SendResult- """+ """Proactive C2C DM (text capped at DM_MAX_CHARS); group_code marks a group-originated DM."""if not self._access_policy.is_dm_allowed(user_id):return SendResult(success=False, error="DM access denied for this user")if len(text) > self.DM_MAX_CHARS:@@ -5200,90 +3681,37 @@ class YuanbaoAdapter(BasePlatformAdapter):chat_id = f"direct:{user_id}"return await self.send(chat_id, text, group_code=group_code)- # ------------------------------------------------------------------- # Media send methods- # -------------------------------------------------------------------+ # Media sends delegate to MessageSender.send_media via the named handler strategy.async def send_image(- self,- chat_id: str,- image_url: str,- caption: Optional[str] = None,- reply_to: Optional[str] = None,- metadata: Optional[dict] = None,- **kwargs: Any,+ self, chat_id: str, image_url: str, caption: Optional[str] = None,+ reply_to: Optional[str] = None, metadata: Optional[dict] = None, **kwargs: Any,) -> SendResult:- """Send image message (URL). Delegates to OutboundManager via ImageUrlHandler."""- return await self._outbound.send_media(- chat_id, "image_url",- reply_to=reply_to, caption=caption, image_url=image_url,- **kwargs,+ return await self._outbound.sender.send_media(+ chat_id, "image_url", reply_to=reply_to, caption=caption, image_url=image_url, **kwargs,)async def send_image_file(- self,- chat_id: str,- image_path: str,- caption: Optional[str] = None,- reply_to: Optional[str] = None,- metadata: Optional[dict] = None,- **kwargs: Any,- ) -> SendResult:- """Send local image file. Delegates to OutboundManager via ImageFileHandler."""- return await self._outbound.send_media(- chat_id, "image_file",- reply_to=reply_to, caption=caption, image_path=image_path,- **kwargs,- )-- async def send_file(- self,- chat_id: str,- file_url: str,- filename: Optional[str] = None,- reply_to: Optional[str] = None,- metadata: Optional[dict] = None,- **kwargs: Any,+ self, chat_id: str, image_path: str, caption: Optional[str] = None,+ reply_to: Optional[str] = None, metadata: Optional[dict] = None, **kwargs: Any,) -> SendResult:- """Send file message (URL). Delegates to OutboundManager via FileUrlHandler."""- return await self._outbound.send_media(- chat_id, "file_url",- reply_to=reply_to, file_url=file_url, filename=filename,- **kwargs,+ return await self._outbound.sender.send_media(+ chat_id, "image_file", reply_to=reply_to, caption=caption, image_path=image_path, **kwargs,)async def send_sticker(- self,- chat_id: str,- sticker_name: Optional[str] = None,- face_index: Optional[int] = None,- reply_to: Optional[str] = None,- **kwargs: Any,+ self, chat_id: str, sticker_name: Optional[str] = None, face_index: Optional[int] = None,+ reply_to: Optional[str] = None, **kwargs: Any,) -> SendResult:- """Send sticker/emoji. Delegates to OutboundManager via StickerHandler."""- return await self._outbound.send_media(- chat_id, "sticker",- reply_to=reply_to,- sticker_name=sticker_name, face_index=face_index,- **kwargs,+ return await self._outbound.sender.send_media(+ chat_id, "sticker", reply_to=reply_to, sticker_name=sticker_name, face_index=face_index, **kwargs,)async def send_document(- self,- chat_id: str,- file_path: str,- filename: Optional[str] = None,- caption: Optional[str] = None,- reply_to: Optional[str] = None,- metadata: Optional[dict] = None,- **kwargs: Any,+ self, chat_id: str, file_path: str, filename: Optional[str] = None, caption: Optional[str] = None,+ reply_to: Optional[str] = None, metadata: Optional[dict] = None, **kwargs: Any,) -> SendResult:- """Send local file (document). Delegates to OutboundManager via DocumentHandler."""- return await self._outbound.send_media(- chat_id, "document",- reply_to=reply_to, caption=caption,- file_path=file_path, filename=filename,- **kwargs,+ return await self._outbound.sender.send_media(+ chat_id, "document", reply_to=reply_to, caption=caption, file_path=file_path, filename=filename, **kwargs,)async def _get_cached_token(self) -> dict:@@ -5293,25 +3721,10 @@ class YuanbaoAdapter(BasePlatformAdapter):route_env=self._route_env,)- def get_status(self) -> dict:- """Return a snapshot of the current connection status."""- conn = self._connection- return {- "connected": conn.is_connected,- "bot_id": self._bot_id,- "connect_id": conn.connect_id,- "reconnect_attempts": conn.reconnect_attempts,- "ws_url": self._ws_url,- }---# ----------------------------------------------------------------------------# Module-level thin delegates (preserve import compatibility for external callers)-# ---------------------------------------------------------------------------+# Module-level delegates kept for external importers (tools/send_message_tool, tools/yuanbao_tools).def get_active_adapter() -> Optional["YuanbaoAdapter"]:- """Delegate to ``YuanbaoAdapter.get_active()``."""return YuanbaoAdapter.get_active()@@ -5321,5 +3734,4 @@ async def send_yuanbao_direct(message: str,media_files: Optional[List[Tuple[str, bool]]] = None,) -> Dict[str, Any]:- """Delegate to ``OutboundManager.send_direct``."""- return await adapter._outbound.send_direct(chat_id, message, media_files)+ return await adapter._outbound.sender.send_direct(chat_id, message, media_files)diff --git a/gateway/platforms/yuanbao_media.py b/gateway/platforms/yuanbao_media.pyindex 1ca803b8792..af5da3a6805 100644--- a/gateway/platforms/yuanbao_media.py+++ b/gateway/platforms/yuanbao_media.py@@ -1,18 +1,15 @@"""yuanbao_media.py — 元宝平台媒体处理模块-提供 COS 上传、文件下载、TIM 媒体消息构建等功能。-移植自 TypeScript 版 media.ts(yuanbao-openclaw-plugin),-使用 httpx 替代 cos-nodejs-sdk-v5,避免引入额外 SDK 依赖。+提供 COS 上传、文件下载、TIM 媒体消息构建等功能。移植自 TypeScript 版 media.ts+(yuanbao-openclaw-plugin),使用 httpx 替代 cos-nodejs-sdk-v5。COS 上传流程:- 1. 调用 genUploadInfo 获取临时凭证(tmpSecretId/tmpSecretKey/sessionToken)- 2. 用临时凭证通过 HMAC-SHA1 签名构建 Authorization 头+ 1. genUploadInfo 获取临时凭证(tmpSecretId/tmpSecretKey/sessionToken)+ 2. 临时凭证 HMAC-SHA1 签名构建 Authorization 头3. HTTP PUT 上传到 COS-TIM 消息体构建:- - buildImageMsgBody() → TIMImageElem- - buildFileMsgBody() → TIMFileElem+TIM 消息体:build_image_msg_body() → TIMImageElem,build_file_msg_body() → TIMFileElem"""from __future__ import annotations@@ -31,30 +28,19 @@ import httpxlogger = logging.getLogger(__name__)-# ============ 常量 ============-UPLOAD_INFO_PATH = "/api/resource/genUploadInfo"DEFAULT_API_DOMAIN = "yuanbao.tencent.com"DEFAULT_MAX_SIZE_MB = 50-# COS 加速域名后缀(优先使用全球加速)+# COS 加速域名(优先使用全球加速)COS_USE_ACCELERATE = True-# ============ 类型映射 ============-# MIME → image_format 数字(TIM 协议字段)_MIME_TO_IMAGE_FORMAT: dict[str, int] = {- "image/jpeg": 1,- "image/jpg": 1,- "image/gif": 2,- "image/png": 3,- "image/bmp": 4,- "image/webp": 255,- "image/heic": 255,- "image/tiff": 255,+ "image/jpeg": 1, "image/jpg": 1, "image/gif": 2, "image/png": 3, "image/bmp": 4,+ "image/webp": 255, "image/heic": 255, "image/tiff": 255,}-# 文件扩展名 → MIME_EXT_TO_MIME: dict[str, str] = {".jpg": "image/jpeg",".jpeg": "image/jpeg",@@ -82,22 +68,17 @@ _EXT_TO_MIME: dict[str, str] = {".ogg": "audio/ogg",".webm": "video/webm",}+_IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".heic", ".tiff", ".ico"}-# ============ 工具函数 ============-def guess_mime_type(filename: str) -> str:"""根据文件扩展名猜测 MIME 类型。"""- ext = os.path.splitext(filename)[-1].lower()- return _EXT_TO_MIME.get(ext, "application/octet-stream")+ return _EXT_TO_MIME.get(os.path.splitext(filename)[-1].lower(), "application/octet-stream")def is_image(filename: str, mime_type: str = "") -> bool:- """判断是否为图片类型。"""- if mime_type.startswith("image/"):- return True- ext = os.path.splitext(filename)[-1].lower()- return ext in {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".heic", ".tiff", ".ico"}+ """判断是否为图片类型(MIME 前缀或扩展名)。"""+ return mime_type.startswith("image/") or os.path.splitext(filename)[-1].lower() in _IMAGE_EXTSdef get_image_format(mime_type: str) -> int:@@ -106,39 +87,29 @@ def get_image_format(mime_type: str) -> int:def md5_hex(data: bytes) -> str:- """计算 MD5 十六进制摘要。"""return hashlib.md5(data).hexdigest()def generate_file_id() -> str:- """生成随机文件 ID(32 位 hex)。"""+ """随机文件 ID(32 位 hex)。"""return secrets.token_hex(16)-# ============ 图片尺寸解析(纯 Python,无需 Pillow) ============def parse_image_size(data: bytes) -> Optional[dict[str, int]]:- """- 解析图片宽高(支持 JPEG/PNG/GIF/WebP),无需第三方依赖。- 返回 {"width": w, "height": h} 或 None(无法识别)。- """- return (- _parse_png_size(data)- or _parse_jpeg_size(data)- or _parse_gif_size(data)- or _parse_webp_size(data)- )+ """解析图片宽高(JPEG/PNG/GIF/WebP),返回 {"width", "height"} 或 None。"""+ return _parse_png_size(data) or _parse_jpeg_size(data) or _parse_gif_size(data) or _parse_webp_size(data)+++def _wh(w: int, h: int) -> dict[str, int]:+ return {"width": w, "height": h}def _parse_png_size(buf: bytes) -> Optional[dict[str, int]]:- if len(buf) < 24:- return None- if buf[:4] != b"\x89PNG":+ if len(buf) < 24 or buf[:4] != b"\x89PNG":return None- w = struct.unpack(">I", buf[16:20])[0]- h = struct.unpack(">I", buf[20:24])[0]- return {"width": w, "height": h}+ return _wh(*struct.unpack(">II", buf[16:24]))def _parse_jpeg_size(buf: bytes) -> Optional[dict[str, int]]:@@ -149,11 +120,9 @@ def _parse_jpeg_size(buf: bytes) -> Optional[dict[str, int]]:if buf[i] != 0xFF:i += 1continue- marker = buf[i + 1]- if marker in {0xC0, 0xC2}:- h = struct.unpack(">H", buf[i + 5: i + 7])[0]- w = struct.unpack(">H", buf[i + 7: i + 9])[0]- return {"width": w, "height": h}+ if buf[i + 1] in {0xC0, 0xC2}: # SOF0 / SOF2: height then width+ h, w = struct.unpack(">HH", buf[i + 5: i + 9])+ return _wh(w, h)if i + 3 < len(buf):i += 2 + struct.unpack(">H", buf[i + 2: i + 4])[0]else:@@ -162,64 +131,40 @@ def _parse_jpeg_size(buf: bytes) -> Optional[dict[str, int]]:def _parse_gif_size(buf: bytes) -> Optional[dict[str, int]]:- if len(buf) < 10:+ if len(buf) < 10 or buf[:6].decode("ascii", errors="replace") not in {"GIF87a", "GIF89a"}:return None- sig = buf[:6].decode("ascii", errors="replace")- if sig not in {"GIF87a", "GIF89a"}:- return None- w = struct.unpack("<H", buf[6:8])[0]- h = struct.unpack("<H", buf[8:10])[0]- return {"width": w, "height": h}+ return _wh(*struct.unpack("<HH", buf[6:10]))def _parse_webp_size(buf: bytes) -> Optional[dict[str, int]]:- if len(buf) < 16:- return None- if buf[:4] != b"RIFF" or buf[8:12] != b"WEBP":+ if len(buf) < 16 or buf[:4] != b"RIFF" or buf[8:12] != b"WEBP":return Nonechunk = buf[12:16].decode("ascii", errors="replace")if chunk == "VP8 ":- if len(buf) >= 30 and buf[23] == 0x9D and buf[24] == 0x01 and buf[25] == 0x2A:- w = struct.unpack("<H", buf[26:28])[0] & 0x3FFF- h = struct.unpack("<H", buf[28:30])[0] & 0x3FFF- return {"width": w, "height": h}+ if len(buf) >= 30 and buf[23:26] == b"\x9d\x01\x2a":+ w, h = struct.unpack("<HH", buf[26:30])+ return _wh(w & 0x3FFF, h & 0x3FFF)elif chunk == "VP8L":if len(buf) >= 25 and buf[20] == 0x2F:bits = struct.unpack("<I", buf[21:25])[0]- w = (bits & 0x3FFF) + 1- h = ((bits >> 14) & 0x3FFF) + 1- return {"width": w, "height": h}- elif chunk == "VP8X":- if len(buf) >= 30:- w = (buf[24] | (buf[25] << 8) | (buf[26] << 16)) + 1- h = (buf[27] | (buf[28] << 8) | (buf[29] << 16)) + 1- return {"width": w, "height": h}+ return _wh((bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1)+ elif chunk == "VP8X" and len(buf) >= 30:+ return _wh(int.from_bytes(buf[24:27], "little") + 1, int.from_bytes(buf[27:30], "little") + 1)return None# ============ URL 下载 ============-async def download_url(- url: str,- max_size_mb: int = DEFAULT_MAX_SIZE_MB,-) -> tuple[bytes, str]:- """- 下载 URL 内容,返回 (bytes, content_type)。-- Args:- url: HTTP(S) URL- max_size_mb: 最大允许大小(MB),超过则抛出异常-- Returns:- (data_bytes, content_type_string)+async def download_url(url: str, max_size_mb: int = DEFAULT_MAX_SIZE_MB) -> tuple[bytes, str]:+ """下载 URL 内容,返回 (bytes, content_type)。Raises:- ValueError: 内容超过大小限制+ ValueError: 内容超过 max_size_mb,或 URL / 重定向目标被 SSRF 防护拦截httpx.HTTPError: 网络/HTTP 错误"""- # SSRF protection: yuanbao downloads model-supplied and inbound URLs- # server-side. Reject private/internal targets up front, and re-validate- # every redirect hop so a public URL can't 302 to http://169.254.169.254/.+ # SSRF protection: yuanbao downloads model-supplied and inbound URLs server-side.+ # Reject private/internal targets up front, and re-validate every redirect hop so a+ # public URL can't 302 to http://169.254.169.254/.from tools.url_safety import create_ssrf_safe_async_client, is_safe_urlif not is_safe_url(url):@@ -229,49 +174,46 @@ async def download_url(if response.is_redirect and response.next_request:redirect_url = str(response.next_request.url)if not is_safe_url(redirect_url):- raise ValueError(- f"Blocked redirect to private/internal address: {redirect_url}"- )+ raise ValueError(f"Blocked redirect to private/internal address: {redirect_url}")max_bytes = max_size_mb * 1024 * 1024async with create_ssrf_safe_async_client(- timeout=30.0,- follow_redirects=True,- event_hooks={"response": [_redirect_guard]},+ timeout=30.0, follow_redirects=True, event_hooks={"response": [_redirect_guard]},) as client:- # 先 HEAD 检查大小+ # HEAD 预检大小;部分服务器不支持 HEAD,忽略try:head = await client.head(url)content_length = int(head.headers.get("content-length", 0) or 0)if content_length > 0 and content_length > max_bytes:- raise ValueError(- f"文件过大: {content_length / 1024 / 1024:.1f} MB > {max_size_mb} MB"- )+ raise ValueError(f"文件过大: {content_length / 1024 / 1024:.1f} MB > {max_size_mb} MB")except httpx.HTTPStatusError:- pass # 部分服务器不支持 HEAD,忽略+ pass- # GET 下载(流式读取,防止超限)+ # 流式 GET,防止超限async with client.stream("GET", url) as resp:resp.raise_for_status()-content_type = resp.headers.get("content-type", "").split(";")[0].strip()-chunks: list[bytes] = []downloaded = 0async for chunk in resp.aiter_bytes(65536):downloaded += len(chunk)if downloaded > max_bytes:- raise ValueError(- f"文件过大: 已超过 {max_size_mb} MB 限制"- )+ raise ValueError(f"文件过大: 已超过 {max_size_mb} MB 限制")chunks.append(chunk)-- data = b"".join(chunks)- return data, content_type+ return b"".join(chunks), content_type# ============ COS 鉴权(HMAC-SHA1) ============+def _hmac_sha1_hex(key: str, msg: str) -> str:+ return hmac.new(key.encode("utf-8"), msg.encode("utf-8"), hashlib.sha1).hexdigest()+++def _sorted_kv(d: dict[str, str]) -> list[tuple[str, str]]:+ """签名用 (小写 key, URL-encoded value) 按字典序排列"""+ return sorted((k.lower(), urllib.parse.quote(str(v), safe="")) for k, v in d.items())++def _cos_sign(method: str,path: str,@@ -282,74 +224,39 @@ def _cos_sign(start_time: Optional[int] = None,expire_seconds: int = 3600,) -> str:- """- 构建 COS 请求签名(q-sign-algorithm=sha1 方案)。- 参考:https://cloud.tencent.com/document/product/436/7778+ """构建 COS 请求签名(q-sign-algorithm=sha1;https://cloud.tencent.com/document/product/436/7778)。Args:- method: HTTP 方法(小写,如 "put")- path: URL 路径(URL encode 后的小写)- params: URL 查询参数 dict(用于签名)- headers: 参与签名的请求头 dict(key 需小写)- secret_id: 临时 SecretId(tmpSecretId)- secret_key: 临时 SecretKey(tmpSecretKey)- start_time: 签名起始 Unix 时间戳(默认 now)- expire_seconds: 签名有效期(秒,默认 3600)+ method / path: HTTP 方法(小写)与 URL-encoded 路径+ params / headers: 参与签名的查询参数与请求头(key 会被小写)+ secret_id / secret_key: 临时 tmpSecretId / tmpSecretKey+ start_time: 签名起始 Unix 时间戳(默认 now);expire_seconds: 有效期(秒)Returns:- Authorization header 值(完整字符串)+ Authorization header 值"""now = int(time.time())q_sign_time = f"{start_time or now};{(start_time or now) + expire_seconds}"-- # Step 1: SignKey = HMAC-SHA1(SecretKey, q-sign-time)- sign_key = hmac.new(- secret_key.encode("utf-8"),- q_sign_time.encode("utf-8"),- hashlib.sha1,- ).hexdigest()-- # Step 2: HttpString- # 参数和头部需按字典序排列,key 小写- sorted_params = sorted((k.lower(), urllib.parse.quote(str(v), safe="") ) for k, v in params.items())- sorted_headers = sorted((k.lower(), urllib.parse.quote(str(v), safe="") ) for k, v in headers.items())-- url_param_list = ";".join(k for k, _ in sorted_params)- url_params = "&".join(f"{k}={v}" for k, v in sorted_params)- header_list = ";".join(k for k, _ in sorted_headers)- header_str = "&".join(f"{k}={v}" for k, v in sorted_headers)-+ # SignKey = HMAC-SHA1(SecretKey, q-sign-time)+ sign_key = _hmac_sha1_hex(secret_key, q_sign_time)+ sorted_params = _sorted_kv(params)+ sorted_headers = _sorted_kv(headers)http_string = "\n".join([method.lower(),path,- url_params,- header_str,- "",- ])-- # Step 3: StringToSign = sha1 hash of HttpString- sha1_of_http = hashlib.sha1(http_string.encode("utf-8")).hexdigest()- string_to_sign = "\n".join([- "sha1",- q_sign_time,- sha1_of_http,+ "&".join(f"{k}={v}" for k, v in sorted_params),+ "&".join(f"{k}={v}" for k, v in sorted_headers),"",])-- # Step 4: Signature = HMAC-SHA1(SignKey, StringToSign)- signature = hmac.new(- sign_key.encode("utf-8"),- string_to_sign.encode("utf-8"),- hashlib.sha1,- ).hexdigest()-+ string_to_sign = "\n".join(["sha1", q_sign_time, hashlib.sha1(http_string.encode("utf-8")).hexdigest(), ""])+ signature = _hmac_sha1_hex(sign_key, string_to_sign)return (f"q-sign-algorithm=sha1"f"&q-ak={secret_id}"f"&q-sign-time={q_sign_time}"f"&q-key-time={q_sign_time}"- f"&q-header-list={header_list}"- f"&q-url-param-list={url_param_list}"+ f"&q-header-list={';'.join(k for k, _ in sorted_headers)}"+ f"&q-url-param-list={';'.join(k for k, _ in sorted_params)}"f"&q-signature={signature}")@@ -365,52 +272,26 @@ async def get_cos_credentials(bot_id: str = "",route_env: str = "",) -> dict:- """- 调用 genUploadInfo 接口获取 COS 临时密钥及上传配置。+ """调用 genUploadInfo 获取 COS 临时密钥及上传配置。Args:- app_key: 应用 Key(用于 X-ID 头)- api_domain: API 域名(如 https://bot.yuanbao.tencent.com)- token: 当前有效的签票 token(X-Token 头)- filename: 待上传的文件名(含扩展名)- file_id: 客户端生成的唯一文件 ID(不传则自动生成)- bot_id: Bot 账号 ID(用于 X-ID 头)+ app_key / bot_id: X-ID 头(bot_id 优先); api_domain: 如 https://bot.yuanbao.tencent.com+ token: 当前有效签票 token(X-Token 头); file_id: 不传则自动生成Returns:- COS 上传配置 dict,包含以下字段:- bucketName (str) — COS Bucket 名称- region (str) — COS 地域- location (str) — 上传 Key(对象路径)- encryptTmpSecretId (str) — 临时 SecretId- encryptTmpSecretKey(str) — 临时 SecretKey- encryptToken (str) — SessionToken- startTime (int) — 凭证起始时间戳(Unix)- expiredTime (int) — 凭证过期时间戳(Unix)- resourceUrl (str) — 上传后的公网访问 URL- resourceID (str) — 资源 ID(可选)+ 接口 data dict:bucketName, region, location (COS key), encryptTmpSecretId,+ encryptTmpSecretKey, encryptToken, startTime, expiredTime, resourceUrl, resourceID(可选)Raises:- RuntimeError: 接口返回非 0 code 或字段缺失+ RuntimeError: 接口返回非 0 code 或 bucketName/location 缺失"""if file_id is None:file_id = generate_file_id()-upload_url = f"{api_domain.rstrip('/')}{UPLOAD_INFO_PATH}"-- headers = {- "Content-Type": "application/json",- "X-Token": token,- "X-ID": bot_id or app_key,- "X-Source": "web",- }+ headers = {"Content-Type": "application/json", "X-Token": token, "X-ID": bot_id or app_key, "X-Source": "web"}if route_env:headers["X-Route-Env"] = route_env- body = {- "fileName": filename,- "fileId": file_id,- "docFrom": "localDoc",- "docOpenId": "",- }+ body = {"fileName": filename, "fileId": file_id, "docFrom": "localDoc", "docOpenId": ""}async with httpx.AsyncClient(timeout=15.0) as client:resp = await client.post(upload_url, json=body, headers=headers)@@ -419,18 +300,11 @@ async def get_cos_credentials(code = result.get("code")if code != 0 and code is not None:- raise RuntimeError(- f"genUploadInfo 失败: code={code}, msg={result.get('msg', '')}"- )-+ raise RuntimeError(f"genUploadInfo 失败: code={code}, msg={result.get('msg', '')}")data = result.get("data") or result- required_fields = ["bucketName", "location"]- missing = [f for f in required_fields if not data.get(f)]+ missing = [f for f in ["bucketName", "location"] if not data.get(f)]if missing:- raise RuntimeError(- f"genUploadInfo 返回字段不完整: 缺少字段 {missing}"- )-+ raise RuntimeError(f"genUploadInfo 返回字段不完整: 缺少字段 {missing}")return data@@ -442,36 +316,19 @@ async def upload_to_cos(bucket: str,region: str,) -> dict:- """- 通过 httpx PUT 请求将文件上传到 COS。- 使用临时凭证(tmpSecretId/tmpSecretKey/sessionToken)构建 HMAC-SHA1 签名。+ """用临时凭证 HMAC-SHA1 签名,httpx PUT 上传到 COS。Args:- file_bytes: 文件二进制内容- filename: 文件名(用于辅助计算 MIME、UUID)- content_type: MIME 类型(如 "image/jpeg")- credentials: get_cos_credentials() 返回的 dict,包含:- encryptTmpSecretId → tmpSecretId- encryptTmpSecretKey → tmpSecretKey- encryptToken → sessionToken- location → COS key(对象路径)- resourceUrl → 上传后公网 URL- startTime → 凭证起始时间(Unix)- expiredTime → 凭证过期时间(Unix)- bucket: COS Bucket 名称(如 chatbot-1234567890)- region: COS 地域(如 ap-guangzhou)+ credentials: get_cos_credentials() 返回的 dict(encryptTmpSecretId/Key, encryptToken,+ location, resourceUrl, startTime, expiredTime)+ bucket / region: 如 chatbot-1234567890 / ap-guangzhouReturns:- 上传结果 dict,包含:- url (str) — COS 公网访问 URL- uuid (str) — 文件内容 MD5- size (int) — 文件大小(字节)- width (int, optional) — 图片宽度(仅图片)- height (int, optional) — 图片高度(仅图片)+ {url, uuid (内容 MD5), size, width?, height? (仅图片)}Raises:- httpx.HTTPStatusError: COS 返回非 2xx 状态- RuntimeError: credentials 字段缺失+ httpx.HTTPStatusError: COS 返回非 2xx+ RuntimeError: credentials 字段缺失"""secret_id: str = credentials.get("encryptTmpSecretId", "")secret_key: str = credentials.get("encryptTmpSecretKey", "")@@ -487,90 +344,45 @@ async def upload_to_cos(f"secretKey={bool(secret_key)}, location={bool(cos_key)}")- # 构建 COS 上传 URL(优先使用全球加速域名)- if COS_USE_ACCELERATE:- cos_host = f"{bucket}.cos.accelerate.myqcloud.com"- else:- cos_host = f"{bucket}.cos.{region}.myqcloud.com"-- # URL encode cos_key(保留 /)- encoded_key = urllib.parse.quote(cos_key, safe="/")- cos_url = f"https://{cos_host}/{encoded_key.lstrip('/')}"+ cos_host = f"{bucket}.cos.accelerate.myqcloud.com" if COS_USE_ACCELERATE else f"{bucket}.cos.{region}.myqcloud.com"+ encoded_key = urllib.parse.quote(cos_key, safe="/").lstrip("/")+ cos_url = f"https://{cos_host}/{encoded_key}"- # 确定 Content-Typeif not content_type or content_type == "application/octet-stream":- if is_image(filename):- content_type = guess_mime_type(filename)- else:- content_type = "application/octet-stream"+ content_type = guess_mime_type(filename) if is_image(filename) else "application/octet-stream"- # 计算文件 MD5 + sizefile_uuid = md5_hex(file_bytes)file_size = len(file_bytes)- # 参与签名的请求头- sign_headers = {- "host": cos_host,- "content-type": content_type,- "x-cos-security-token": session_token,- }-- # 计算签名有效期now = int(time.time())- sign_start = start_time if start_time else now- sign_expire = (expired_time - now) if expired_time and expired_time > now else 3600-authorization = _cos_sign(method="put",- path=f"/{encoded_key.lstrip('/')}",+ path=f"/{encoded_key}",params={},- headers=sign_headers,+ headers={"host": cos_host, "content-type": content_type, "x-cos-security-token": session_token},secret_id=secret_id,secret_key=secret_key,- start_time=sign_start,- expire_seconds=sign_expire,- )-- put_headers = {- "Authorization": authorization,- "Content-Type": content_type,- "x-cos-security-token": session_token,- }-- logger.info(- "COS PUT: bucket=%s region=%s key=%s size=%d mime=%s",- bucket, region, cos_key, file_size, content_type,+ start_time=start_time if start_time else now,+ expire_seconds=(expired_time - now) if expired_time and expired_time > now else 3600,)+ put_headers = {"Authorization": authorization, "Content-Type": content_type, "x-cos-security-token": session_token}+ logger.info("COS PUT: bucket=%s region=%s key=%s size=%d mime=%s", bucket, region, cos_key, file_size, content_type)async with httpx.AsyncClient(timeout=120.0) as client:- resp = await client.put(- cos_url,- content=file_bytes,- headers=put_headers,- )+ resp = await client.put(cos_url, content=file_bytes, headers=put_headers)resp.raise_for_status()- # 解析图片尺寸(仅图片类型)- result: dict[str, Any] = {- "url": resource_url or cos_url,- "uuid": file_uuid,- "size": file_size,- }-+ result: dict[str, Any] = {"url": resource_url or cos_url, "uuid": file_uuid, "size": file_size}if content_type.startswith("image/"):size_info = parse_image_size(file_bytes)if size_info:result["width"] = size_info["width"]result["height"] = size_info["height"]-- logger.info(- "COS 上传成功: url=%s size=%d",- result["url"], file_size,- )+ logger.info("COS 上传成功: url=%s size=%d", result["url"], file_size)return result-# ============ TIM 媒体消息构建 ============+# ============ TIM 媒体消息构建(https://cloud.tencent.com/document/product/269/2720) ============def build_image_msg_body(url: str,@@ -581,85 +393,29 @@ def build_image_msg_body(height: int = 0,mime_type: str = "",) -> list[dict]:- """- 构建腾讯 IM TIMImageElem 消息体。- 参考:https://cloud.tencent.com/document/product/269/2720-- Args:- url: 图片公网访问 URL(COS resourceUrl)- uuid: 文件 UUID(MD5 或其他唯一标识)- filename: 文件名(uuid 为空时作为备用)- size: 文件大小(字节)- width: 图片宽度(像素)- height: 图片高度(像素)- mime_type: MIME 类型(用于确定 image_format)-- Returns:- TIMImageElem 消息体列表(适合直接放入 msg_body)- """- _uuid = uuid or filename or _basename_from_url(url) or "image"- image_format = get_image_format(mime_type) if mime_type else 255-- return [- {- "msg_type": "TIMImageElem",- "msg_content": {- "uuid": _uuid,- "image_format": image_format,- "image_info_array": [- {- "type": 1, # 1 = 原图- "size": size,- "width": width,- "height": height,- "url": url,- }- ],- },- }- ]---def build_file_msg_body(- url: str,- filename: str,- uuid: Optional[str] = None,- size: int = 0,-) -> list[dict]:- """- 构建腾讯 IM TIMFileElem 消息体。- 参考:https://cloud.tencent.com/document/product/269/2720-- Args:- url: 文件公网访问 URL(COS resourceUrl)- filename: 文件名(含扩展名)- uuid: 文件 UUID(MD5 或其他唯一标识,不传则使用 filename)- size: 文件大小(字节)-- Returns:- TIMFileElem 消息体列表(适合直接放入 msg_body)- """- _uuid = uuid or filename-- return [- {- "msg_type": "TIMFileElem",- "msg_content": {- "uuid": _uuid,- "file_name": filename,- "file_size": size,- "url": url,- },- }- ]-+ """构建 TIMImageElem 消息体(可直接放入 msg_body)。uuid 缺省依次退到 filename / URL basename / "image"。"""+ return [{+ "msg_type": "TIMImageElem",+ "msg_content": {+ "uuid": uuid or filename or _basename_from_url(url) or "image",+ "image_format": get_image_format(mime_type) if mime_type else 255,+ "image_info_array": [+ {"type": 1, "size": size, "width": width, "height": height, "url": url}, # type 1 = 原图+ ],+ },+ }]+++def build_file_msg_body(url: str, filename: str, uuid: Optional[str] = None, size: int = 0) -> list[dict]:+ """构建 TIMFileElem 消息体(可直接放入 msg_body)。uuid 缺省使用 filename。"""+ return [{+ "msg_type": "TIMFileElem",+ "msg_content": {"uuid": uuid or filename, "file_name": filename, "file_size": size, "url": url},+ }]-# ============ 内部工具 ============def _basename_from_url(url: str) -> str:- """从 URL 提取文件名。"""try:- parsed = urllib.parse.urlparse(url)- return os.path.basename(parsed.path)+ return os.path.basename(urllib.parse.urlparse(url).path)except Exception:return ""diff --git a/gateway/platforms/yuanbao_proto.py b/gateway/platforms/yuanbao_proto.pyindex 4eeb54c5559..fce9585d081 100644--- a/gateway/platforms/yuanbao_proto.py+++ b/gateway/platforms/yuanbao_proto.py@@ -9,9 +9,8 @@ yuanbao_proto.py - Yuanbao WebSocket 协议编解码(纯 Python 实现)└── InboundMessagePush / SendC2CMessageReq / SendGroupMessageReq / ...(trpc.yuanbao.yuanbao_conn.yuanbao_openclaw_proxy.*)-注意:conn 层(ConnMsg)本身是标准 protobuf,不是自定义二进制格式。- conn.proto 注释里的自定义格式(magic+head_len+body_len)仅用于 quic/tcp,- WebSocket 直接传 ConnMsg protobuf bytes(无粘包问题,每个 ws frame = 一条消息)。+注意:conn 层(ConnMsg)本身是标准 protobuf,不是自定义二进制格式;conn.proto 注释里的+magic+head_len+body_len 格式仅用于 quic/tcp。WebSocket 每个 frame = 一条 ConnMsg protobuf。实现方式:手写 varint / protobuf wire-format 编解码,不依赖第三方 protobuf 库。"""@@ -24,10 +23,6 @@ from typing import Optionallogger = logging.getLogger(__name__)-# ============================================================-# Debug 开关-# ============================================================-DEBUG_MODE = False@@ -42,56 +37,32 @@ def _dbg(label: str, data: bytes) -> None:# 常量# ============================================================-# conn 层消息类型枚举(ConnMsg.Head.cmd_type)+# conn 层消息类型(ConnMsg.Head.cmd_type)PB_MSG_TYPES = {- "ConnMsg": "trpc.yuanbao.conn_common.ConnMsg",- "AuthBindReq": "trpc.yuanbao.conn_common.AuthBindReq",- "AuthBindRsp": "trpc.yuanbao.conn_common.AuthBindRsp",- "PingReq": "trpc.yuanbao.conn_common.PingReq",- "PingRsp": "trpc.yuanbao.conn_common.PingRsp",- "KickoutMsg": "trpc.yuanbao.conn_common.KickoutMsg",- "DirectedPush": "trpc.yuanbao.conn_common.DirectedPush",- "PushMsg": "trpc.yuanbao.conn_common.PushMsg",+ n: f"trpc.yuanbao.conn_common.{n}"+ for n in ("ConnMsg", "AuthBindReq", "AuthBindRsp", "PingReq", "PingRsp", "KickoutMsg", "DirectedPush", "PushMsg")}-# cmd_type 枚举-CMD_TYPE = {- "Request": 0, # 上行请求- "Response": 1, # 上行请求的回包- "Push": 2, # 下行推送- "PushAck": 3, # 下行推送的回包(ACK)-}+# cmd_type: 上行请求 / 请求回包 / 下行推送 / 推送 ACK+CMD_TYPE = {"Request": 0, "Response": 1, "Push": 2, "PushAck": 3}-# 内置命令字-CMD = {- "AuthBind": "auth-bind",- "Ping": "ping",- "Kickout": "kickout",- "UpdateMeta": "update-meta",-}--# 内置模块名-MODULE = {- "ConnAccess": "conn_access",-}+# 内置命令字 / 模块名+CMD = {"AuthBind": "auth-bind", "Ping": "ping", "Kickout": "kickout", "UpdateMeta": "update-meta"}+MODULE = {"ConnAccess": "conn_access"}-# biz 层服务/方法映射-# TS client uses the short name 'yuanbao_openclaw_proxy' (not the full package path)+# biz 层服务/方法映射。TS client 使用短名 'yuanbao_openclaw_proxy'(非完整包路径)。_BIZ_PKG = "yuanbao_openclaw_proxy"BIZ_SERVICES = {- "InboundMessagePush": f"{_BIZ_PKG}.InboundMessagePush",- "SendC2CMessageReq": f"{_BIZ_PKG}.SendC2CMessageReq",- "SendC2CMessageRsp": f"{_BIZ_PKG}.SendC2CMessageRsp",- "SendGroupMessageReq": f"{_BIZ_PKG}.SendGroupMessageReq",- "SendGroupMessageRsp": f"{_BIZ_PKG}.SendGroupMessageRsp",- "QueryGroupInfoReq": f"{_BIZ_PKG}.QueryGroupInfoReq",- "QueryGroupInfoRsp": f"{_BIZ_PKG}.QueryGroupInfoRsp",- "GetGroupMemberListReq": f"{_BIZ_PKG}.GetGroupMemberListReq",- "GetGroupMemberListRsp": f"{_BIZ_PKG}.GetGroupMemberListRsp",- "SendPrivateHeartbeatReq": f"{_BIZ_PKG}.SendPrivateHeartbeatReq",- "SendPrivateHeartbeatRsp": f"{_BIZ_PKG}.SendPrivateHeartbeatRsp",- "SendGroupHeartbeatReq": f"{_BIZ_PKG}.SendGroupHeartbeatReq",- "SendGroupHeartbeatRsp": f"{_BIZ_PKG}.SendGroupHeartbeatRsp",+ n: f"{_BIZ_PKG}.{n}"+ for n in (+ "InboundMessagePush",+ "SendC2CMessageReq", "SendC2CMessageRsp",+ "SendGroupMessageReq", "SendGroupMessageRsp",+ "QueryGroupInfoReq", "QueryGroupInfoRsp",+ "GetGroupMemberListReq", "GetGroupMemberListRsp",+ "SendPrivateHeartbeatReq", "SendPrivateHeartbeatRsp",+ "SendGroupHeartbeatReq", "SendGroupHeartbeatRsp",+ )}# openclaw instance_id(固定值 17)@@ -123,17 +94,16 @@ def next_seq_no() -> int:# Protobuf wire-format 基础工具(手写,不依赖 google.protobuf)# ============================================================-# wire typesWT_VARINT = 0WT_64BIT = 1WT_LEN = 2WT_32BIT = 5+_FIXED_SIZE = {WT_64BIT: 8, WT_32BIT: 4}def _encode_varint(value: int) -> bytes:- """将非负整数编码为 protobuf varint"""+ """将整数编码为 protobuf varint(负数按 64-bit two's complement)"""if value < 0:- # 处理有符号负数(int32/int64 用 two's complement,64-bit)value = value & 0xFFFFFFFFFFFFFFFFout = []while True:@@ -165,35 +135,36 @@ def _decode_varint(data: bytes, pos: int) -> tuple[int, int]:def _encode_field(field_number: int, wire_type: int, value: bytes) -> bytes:"""编码一个 protobuf field(tag + value)"""- tag = (field_number << 3) | wire_type- return _encode_varint(tag) + value+ return _encode_varint((field_number << 3) | wire_type) + valuedef _encode_string(s: str) -> bytes:- """编码 protobuf string 字段的 value 部分(length-prefixed UTF-8)"""+ """length-prefixed UTF-8 string value"""encoded = s.encode("utf-8")return _encode_varint(len(encoded)) + encoded-def _encode_bytes(b: bytes) -> bytes:- """编码 protobuf bytes 字段的 value 部分(length-prefixed)"""+def _encode_message(b: bytes) -> bytes:+ """length-prefixed bytes / 嵌套 message value"""return _encode_varint(len(b)) + b-def _encode_message(b: bytes) -> bytes:- """编码嵌套 message(length-prefixed)"""- return _encode_varint(len(b)) + b+# 完整 field 编码快捷方式:string / varint / 嵌套 message+def _s(fn: int, s: str) -> bytes:+ return _encode_field(fn, WT_LEN, _encode_string(s))+++def _v(fn: int, n: int) -> bytes:+ return _encode_field(fn, WT_VARINT, _encode_varint(n))+++def _m(fn: int, b: bytes) -> bytes:+ return _encode_field(fn, WT_LEN, _encode_message(b))def _parse_fields(data: bytes) -> list[tuple[int, int, bytes | int]]:- """- 解析 protobuf message 的所有字段,返回 [(field_number, wire_type, raw_value), ...]- raw_value:- - WT_VARINT: int- - WT_LEN: bytes- - WT_64BIT: bytes (8 bytes)- - WT_32BIT: bytes (4 bytes)- """+ """解析 message 的所有字段 → [(field_number, wire_type, raw_value)];+ raw_value 为 int(VARINT)或 bytes(LEN / 64BIT / 32BIT)。"""fields = []pos = 0n = len(data)@@ -203,124 +174,116 @@ def _parse_fields(data: bytes) -> list[tuple[int, int, bytes | int]]:wire_type = tag & 0x07if wire_type == WT_VARINT:val, pos = _decode_varint(data, pos)- fields.append((field_number, wire_type, val))elif wire_type == WT_LEN:length, pos = _decode_varint(data, pos)val = data[pos: pos + length]pos += length- fields.append((field_number, wire_type, val))- elif wire_type == WT_64BIT:- val = data[pos: pos + 8]- pos += 8- fields.append((field_number, wire_type, val))- elif wire_type == WT_32BIT:- val = data[pos: pos + 4]- pos += 4- fields.append((field_number, wire_type, val))+ elif wire_type in _FIXED_SIZE:+ size = _FIXED_SIZE[wire_type]+ val = data[pos: pos + size]+ pos += sizeelse:raise ValueError(f"unknown wire type {wire_type} at pos {pos - 1}")+ fields.append((field_number, wire_type, val))return fieldsdef _fields_to_dict(fields: list) -> dict[int, list]:- """将 fields 列表转为 {field_number: [value, ...]} 字典(repeated 字段会有多个)"""+ """fields 列表 → {field_number: [(wire_type, value), ...]}(repeated 字段有多个)"""d: dict[int, list] = {}for fn, wt, val in fields:d.setdefault(fn, []).append((wt, val))return d-def _get_string(fdict: dict, fn: int, default: str = "") -> str:- """从 fields dict 取第一个 string 字段"""+def _parse_dict(data: bytes) -> dict[int, list]:+ return _fields_to_dict(_parse_fields(data))+++def _first(fdict: dict, fn: int, wt: int):+ """第一个 wire type 匹配的字段值,无则 None"""entries = fdict.get(fn)- if not entries:- return default- wt, val = entries[0]- if wt == WT_LEN and isinstance(val, (bytes, bytearray)):+ if entries and entries[0][0] == wt:+ return entries[0][1]+ return None+++def _get_string(fdict: dict, fn: int, default: str = "") -> str:+ val = _first(fdict, fn, WT_LEN)+ if isinstance(val, (bytes, bytearray)):return val.decode("utf-8", errors="replace")return defaultdef _get_varint(fdict: dict, fn: int, default: int = 0) -> int:- """从 fields dict 取第一个 varint 字段"""- entries = fdict.get(fn)- if not entries:- return default- wt, val = entries[0]- if wt == WT_VARINT and isinstance(val, int):- return val- return default+ val = _first(fdict, fn, WT_VARINT)+ return val if isinstance(val, int) else defaultdef _get_bytes(fdict: dict, fn: int, default: bytes = b"") -> bytes:- """从 fields dict 取第一个 bytes/message 字段"""- entries = fdict.get(fn)- if not entries:- return default- wt, val = entries[0]- if wt == WT_LEN and isinstance(val, (bytes, bytearray)):- return bytes(val)- return default+ val = _first(fdict, fn, WT_LEN)+ return bytes(val) if isinstance(val, (bytes, bytearray)) else defaultdef _get_repeated_bytes(fdict: dict, fn: int) -> list[bytes]:- """取所有 repeated bytes/message 字段"""- entries = fdict.get(fn, [])- return [bytes(val) for wt, val in entries if wt == WT_LEN]+ return [bytes(val) for wt, val in fdict.get(fn, []) if wt == WT_LEN]+++# 字段表驱动编解码:spec = [(field_number, key, kind)],kind:+# "s" string(编码时 str(v)) "r" string(原值) "i" varint(编码时 int(v))+# 编码跳过 falsy 值;解码只保留 truthy 值。spec 顺序即 wire 顺序和 dict 插入顺序。+_STR_KINDS = ("s", "r")+++def _encode_spec(obj: dict, spec: list) -> bytes:+ buf = b""+ for fn, key, kind in spec:+ v = obj.get(key, "" if kind in _STR_KINDS else 0)+ if v:+ buf += _s(fn, str(v) if kind == "s" else v) if kind in _STR_KINDS else _v(fn, int(v))+ return buf+++def _decode_spec(fdict: dict, spec: list) -> dict:+ out: dict = {}+ for fn, key, kind in spec:+ v = _get_string(fdict, fn) if kind in _STR_KINDS else _get_varint(fdict, fn)+ if v:+ out[key] = v+ return out# ============================================================# ConnMsg 层编解码# ============================================================-#-# ConnMsg protobuf schema (conn.json):-# message Head {-# uint32 cmd_type = 1;-# string cmd = 2;-# uint32 seq_no = 3;-# string msg_id = 4;-# string module = 5;-# bool need_ack = 6;-# ...-# int32 status = 10;-# }-# message ConnMsg {-# Head head = 1;-# bytes data = 2;-# }+# message Head { uint32 cmd_type=1; string cmd=2; uint32 seq_no=3; string msg_id=4;+# string module=5; bool need_ack=6; ... int32 status=10; }+# message ConnMsg { Head head=1; bytes data=2; }def _encode_head(- cmd_type: int,- cmd: str,- seq_no: int,- msg_id: str,- module: str,- need_ack: bool = False,- status: int = 0,+ cmd_type: int, cmd: str, seq_no: int, msg_id: str, module: str, need_ack: bool = False, status: int = 0,) -> bytes:- """编码 ConnMsg.Head"""buf = b""if cmd_type != 0:- buf += _encode_field(1, WT_VARINT, _encode_varint(cmd_type))+ buf += _v(1, cmd_type)if cmd:- buf += _encode_field(2, WT_LEN, _encode_string(cmd))+ buf += _s(2, cmd)if seq_no != 0:- buf += _encode_field(3, WT_VARINT, _encode_varint(seq_no))+ buf += _v(3, seq_no)if msg_id:- buf += _encode_field(4, WT_LEN, _encode_string(msg_id))+ buf += _s(4, msg_id)if module:- buf += _encode_field(5, WT_LEN, _encode_string(module))+ buf += _s(5, module)if need_ack:- buf += _encode_field(6, WT_VARINT, _encode_varint(1))+ buf += _v(6, 1)if status != 0:- buf += _encode_field(10, WT_VARINT, _encode_varint(status & 0xFFFFFFFFFFFFFFFF))+ buf += _v(10, status & 0xFFFFFFFFFFFFFFFF)return bufdef _decode_head(data: bytes) -> dict:- """解码 ConnMsg.Head,返回 dict"""- fdict = _fields_to_dict(_parse_fields(data))+ fdict = _parse_dict(data)return {"cmd_type": _get_varint(fdict, 1, 0),"cmd": _get_string(fdict, 2, ""),@@ -332,137 +295,49 @@ def _decode_head(data: bytes) -> dict:}-def encode_conn_msg(msg_type: int, seq_no: int, data: bytes) -> bytes:- """- 编码 ConnMsg(简化接口,对应任务要求的签名)。-- Args:- msg_type: cmd_type(CMD_TYPE 枚举值)- seq_no: 序列号- data: 内层 payload bytes(业务 protobuf)-- Returns:- ConnMsg 编码后的 bytes- """- head_bytes = _encode_head(- cmd_type=msg_type,- cmd="",- seq_no=seq_no,- msg_id="",- module="",- )- buf = _encode_field(1, WT_LEN, _encode_message(head_bytes))+def _conn_msg(label: str, cmd_type: int, cmd: str, seq_no: int, msg_id: str, module: str, data: bytes, need_ack: bool) -> bytes:+ buf = _m(1, _encode_head(cmd_type, cmd, seq_no, msg_id, module, need_ack))if data:- buf += _encode_field(2, WT_LEN, _encode_bytes(data))- _dbg("encode_conn_msg", buf)+ buf += _m(2, data)+ _dbg(label, buf)return buf-def decode_conn_msg(data: bytes) -> dict:- """- 解码 ConnMsg,返回 {msg_type, seq_no, data, head}。-- Returns:- {- "msg_type": int, # cmd_type- "seq_no": int,- "data": bytes, # 内层 payload- "head": dict, # 完整 head 字段- }- """- _dbg("decode_conn_msg", data)- fdict = _fields_to_dict(_parse_fields(data))- head_bytes = _get_bytes(fdict, 1)- payload = _get_bytes(fdict, 2)- head = _decode_head(head_bytes) if head_bytes else {- "cmd_type": 0, "cmd": "", "seq_no": 0, "msg_id": "", "module": "",- "need_ack": False, "status": 0,- }- return {- "msg_type": head["cmd_type"],- "seq_no": head["seq_no"],- "data": payload,- "head": head,- }+def encode_conn_msg(msg_type: int, seq_no: int, data: bytes) -> bytes:+ """编码 ConnMsg(简化接口:仅 cmd_type + seq_no + payload)"""+ return _conn_msg("encode_conn_msg", msg_type, "", seq_no, "", "", data, False)def encode_conn_msg_full(- cmd_type: int,- cmd: str,- seq_no: int,- msg_id: str,- module: str,- data: bytes,- need_ack: bool = False,+ cmd_type: int, cmd: str, seq_no: int, msg_id: str, module: str, data: bytes, need_ack: bool = False,) -> bytes:- """- 编码完整的 ConnMsg(含 cmd/msg_id/module 等 head 字段)。- 比 encode_conn_msg 提供更多 head 控制。- """- head_bytes = _encode_head(- cmd_type=cmd_type,- cmd=cmd,- seq_no=seq_no,- msg_id=msg_id,- module=module,- need_ack=need_ack,- )- buf = _encode_field(1, WT_LEN, _encode_message(head_bytes))- if data:- buf += _encode_field(2, WT_LEN, _encode_bytes(data))- _dbg("encode_conn_msg_full", buf)- return buf+ """编码完整的 ConnMsg(含 cmd/msg_id/module 等 head 字段)"""+ return _conn_msg("encode_conn_msg_full", cmd_type, cmd, seq_no, msg_id, module, data, need_ack)+++def decode_conn_msg(data: bytes) -> dict:+ """解码 ConnMsg → {msg_type, seq_no, data, head}(head 为完整 Head dict)"""+ _dbg("decode_conn_msg", data)+ fdict = _parse_dict(data)+ head = _decode_head(_get_bytes(fdict, 1))+ return {"msg_type": head["cmd_type"], "seq_no": head["seq_no"], "data": _get_bytes(fdict, 2), "head": head}# ============================================================-# BizMsg 层编解码(biz payload 本身也是 protobuf)+# BizMsg 层:业务 body 包装成 ConnMsg(head.cmd = method, head.module = service)+# 与 conn-codec.ts buildBusinessConnMsg(cmd, module, bizData, msgId) 行为一致。# ============================================================-#-# 任务要求的 encode_biz_msg / decode_biz_msg 是一个中间抽象层:-# encode_biz_msg(service, method, req_id, body) -> conn_msg_bytes-# 即:将业务 body 包装成 ConnMsg,其中 head.cmd = method, head.module = service-#-# 这与 conn-codec.ts 中 buildBusinessConnMsg() 的行为一致:-# buildBusinessConnMsg(cmd, module, bizData, msgId) -> ConnMsg bytesdef encode_biz_msg(service: str, method: str, req_id: str, body: bytes) -> bytes:- """- 将业务 payload 包装为 ConnMsg bytes。-- Args:- service: 模块名(head.module),如 "yuanbao_openclaw_proxy"- method: 命令字(head.cmd),如 "send_c2c_message"- req_id: 消息 ID(head.msg_id)- body: 已编码的业务 protobuf bytes-- Returns:- ConnMsg bytes(可直接发送到 WebSocket)- """+ """将已编码的业务 protobuf 包装为可直接发送的 ConnMsg bytes"""return encode_conn_msg_full(- cmd_type=CMD_TYPE["Request"],- cmd=method,- seq_no=next_seq_no(),- msg_id=req_id,- module=service,- data=body,+ cmd_type=CMD_TYPE["Request"], cmd=method, seq_no=next_seq_no(), msg_id=req_id, module=service, data=body,)def decode_biz_msg(data: bytes) -> dict:- """- 解码 ConnMsg bytes,返回业务层信息。-- Returns:- {- "service": str, # head.module- "method": str, # head.cmd- "req_id": str, # head.msg_id- "body": bytes, # 内层 biz payload- "is_response": bool, # cmd_type == 1 (Response)- "head": dict, # 完整 head- }- """+ """解码 ConnMsg → {service, method, req_id, body, is_response, head}"""result = decode_conn_msg(data)head = result["head"]return {@@ -475,247 +350,107 @@ def decode_biz_msg(data: bytes) -> dict:}+def _biz_request(method: str, prefix: str, body: bytes, msg_id: str = "") -> bytes:+ """biz 请求 ConnMsg;req_id 为 msg_id,空则 '<prefix>_<seq>'(seq 在 conn seq_no 之前分配)"""+ req_id = msg_id or f"{prefix}_{next_seq_no()}"+ return encode_biz_msg(service=_BIZ_PKG, method=method, req_id=req_id, body=body)++# ============================================================# 业务 protobuf 消息编解码(biz payload)# ============================================================-# ---------- MsgContent 编解码 -----------# field 1: text (string)-# field 2: uuid (string)-# field 3: image_format (uint32)-# field 4: data (string)-# field 5: desc (string)-# field 6: ext (string)-# field 7: sound (string)-# field 8: image_info_array (repeated message)-# field 9: index (uint32)-# field 10: url (string)-# field 11: file_size (uint32)-# field 12: file_name (string)-# field 999: ext_map (map<string, string>) ← extension info for WeChat chat-history forwarding-# protobuf map is wire-encoded as a repeated message entry; each entry has:-# field 1: key (string)-# field 2: value (string)-# key format: wexin_forward_msg_[forward_msg_id]_[userid]-# value: base64(ForwardMsgData protobuf) ← NOT JSON; it is base64-encoded-# protobuf bytes that must be parsed with decode_forward_msg_data().---def _encode_map_entry(key: str, value: str) -> bytes:- """Encode a single entry of a protobuf map<string, string> (field 1 key, field 2 value)."""- buf = b""- if key:- buf += _encode_field(1, WT_LEN, _encode_string(str(key)))- if value:- buf += _encode_field(2, WT_LEN, _encode_string(str(value)))- return buf---def _decode_map_entry(data: bytes) -> tuple[str, str]:- """Decode a single entry of a protobuf map<string, string>, returning (key, value)."""- fdict = _fields_to_dict(_parse_fields(data))- return _get_string(fdict, 1), _get_string(fdict, 2)+# MsgContent:1 text, 2 uuid, 3 image_format, 4 data, 5 desc, 6 ext, 7 sound,+# 8 image_info_array (repeated), 9 index, 10 url, 11 file_size, 12 file_name,+# 999 ext_map (map<string,string>: repeated entry{1 key, 2 value})+# ext_map key 格式 wexin_forward_msg_[forward_msg_id]_[userid],value 为+# base64(ForwardMsgData protobuf)(不是 JSON),用 decode_forward_msg_data() 解析。+_MSG_CONTENT_SPEC = [+ (1, "text", "s"), (2, "uuid", "s"), (4, "data", "s"), (5, "desc", "s"),+ (6, "ext", "s"), (7, "sound", "s"), (10, "url", "s"), (12, "file_name", "s"),+ (3, "image_format", "i"), (9, "index", "i"), (11, "file_size", "i"),+]+_IMAGE_INFO_SPEC = [(1, "type", "i"), (2, "size", "i"), (3, "width", "i"), (4, "height", "i"), (5, "url", "r")]+_MAP_ENTRY_SPEC = [(1, "key", "s"), (2, "value", "s")]def _encode_msg_content(content: dict) -> bytes:- buf = b""- for fn, key in [- (1, "text"), (2, "uuid"), (4, "data"), (5, "desc"),- (6, "ext"), (7, "sound"), (10, "url"), (12, "file_name"),- ]:- v = content.get(key, "")- if v:- buf += _encode_field(fn, WT_LEN, _encode_string(str(v)))- for fn, key in [(3, "image_format"), (9, "index"), (11, "file_size")]:- v = content.get(key, 0)- if v:- buf += _encode_field(fn, WT_VARINT, _encode_varint(int(v)))- # image_info_array (repeated)+ buf = _encode_spec(content, _MSG_CONTENT_SPEC)for img in content.get("image_info_array") or []:- img_buf = b""- for ifn, ikey in [(1, "type"), (2, "size"), (3, "width"), (4, "height")]:- iv = img.get(ikey, 0)- if iv:- img_buf += _encode_field(ifn, WT_VARINT, _encode_varint(int(iv)))- url = img.get("url", "")- if url:- img_buf += _encode_field(5, WT_LEN, _encode_string(url))- buf += _encode_field(8, WT_LEN, _encode_message(img_buf))- # ext_map (map<string, string>, field 999) — repeated message entries+ buf += _m(8, _encode_spec(img, _IMAGE_INFO_SPEC))ext_map = content.get("ext_map")if isinstance(ext_map, dict):for k, v in ext_map.items():- entry_bytes = _encode_map_entry(str(k), str(v))- buf += _encode_field(999, WT_LEN, _encode_message(entry_bytes))+ buf += _m(999, _encode_spec({"key": str(k), "value": str(v)}, _MAP_ENTRY_SPEC))return bufdef _decode_msg_content(data: bytes) -> dict:- fdict = _fields_to_dict(_parse_fields(data))- content: dict = {}- for fn, key in [- (1, "text"), (2, "uuid"), (4, "data"), (5, "desc"),- (6, "ext"), (7, "sound"), (10, "url"), (12, "file_name"),- ]:- v = _get_string(fdict, fn)- if v:- content[key] = v- for fn, key in [(3, "image_format"), (9, "index"), (11, "file_size")]:- v = _get_varint(fdict, fn)- if v:- content[key] = v- imgs = []- for img_bytes in _get_repeated_bytes(fdict, 8):- ifdict = _fields_to_dict(_parse_fields(img_bytes))- img = {}- for ifn, ikey in [(1, "type"), (2, "size"), (3, "width"), (4, "height")]:- iv = _get_varint(ifdict, ifn)- if iv:- img[ikey] = iv- url = _get_string(ifdict, 5)- if url:- img["url"] = url- if img:- imgs.append(img)+ fdict = _parse_dict(data)+ content = _decode_spec(fdict, _MSG_CONTENT_SPEC)+ imgs = [img for img in (_decode_spec(_parse_dict(b), _IMAGE_INFO_SPEC) for b in _get_repeated_bytes(fdict, 8)) if img]if imgs:content["image_info_array"] = imgs- # ext_map (field 999) — decode repeated map entries into a plain dictext_map: dict[str, str] = {}for entry_bytes in _get_repeated_bytes(fdict, 999):- k, v = _decode_map_entry(entry_bytes)+ efdict = _parse_dict(entry_bytes)+ k = _get_string(efdict, 1)if k:- ext_map[k] = v+ ext_map[k] = _get_string(efdict, 2)if ext_map:content["ext_map"] = ext_mapreturn content-# ---------- MsgBodyElement 编解码 -----------# field 1: msg_type (string) e.g. "TIMTextElem"-# field 2: msg_content (message MsgContent)+# MsgBodyElement:1 msg_type (string, e.g. "TIMTextElem"), 2 msg_content (MsgContent)def _encode_msg_body_element(element: dict) -> bytes:buf = b""msg_type = element.get("msg_type", "")if msg_type:- buf += _encode_field(1, WT_LEN, _encode_string(msg_type))+ buf += _s(1, msg_type)content = element.get("msg_content", {})if content:- content_bytes = _encode_msg_content(content)- buf += _encode_field(2, WT_LEN, _encode_message(content_bytes))+ buf += _m(2, _encode_msg_content(content))return bufdef _decode_msg_body_element(data: bytes) -> dict:- fdict = _fields_to_dict(_parse_fields(data))- msg_type = _get_string(fdict, 1, "")+ fdict = _parse_dict(data)content_bytes = _get_bytes(fdict, 2)- content = _decode_msg_content(content_bytes) if content_bytes else {}- return {"msg_type": msg_type, "msg_content": content}+ return {"msg_type": _get_string(fdict, 1, ""), "msg_content": _decode_msg_content(content_bytes) if content_bytes else {}}-# ---------- LogInfoExt -----------# field 1: trace_id (string)+def _encode_msg_body(fn: int, msg_body: list) -> bytes:+ return b"".join(_m(fn, _encode_msg_body_element(el)) for el in msg_body)def _encode_log_ext(trace_id: str) -> bytes:- if not trace_id:- return b""- return _encode_field(1, WT_LEN, _encode_string(trace_id))---def _decode_im_msg_seq(data: bytes) -> dict:- """Decode a single ImMsgSeq sub-message (field 17 of InboundMessagePush).-- ImMsgSeq proto fields:- 1: msg_seq (uint64)- 2: msg_id (string)- """- fdict = _fields_to_dict(_parse_fields(data))- return {- "msg_seq": _get_varint(fdict, 1),- "msg_id": _get_string(fdict, 2),- }---def _decode_log_ext(data: bytes) -> dict:- fdict = _fields_to_dict(_parse_fields(data))- return {"trace_id": _get_string(fdict, 1)}+ """LogInfoExt:1 trace_id"""+ return _s(1, trace_id) if trace_id else b""# ============================================================# 入站消息解析# ============================================================-#-# InboundMessagePush fields:-# 1: callback_command (string)-# 2: from_account (string)-# 3: to_account (string)-# 4: sender_nickname (string)-# 5: group_id (string)-# 6: group_code (string)-# 7: group_name (string)-# 8: msg_seq (uint32)-# 9: msg_random (uint32)-# 10: msg_time (uint32)-# 11: msg_key (string)-# 12: msg_id (string)-# 13: msg_body (repeated MsgBodyElement)-# 14: cloud_custom_data (string)-# 15: event_time (uint32)-# 16: bot_owner_id (string)-# 17: recall_msg_seq_list (repeated ImMsgSeq)-# 18: claw_msg_type (uint32/enum)-# 19: private_from_group_code (string)-# 20: log_ext (message LogInfoExt)+# InboundMessagePush: 1 callback_command, 2 from_account, 3 to_account, 4 sender_nickname,+# 5 group_id, 6 group_code, 7 group_name, 8 msg_seq, 9 msg_random, 10 msg_time, 11 msg_key,+# 12 msg_id, 13 msg_body (repeated MsgBodyElement), 14 cloud_custom_data, 15 event_time,+# 16 bot_owner_id, 17 recall_msg_seq_list (repeated ImMsgSeq{1 msg_seq, 2 msg_id}),+# 18 claw_msg_type, 19 private_from_group_code, 20 log_ext (LogInfoExt{1 trace_id})def decode_inbound_push(data: bytes) -> Optional[dict]:- """- 解析入站消息推送的 biz payload(InboundMessagePush proto bytes)。-- Args:- data: ConnMsg.data 字段的 bytes(即 biz payload)-- Returns:- {- "from_account": str,- "to_account": str (可选),- "group_code": str (可选,群消息才有),- "group_id": str (可选),- "group_name": str (可选),- "msg_key": str,- "msg_id": str,- "msg_seq": int,- "msg_random": int,- "msg_time": int,- "sender_nickname": str,- "msg_body": [{"msg_type": str, "msg_content": dict}, ...],- "callback_command": str,- "cloud_custom_data": str,- "bot_owner_id": str,- "claw_msg_type": int,- "private_from_group_code": str,- "trace_id": str,- "recall_msg_seq_list": [{"msg_seq": int, "msg_id": str}, ...] 或 None,- }- 或 None(解析失败)+ """解析 InboundMessagePush biz payload。++ Returns: 上述字段的 dict(空值已过滤,msg_body / msg_seq 始终保留;+ recall_msg_seq_list 为 [{msg_seq, msg_id}] 或 None),解析失败返回 None。"""try:_dbg("decode_inbound_push input", data)- fdict = _fields_to_dict(_parse_fields(data))-- msg_body = []- for el_bytes in _get_repeated_bytes(fdict, 13):- msg_body.append(_decode_msg_body_element(el_bytes))-+ fdict = _parse_dict(data)log_ext_bytes = _get_bytes(fdict, 20)- trace_id = _decode_log_ext(log_ext_bytes).get("trace_id", "") if log_ext_bytes else ""-- recall_seq_raw = _get_repeated_bytes(fdict, 17)- recall_msg_seq_list = [_decode_im_msg_seq(b) for b in recall_seq_raw] or None-result: dict = {"callback_command": _get_string(fdict, 1),"from_account": _get_string(fdict, 2),@@ -729,16 +464,18 @@ def decode_inbound_push(data: bytes) -> Optional[dict]:"msg_time": _get_varint(fdict, 10),"msg_key": _get_string(fdict, 11),"msg_id": _get_string(fdict, 12),- "msg_body": msg_body,+ "msg_body": [_decode_msg_body_element(b) for b in _get_repeated_bytes(fdict, 13)],"cloud_custom_data": _get_string(fdict, 14),"event_time": _get_varint(fdict, 15),"bot_owner_id": _get_string(fdict, 16),- "recall_msg_seq_list": recall_msg_seq_list,+ "recall_msg_seq_list": [+ {"msg_seq": _get_varint(d, 1), "msg_id": _get_string(d, 2)}+ for d in map(_parse_dict, _get_repeated_bytes(fdict, 17))+ ] or None,"claw_msg_type": _get_varint(fdict, 18),"private_from_group_code": _get_string(fdict, 19),- "trace_id": trace_id,+ "trace_id": _get_string(_parse_dict(log_ext_bytes), 1) if log_ext_bytes else "",}- # 过滤空值(保持 API 整洁)return {k: v for k, v in result.items() if v or k in {"msg_body", "msg_seq"}}except Exception as e:if DEBUG_MODE:@@ -749,103 +486,50 @@ def decode_inbound_push(data: bytes) -> Optional[dict]:# ============================================================# WeChat forwarded chat-history parsing (ForwardMsgData)# ============================================================-#-# The value of ext_map["wexin_forward_msg_<id>_<userid>"] is a base64-encoded-# ForwardMsgData protobuf (NOT JSON). Structure (verified against live captures):-#-# message ForwardMsgData {-# uint32 sub_type = 1; // 1 = WeChat chat-history forward-# uint32 begin_time = 2;-# uint32 end_time = 3;-# string nick_name = 4; // forwarder's WeChat nickname-# repeated ForwardMsg msg = 5;-# }-# message ForwardMsg {-# string sender = 1;-# uint32 time = 2;-# string plainText = 3;-# repeated MsgContent msgContent = 4;-# }-# message MsgContent {-# uint32 type = 1; // 1=TEXT, 2=MULTIMEDIA, 3=nested forward-# string text = 2; // type==1-# repeated Multimedia multimedia = 3; // type==2-# }-# message Multimedia {-# string type = 1; // image / file / document / url / video-# string url = 2;-# string file_name = 4;-# uint32 file_size = 5;-# uint32 width = 6;-# uint32 height = 7;-# string media_id = 15; // can be used directly as a ybres RID-# string res_type = 24;-# }---def _decode_forward_multimedia(data: bytes) -> dict:- """Decode a single Multimedia sub-message into the dict shape expected by _format_multimedia."""- fdict = _fields_to_dict(_parse_fields(data))- media: dict = {}- mtype = _get_string(fdict, 1)- if mtype:- media["type"] = mtype- url = _get_string(fdict, 2)- if url:- media["url"] = url- file_name = _get_string(fdict, 4)- if file_name:- media["file_name"] = file_name- file_size = _get_varint(fdict, 5)- if file_size:- media["file_size"] = file_size- media_id = _get_string(fdict, 15)- if media_id:- media["media_id"] = media_id- return media+# ext_map["wexin_forward_msg_<id>_<userid>"] = base64(ForwardMsgData) — protobuf, NOT JSON.+# Verified against live captures:+# ForwardMsgData { uint32 sub_type=1 (1 = WeChat chat-history forward); uint32 begin_time=2;+# uint32 end_time=3; string nick_name=4 (forwarder); repeated ForwardMsg msg=5 }+# ForwardMsg { string sender=1; uint32 time=2; string plainText=3; repeated MsgContent msgContent=4 }+# MsgContent { uint32 type=1 (1=TEXT, 2=MULTIMEDIA, 3=nested forward); string text=2;+# repeated Multimedia multimedia=3 }+# Multimedia { string type=1 (image/file/document/url/video); string url=2; string file_name=4;+# uint32 file_size=5; uint32 width=6; uint32 height=7;+# string media_id=15 (usable directly as a ybres RID); string res_type=24 }+_FORWARD_MULTIMEDIA_SPEC = [(1, "type", "s"), (2, "url", "s"), (4, "file_name", "s"), (5, "file_size", "i"), (15, "media_id", "s")]def _decode_forward_msg_content(data: bytes) -> dict:- """Decode a single MsgContent sub-message into {type, text?, multimedia?}."""- fdict = _fields_to_dict(_parse_fields(data))+ """MsgContent → {type, text?, multimedia?}(shape 与 _format_multimedia 对齐)"""+ fdict = _parse_dict(data)content: dict = {"type": _get_varint(fdict, 1)}text = _get_string(fdict, 2)if text:content["text"] = text- multimedia = [- _decode_forward_multimedia(b) for b in _get_repeated_bytes(fdict, 3)- ]+ multimedia = [_decode_spec(_parse_dict(b), _FORWARD_MULTIMEDIA_SPEC) for b in _get_repeated_bytes(fdict, 3)]if multimedia:content["multimedia"] = multimediareturn contentdef _decode_forward_msg(data: bytes) -> dict:- """Decode a single ForwardMsg sub-message into {sender, plainText, msgContent}."""- fdict = _fields_to_dict(_parse_fields(data))+ fdict = _parse_dict(data)return {"sender": _get_string(fdict, 1),"time": _get_varint(fdict, 2),"plainText": _get_string(fdict, 3),- "msgContent": [- _decode_forward_msg_content(b) for b in _get_repeated_bytes(fdict, 4)- ],+ "msgContent": [_decode_forward_msg_content(b) for b in _get_repeated_bytes(fdict, 4)],}def decode_forward_msg_data(data: bytes) -> Optional[dict]:"""Parse ForwardMsgData protobuf bytes (the base64-decoded ext_map value).- Args:- data: ForwardMsgData protobuf bytes, after base64 decoding.-- Returns:- A dict matching the structure consumed by- ``ForwardedRecordsParseMiddleware.build_forward_text``- (``sub_type`` / ``nick_name`` / ``msg`` list); ``None`` on parse failure.+ Returns the ``sub_type`` / ``nick_name`` / ``msg`` structure consumed by+ ``ForwardedRecordsParseMiddleware.build_forward_text``; ``None`` on parse failure."""try:- fdict = _fields_to_dict(_parse_fields(data))+ fdict = _parse_dict(data)return {"sub_type": _get_varint(fdict, 1),"begin_time": _get_varint(fdict, 2),@@ -859,114 +543,51 @@ def decode_forward_msg_data(data: bytes) -> Optional[dict]:return None-def _encode_forward_multimedia(media: dict) -> bytes:- buf = b""- for fn, key in [(1, "type"), (2, "url"), (4, "file_name"), (15, "media_id")]:- v = media.get(key, "")- if v:- buf += _encode_field(fn, WT_LEN, _encode_string(str(v)))- for fn, key in [(5, "file_size"), (6, "width"), (7, "height")]:- v = media.get(key, 0)- if v:- buf += _encode_field(fn, WT_VARINT, _encode_varint(int(v)))- return buf---def _encode_forward_msg_content(content: dict) -> bytes:- buf = _encode_field(1, WT_VARINT, _encode_varint(int(content.get("type", 0))))- text = content.get("text", "")- if text:- buf += _encode_field(2, WT_LEN, _encode_string(str(text)))- for media in content.get("multimedia") or []:- buf += _encode_field(3, WT_LEN, _encode_message(_encode_forward_multimedia(media)))- return buf---def _encode_forward_msg(msg: dict) -> bytes:- buf = b""- sender = msg.get("sender", "")- if sender:- buf += _encode_field(1, WT_LEN, _encode_string(str(sender)))- time_val = msg.get("time", 0)- if time_val:- buf += _encode_field(2, WT_VARINT, _encode_varint(int(time_val)))- plain = msg.get("plainText", "")- if plain:- buf += _encode_field(3, WT_LEN, _encode_string(str(plain)))- for mc in msg.get("msgContent") or []:- buf += _encode_field(4, WT_LEN, _encode_message(_encode_forward_msg_content(mc)))- return buf---def encode_forward_msg_data(data: dict) -> bytes:- """Encode ForwardMsgData protobuf bytes (inverse of ``decode_forward_msg_data``).-- Mainly used to build mock / test data; production code never needs to encode this.- """- buf = _encode_field(1, WT_VARINT, _encode_varint(int(data.get("sub_type", 0))))- for fn, key in [(2, "begin_time"), (3, "end_time")]:- v = data.get(key, 0)- if v:- buf += _encode_field(fn, WT_VARINT, _encode_varint(int(v)))- nick = data.get("nick_name", "")- if nick:- buf += _encode_field(4, WT_LEN, _encode_string(str(nick)))- for msg in data.get("msg") or []:- buf += _encode_field(5, WT_LEN, _encode_message(_encode_forward_msg(msg)))- return buf--# ============================================================# Outbound message encoding# ============================================================-def _encode_send_c2c_req(+++def encode_send_c2c_message(to_account: str,- from_account: str,msg_body: list,+ from_account: str,msg_id: str = "",msg_random: int = 0,msg_seq: Optional[int] = None,group_code: str = "",trace_id: str = "",) -> bytes:+ """Encode a SendC2CMessageReq and return the full ConnMsg bytes (ready to send over WebSocket).++ SendC2CMessageReq: 1 msg_id, 2 to_account, 3 from_account, 4 msg_random,+ 5 msg_body (repeated MsgBodyElement), 6 group_code, 7 msg_seq, 8 log_ext.+ msg_body items are {"msg_type": str, "msg_content": dict}; msg_id doubles as req_id when set;+ group_code is filled for the "private chat originating from a group" case."""- Encode a SendC2CMessageReq biz payload.-- SendC2CMessageReq fields:- 1: msg_id (string)- 2: to_account (string)- 3: from_account (string)- 4: msg_random (uint32)- 5: msg_body (repeated MsgBodyElement)- 6: group_code (string)- 7: msg_seq (uint64)- 8: log_ext (LogInfoExt)- """- buf = b""+ biz_bytes = b""if msg_id:- buf += _encode_field(1, WT_LEN, _encode_string(msg_id))- buf += _encode_field(2, WT_LEN, _encode_string(to_account))+ biz_bytes += _s(1, msg_id)+ biz_bytes += _s(2, to_account)if from_account:- buf += _encode_field(3, WT_LEN, _encode_string(from_account))+ biz_bytes += _s(3, from_account)if msg_random:- buf += _encode_field(4, WT_VARINT, _encode_varint(msg_random))- for el in msg_body:- el_bytes = _encode_msg_body_element(el)- buf += _encode_field(5, WT_LEN, _encode_message(el_bytes))+ biz_bytes += _v(4, msg_random)+ biz_bytes += _encode_msg_body(5, msg_body)if group_code:- buf += _encode_field(6, WT_LEN, _encode_string(group_code))+ biz_bytes += _s(6, group_code)if msg_seq is not None:- buf += _encode_field(7, WT_VARINT, _encode_varint(msg_seq))+ biz_bytes += _v(7, msg_seq)if trace_id:- log_bytes = _encode_log_ext(trace_id)- buf += _encode_field(8, WT_LEN, _encode_message(log_bytes))- return buf+ biz_bytes += _m(8, _encode_log_ext(trace_id))+ _dbg("encode_send_c2c biz payload", biz_bytes)+ return _biz_request("send_c2c_message", "c2c", biz_bytes, msg_id)-def _encode_send_group_req(+def encode_send_group_message(group_code: str,- from_account: str,msg_body: list,+ from_account: str,msg_id: str = "",to_account: str = "",random: str = "",@@ -974,150 +595,37 @@ def _encode_send_group_req(ref_msg_id: str = "",trace_id: str = "",) -> bytes:+ """Encode a SendGroupMessageReq and return the full ConnMsg bytes (ready to send over WebSocket).++ SendGroupMessageReq: 1 msg_id, 2 group_code, 3 from_account, 4 to_account (usually empty),+ 5 random (string), 6 msg_body, 7 ref_msg_id (quoted message), 8 msg_seq, 9 log_ext."""- Encode a SendGroupMessageReq biz payload.-- SendGroupMessageReq fields:- 1: msg_id (string)- 2: group_code (string)- 3: from_account (string)- 4: to_account (string)- 5: random (string)- 6: msg_body (repeated MsgBodyElement)- 7: ref_msg_id (string)- 8: msg_seq (uint64)- 9: log_ext (LogInfoExt)- """- buf = b""+ biz_bytes = b""if msg_id:- buf += _encode_field(1, WT_LEN, _encode_string(msg_id))- buf += _encode_field(2, WT_LEN, _encode_string(group_code))+ biz_bytes += _s(1, msg_id)+ biz_bytes += _s(2, group_code)if from_account:- buf += _encode_field(3, WT_LEN, _encode_string(from_account))+ biz_bytes += _s(3, from_account)if to_account:- buf += _encode_field(4, WT_LEN, _encode_string(to_account))+ biz_bytes += _s(4, to_account)if random:- buf += _encode_field(5, WT_LEN, _encode_string(random))- for el in msg_body:- el_bytes = _encode_msg_body_element(el)- buf += _encode_field(6, WT_LEN, _encode_message(el_bytes))+ biz_bytes += _s(5, random)+ biz_bytes += _encode_msg_body(6, msg_body)if ref_msg_id:- buf += _encode_field(7, WT_LEN, _encode_string(ref_msg_id))+ biz_bytes += _s(7, ref_msg_id)if msg_seq is not None:- buf += _encode_field(8, WT_VARINT, _encode_varint(msg_seq))+ biz_bytes += _v(8, msg_seq)if trace_id:- log_bytes = _encode_log_ext(trace_id)- buf += _encode_field(9, WT_LEN, _encode_message(log_bytes))- return buf---def encode_send_c2c_message(- to_account: str,- msg_body: list,- from_account: str,- msg_id: str = "",- msg_random: int = 0,- msg_seq: Optional[int] = None,- group_code: str = "",- trace_id: str = "",-) -> bytes:- """- Encode a C2C send-message request and return the full ConnMsg bytes- (ready to be sent over WebSocket).-- Args:- to_account: recipient account- msg_body: list of message-body elements; each item is- {"msg_type": str, "msg_content": dict}.- Example: [{"msg_type": "TIMTextElem", "msg_content": {"text": "hello"}}]- from_account: sender account (the bot account)- msg_id: unique message ID (req_id is used when empty)- msg_random: random number for de-duplication- msg_seq: message sequence number (optional)- group_code: filled in for the "private chat originating from a group" case- trace_id: trace ID for request tracing-- Returns:- ConnMsg bytes- """- biz_bytes = _encode_send_c2c_req(- to_account=to_account,- from_account=from_account,- msg_body=msg_body,- msg_id=msg_id,- msg_random=msg_random,- msg_seq=msg_seq,- group_code=group_code,- trace_id=trace_id,- )- _dbg("encode_send_c2c biz payload", biz_bytes)- req_id = msg_id or f"c2c_{next_seq_no()}"- return encode_conn_msg_full(- cmd_type=CMD_TYPE["Request"],- cmd="send_c2c_message",- seq_no=next_seq_no(),- msg_id=req_id,- module=_BIZ_PKG,- data=biz_bytes,- )---def encode_send_group_message(- group_code: str,- msg_body: list,- from_account: str,- msg_id: str = "",- to_account: str = "",- random: str = "",- msg_seq: Optional[int] = None,- ref_msg_id: str = "",- trace_id: str = "",-) -> bytes:- """- Encode a group send-message request and return the full ConnMsg bytes- (ready to be sent over WebSocket).-- Args:- group_code: group ID- msg_body: list of message-body elements- from_account: sender account (the bot account)- msg_id: unique message ID- to_account: targeted recipient (usually empty)- random: random string for de-duplication- msg_seq: message sequence number- ref_msg_id: ID of the referenced (quoted) message- trace_id: trace ID for request tracing-- Returns:- ConnMsg bytes- """- biz_bytes = _encode_send_group_req(- group_code=group_code,- from_account=from_account,- msg_body=msg_body,- msg_id=msg_id,- to_account=to_account,- random=random,- msg_seq=msg_seq,- ref_msg_id=ref_msg_id,- trace_id=trace_id,- )+ biz_bytes += _m(9, _encode_log_ext(trace_id))_dbg("encode_send_group biz payload", biz_bytes)- req_id = msg_id or f"grp_{next_seq_no()}"- return encode_conn_msg_full(- cmd_type=CMD_TYPE["Request"],- cmd="send_group_message",- seq_no=next_seq_no(),- msg_id=req_id,- module=_BIZ_PKG,- data=biz_bytes,- )+ return _biz_request("send_group_message", "grp", biz_bytes, msg_id)# ============================================================-# AuthBind / Ping 帮助函数+# AuthBind / Ping / PushAck# ============================================================+def encode_auth_bind(biz_id: str,uid: str,@@ -1129,275 +637,117 @@ def encode_auth_bind(bot_version: str = "",route_env: str = "",) -> bytes:- """- 构造 auth-bind 请求 ConnMsg bytes。+ """构造 auth-bind 请求 ConnMsg bytes。- AuthBindReq fields:- 1: biz_id (string)- 2: auth_info (message AuthInfo: uid=1, source=2, token=3)- 3: device_info (message DeviceInfo: app_version=1, app_operation_system=2, instance_id=10, bot_version=24)- 5: env_name (string)+ AuthBindReq: 1 biz_id, 2 auth_info (AuthInfo{1 uid, 2 source, 3 token}),+ 3 device_info (DeviceInfo{1 app_version, 2 app_operation_system, 10 instance_id, 24 bot_version}),+ 5 env_name"""- # AuthInfo- auth_buf = (- _encode_field(1, WT_LEN, _encode_string(uid))- + _encode_field(2, WT_LEN, _encode_string(source))- + _encode_field(3, WT_LEN, _encode_string(token))- )- # DeviceInfo+ auth_buf = _s(1, uid) + _s(2, source) + _s(3, token)dev_buf = b""if app_version:- dev_buf += _encode_field(1, WT_LEN, _encode_string(app_version))+ dev_buf += _s(1, app_version)if operation_system:- dev_buf += _encode_field(2, WT_LEN, _encode_string(operation_system))- dev_buf += _encode_field(10, WT_LEN, _encode_string(str(HERMES_INSTANCE_ID)))+ dev_buf += _s(2, operation_system)+ dev_buf += _s(10, str(HERMES_INSTANCE_ID))if bot_version:- dev_buf += _encode_field(24, WT_LEN, _encode_string(bot_version))-- req_buf = (- _encode_field(1, WT_LEN, _encode_string(biz_id))- + _encode_field(2, WT_LEN, _encode_message(auth_buf))- + _encode_field(3, WT_LEN, _encode_message(dev_buf))- )+ dev_buf += _s(24, bot_version)+ req_buf = _s(1, biz_id) + _m(2, auth_buf) + _m(3, dev_buf)if route_env:- req_buf += _encode_field(5, WT_LEN, _encode_string(route_env))-+ req_buf += _s(5, route_env)return encode_conn_msg_full(- cmd_type=CMD_TYPE["Request"],- cmd=CMD["AuthBind"],- seq_no=next_seq_no(),- msg_id=msg_id,- module=MODULE["ConnAccess"],- data=req_buf,+ cmd_type=CMD_TYPE["Request"], cmd=CMD["AuthBind"], seq_no=next_seq_no(), msg_id=msg_id,+ module=MODULE["ConnAccess"], data=req_buf,)def encode_ping(msg_id: str) -> bytes:"""构造 ping 请求 ConnMsg bytes(PingReq 为空消息)"""return encode_conn_msg_full(- cmd_type=CMD_TYPE["Request"],- cmd=CMD["Ping"],- seq_no=next_seq_no(),- msg_id=msg_id,- module=MODULE["ConnAccess"],- data=b"",+ cmd_type=CMD_TYPE["Request"], cmd=CMD["Ping"], seq_no=next_seq_no(), msg_id=msg_id,+ module=MODULE["ConnAccess"], data=b"",)def encode_push_ack(original_head: dict) -> bytes:- """构造 push ACK 回包"""+ """构造 push ACK 回包(回显原 head 的 cmd / msg_id / module)"""return encode_conn_msg_full(- cmd_type=CMD_TYPE["PushAck"],- cmd=original_head.get("cmd", ""),- seq_no=next_seq_no(),- msg_id=original_head.get("msg_id", ""),- module=original_head.get("module", ""),- data=b"",+ cmd_type=CMD_TYPE["PushAck"], cmd=original_head.get("cmd", ""), seq_no=next_seq_no(),+ msg_id=original_head.get("msg_id", ""), module=original_head.get("module", ""), data=b"",)# ============================================================-# Heartbeat 编码+# Heartbeat / 群信息 / 群成员列表# ============================================================-def encode_send_private_heartbeat(- from_account: str,- to_account: str,- heartbeat: int = WS_HEARTBEAT_RUNNING,-) -> bytes:- """- 编码 SendPrivateHeartbeatReq,返回完整 ConnMsg bytes。- SendPrivateHeartbeatReq fields:- 1: from_account (string)- 2: to_account (string)- 3: heartbeat (varint: RUNNING=1, FINISH=2)- """- buf = (- _encode_field(1, WT_LEN, _encode_string(from_account))- + _encode_field(2, WT_LEN, _encode_string(to_account))- + _encode_field(3, WT_VARINT, _encode_varint(heartbeat))- )- req_id = f"hb_priv_{next_seq_no()}"- return encode_biz_msg(- service=_BIZ_PKG,- method="send_private_heartbeat",- req_id=req_id,- body=buf,- )+def encode_send_private_heartbeat(from_account: str, to_account: str, heartbeat: int = WS_HEARTBEAT_RUNNING) -> bytes:+ """SendPrivateHeartbeatReq{1 from_account, 2 to_account, 3 heartbeat (RUNNING=1, FINISH=2)} → ConnMsg bytes"""+ buf = _s(1, from_account) + _s(2, to_account) + _v(3, heartbeat)+ return _biz_request("send_private_heartbeat", "hb_priv", buf)def encode_send_group_heartbeat(- from_account: str,- group_code: str,- heartbeat: int = WS_HEARTBEAT_RUNNING,- send_time: int = 0,+ from_account: str, group_code: str, heartbeat: int = WS_HEARTBEAT_RUNNING, send_time: int = 0,) -> bytes:- """- 编码 SendGroupHeartbeatReq,返回完整 ConnMsg bytes。-- SendGroupHeartbeatReq fields:- 1: from_account (string)- 2: to_account (string) — 群场景留空- 3: group_code (string)- 4: send_time (int64, ms timestamp)- 5: heartbeat (varint: RUNNING=1, FINISH=2)- """+ """SendGroupHeartbeatReq{1 from_account, 2 to_account (群场景留空), 3 group_code,+ 4 send_time (ms; 0 → now), 5 heartbeat} → ConnMsg bytes"""import time as _timets = send_time or int(_time.time() * 1000)- buf = (- _encode_field(1, WT_LEN, _encode_string(from_account))- + _encode_field(2, WT_LEN, _encode_string("")) # to_account empty for group- + _encode_field(3, WT_LEN, _encode_string(group_code))- + _encode_field(4, WT_VARINT, _encode_varint(ts))- + _encode_field(5, WT_VARINT, _encode_varint(heartbeat))- )- req_id = f"hb_grp_{next_seq_no()}"- return encode_biz_msg(- service=_BIZ_PKG,- method="send_group_heartbeat",- req_id=req_id,- body=buf,- )-+ buf = _s(1, from_account) + _s(2, "") + _s(3, group_code) + _v(4, ts) + _v(5, heartbeat)+ return _biz_request("send_group_heartbeat", "hb_grp", buf)-# ============================================================-# 群信息查询-# ============================================================def encode_query_group_info(group_code: str) -> bytes:- """- 编码 QueryGroupInfoReq,返回完整 ConnMsg bytes。-- QueryGroupInfoReq fields:- 1: group_code (string)- """- buf = _encode_field(1, WT_LEN, _encode_string(group_code))- req_id = f"qgi_{next_seq_no()}"- return encode_biz_msg(- service=_BIZ_PKG,- method="query_group_info",- req_id=req_id,- body=buf,- )+ """QueryGroupInfoReq{1 group_code} → ConnMsg bytes"""+ return _biz_request("query_group_info", "qgi", _s(1, group_code))def decode_query_group_info_rsp(data: bytes) -> Optional[dict]:- """- 解码 QueryGroupInfoRsp biz payload。+ """解码 QueryGroupInfoRsp(对齐 TS biz-codec / member.ts queryGroupInfo)。- Proto 结构(对齐 TS biz-codec / member.ts queryGroupInfo):-- message QueryGroupInfoRsp {- int32 code = 1;- string message = 2;- GroupInfo group_info = 3; // 嵌套 message- }-- message GroupInfo {- string group_name = 1;- string group_owner_user_id = 2;- string group_owner_nickname = 3;- uint32 group_size = 4;- }-- Returns:- 解码后的 dict,或 None(解析失败)+ QueryGroupInfoRsp{1 code, 2 message, 3 GroupInfo{1 group_name, 2 group_owner_user_id,+ 3 group_owner_nickname, 4 group_size}} → {code, message?, group_name, owner_id,+ owner_nickname, member_count},解析失败返回 None。"""try:- fdict = _fields_to_dict(_parse_fields(data))- code = _get_varint(fdict, 1, 0)+ fdict = _parse_dict(data)+ result: dict = {"code": _get_varint(fdict, 1, 0)}msg = _get_string(fdict, 2)-- result: dict = {"code": code}if msg:result["message"] = msg-- # field 3 = nested GroupInfo message+ # field 3 taken regardless of wire type; non-bytes payloads fall back to defaultsgi_entries = fdict.get(3, [])gi_bytes = gi_entries[0][1] if gi_entries else b""- if gi_bytes and isinstance(gi_bytes, (bytes, bytearray)):- gi = _fields_to_dict(_parse_fields(gi_bytes))- result["group_name"] = _get_string(gi, 1) or ""- result["owner_id"] = _get_string(gi, 2) or ""- result["owner_nickname"] = _get_string(gi, 3) or ""- result["member_count"] = _get_varint(gi, 4, 0)- else:- result["group_name"] = ""- result["owner_id"] = ""- result["owner_nickname"] = ""- result["member_count"] = 0-+ gi = _parse_dict(gi_bytes) if gi_bytes and isinstance(gi_bytes, (bytes, bytearray)) else {}+ result["group_name"] = _get_string(gi, 1)+ result["owner_id"] = _get_string(gi, 2)+ result["owner_nickname"] = _get_string(gi, 3)+ result["member_count"] = _get_varint(gi, 4, 0)return resultexcept Exception:return None-# ============================================================-# 群成员列表查询-# ============================================================--def encode_get_group_member_list(- group_code: str,- offset: int = 0,- limit: int = 200,-) -> bytes:- """- 编码 GetGroupMemberListReq,返回完整 ConnMsg bytes。-- GetGroupMemberListReq fields:- 1: group_code (string)- 2: offset (uint32)- 3: limit (uint32)- """- buf = _encode_field(1, WT_LEN, _encode_string(group_code))+def encode_get_group_member_list(group_code: str, offset: int = 0, limit: int = 200) -> bytes:+ """GetGroupMemberListReq{1 group_code, 2 offset, 3 limit} → ConnMsg bytes"""+ buf = _s(1, group_code)if offset:- buf += _encode_field(2, WT_VARINT, _encode_varint(offset))- buf += _encode_field(3, WT_VARINT, _encode_varint(limit))- req_id = f"gml_{next_seq_no()}"- return encode_biz_msg(- service=_BIZ_PKG,- method="get_group_member_list",- req_id=req_id,- body=buf,- )+ buf += _v(2, offset)+ buf += _v(3, limit)+ return _biz_request("get_group_member_list", "gml", buf)def decode_get_group_member_list_rsp(data: bytes) -> Optional[dict]:- """- 解码 GetGroupMemberListRsp biz payload。-- GetGroupMemberListRsp fields:- 1: code (int32)- 2: message (string)- 3: members (repeated message MemberInfo)- 4: next_offset (uint32)- 5: is_complete (bool/varint)-- MemberInfo fields:- 1: user_id (string)- 2: nickname (string)- 3: role (uint32) — 0=member, 1=admin, 2=owner- 4: join_time (uint32)- 5: name_card (string) — 群昵称-- Returns:- {- "code": int,- "message": str,- "members": [{"user_id": str, "nickname": str, "role": int, ...}, ...],- "next_offset": int,- "is_complete": bool,- }- 或 None(解析失败)+ """解码 GetGroupMemberListRsp{1 code, 2 message, 3 members (repeated MemberInfo), 4 next_offset,+ 5 is_complete};MemberInfo{1 user_id, 2 nickname, 3 role (0=member,1=admin,2=owner),+ 4 join_time, 5 name_card (群昵称)}。member dict 过滤空值但保留 role;解析失败返回 None。"""try:- fdict = _fields_to_dict(_parse_fields(data))- code = _get_varint(fdict, 1, 0)-+ fdict = _parse_dict(data)members = []- for member_bytes in _get_repeated_bytes(fdict, 3):- mdict = _fields_to_dict(_parse_fields(member_bytes))+ for mdict in map(_parse_dict, _get_repeated_bytes(fdict, 3)):member = {"user_id": _get_string(mdict, 1),"nickname": _get_string(mdict, 2),@@ -1406,9 +756,8 @@ def decode_get_group_member_list_rsp(data: bytes) -> Optional[dict]:"name_card": _get_string(mdict, 5),}members.append({k: v for k, v in member.items() if v or k == "role"})-return {- "code": code,+ "code": _get_varint(fdict, 1, 0),"message": _get_string(fdict, 2),"members": members,"next_offset": _get_varint(fdict, 4),diff --git a/gateway/platforms/yuanbao_sticker.py b/gateway/platforms/yuanbao_sticker.pyindex 51f7f31c3e1..3119c38d793 100644--- a/gateway/platforms/yuanbao_sticker.py+++ b/gateway/platforms/yuanbao_sticker.py@@ -1,19 +1,11 @@"""-Yuanbao sticker (TIMFaceElem) support.--Ported from yuanbao-openclaw-plugin/src/sticker/.+Yuanbao sticker (TIMFaceElem) support. Ported from yuanbao-openclaw-plugin/src/sticker/.TIMFaceElem wire format:- {- "msg_type": "TIMFaceElem",- "msg_content": {- "index": 0, # always 0 per Yuanbao convention- "data": "<json>", # serialised sticker metadata- }- }--The `data` field carries a JSON string with the sticker's metadata so the-receiver can look up the correct asset in the emoji pack.+ {"msg_type": "TIMFaceElem",+ "msg_content": {"index": 0, # always 0 per Yuanbao convention+ "data": "<json>"}} # serialised sticker metadata so the receiver+ # can look up the asset in the emoji pack"""from __future__ import annotations@@ -24,350 +16,102 @@ import reimport unicodedatafrom typing import Optional-# ----------------------------------------------------------------------------# Sticker catalogue – ported from builtin-stickers.json-# Key : canonical name (Chinese)-# Value : {sticker_id, package_id, name, description, width, height, formats}-# ---------------------------------------------------------------------------+# Sticker catalogue – ported from builtin-stickers.json. Every builtin sticker is in+# package 1003, 128x128 png, with name == key; only (name, sticker_id, description) vary.+_STICKERS: list[tuple[str, str, str]] = [+ ("六六六", "278", "666 厉害 牛 棒 绝了 好强 awesome"),+ ("我想开了", "262", "想开 佛系 释怀 顿悟 看淡了 无所谓"),+ ("害羞", "130", "腼腆 不好意思 脸红 娇羞 羞涩 捂脸"),+ ("比心", "252", "笔芯 爱你 爱心手势 love heart 喜欢你"),+ ("委屈", "125", "难过 想哭 可怜巴巴 瘪嘴 受伤 被欺负"),+ ("亲亲", "146", "么么 mua 亲一下 kiss 飞吻 啵"),+ ("酷", "131", "帅 墨镜 cool 高冷 有型 swagger"),+ ("睡", "145", "睡觉 困 zzZ 打盹 躺平 休眠 sleepy"),+ ("发呆", "152", "懵 愣住 放空 呆滞 出神 脑子空白"),+ ("可怜", "157", "卖萌 求饶 委屈巴巴 弱小 拜托 眼巴巴"),+ ("摊手", "200", "无奈 没办法 耸肩 随便 那咋整 whatever"),+ ("头大", "213", "头疼 烦恼 郁闷 难搞 崩溃 一团乱"),+ ("吓", "256", "害怕 惊恐 震惊 吓一跳 恐怖 怂"),+ ("吐血", "203", "无语 崩溃 被雷 内伤 一口老血 屮"),+ ("哼", "185", "傲娇 生气 不满 撇嘴 不理 赌气"),+ ("嘿嘿", "220", "坏笑 猥琐笑 偷笑 憨笑 得意 你懂的"),+ ("头秃", "218", "程序员 加班 焦虑 没头发 秃了 肝爆"),+ ("暗中观察", "221", "窥屏 潜水 偷偷看 角落 围观 屏住呼吸"),+ ("我酸了", "224", "嫉妒 柠檬精 羡慕 吃柠檬 眼红 恰柠檬"),+ ("打call", "246", "应援 加油 支持 喝彩 助威 call"),+ ("庆祝", "251", "祝贺 开心 耶 party 胜利 干杯"),+ ("奋斗", "151", "努力 加油 拼搏 冲 干劲 卷起来"),+ ("惊讶", "143", "震惊 哇 不敢相信 OMG 居然 这么离谱"),+ ("疑问", "144", "问号 不懂 啥 为什么 啥情况 懵逼问"),+ ("仔细分析", "248", "思考 推敲 认真 研究 琢磨 让我想想"),+ ("撅嘴", "184", "嘟嘴 卖萌 不高兴 撒娇 嘴翘"),+ ("泪奔", "199", "大哭 伤心 破防 感动哭 泪流满面 呜呜"),+ ("尊嘟假嘟", "276", "真的假的 真假 可爱问 你骗我 是不是"),+ ("略略略", "113", "调皮 吐舌 不服 略 气死你 鬼脸"),+ ("困", "180", "想睡 倦 打哈欠 睁不开眼 好困啊 sleepy"),+ ("折磨", "181", "难受 痛苦 煎熬 蚌埠住了 受不了 要命"),+ ("抠鼻", "182", "不屑 无聊 淡定 无所谓 鄙视 挖鼻"),+ ("鼓掌", "183", "拍手 叫好 赞同 666 喝彩 掌声"),+ ("斜眼笑", "204", "滑稽 坏笑 doge 意味深长 阴阳怪气 嘿嘿嘿"),+ ("辣眼睛", "216", "看不下去 cringe 毁三观 太丑了 瞎了"),+ ("哦哟", "217", "惊讶 起哄 哇哦 有戏 不简单 哟"),+ ("吃瓜", "222", "围观 看戏 八卦 路人 看热闹 板凳"),+ ("狗头", "225", "doge 保命 开玩笑 滑稽 反讽 懂的都懂"),+ ("敬礼", "227", "salute 尊重 收到 遵命 致敬 报告"),+ ("哦", "231", "知道了 明白 敷衍 嗯 这样啊 收到"),+ ("拿到红包", "236", "红包 谢谢老板 发财 开心 抢到了 欧气"),+ ("牛吖", "239", "牛 厉害 强 666 佩服 大佬"),+ ("贴贴", "272", "抱抱 亲昵 蹭蹭 亲密 靠靠 撒娇贴"),+ ("爱心", "138", "心 love 喜欢你 红心 示爱 么么哒"),+ ("晚安", "170", "好梦 睡了 night 早点休息 安啦 moon"),+ ("太阳", "176", "晴天 早上好 阳光 morning 好天气 日"),+ ("柠檬", "266", "酸 嫉妒 柠檬精 羡慕 我酸 恰柠檬"),+ ("大冤种", "267", "倒霉 吃亏 自嘲 好心没好报 背锅 工具人"),+ ("吐了", "132", "恶心 yue 受不了 嫌弃 想吐 生理不适"),+ ("怒", "134", "生气 愤怒 火大 暴躁 气炸 怼"),+ ("玫瑰", "165", "花 示爱 表白 浪漫 送你花 情人节"),+ ("凋谢", "119", "花谢 失恋 难过 枯萎 心碎 凉了"),+ ("点赞", "159", "赞 认同 好棒 good like 大拇指 顶"),+ ("握手", "164", "合作 你好 商务 hello deal 成交 友好"),+ ("抱拳", "163", "谢谢 失敬 江湖 承让 拜托 有礼"),+ ("ok", "169", "好的 收到 没问题 okay 行 可以 懂了"),+ ("拳头", "174", "加油 干 冲 fight 力量 击拳 硬气"),+ ("鞭炮", "191", "过年 喜庆 爆竹 春节 噼里啪啦 红"),+ ("烟花", "258", "庆典 漂亮 新年 嘭 绽放 节日快乐"),+]+STICKER_MAP: dict[str, dict] = {- "六六六": {- "sticker_id": "278", "package_id": "1003", "name": "六六六",- "description": "666 厉害 牛 棒 绝了 好强 awesome",- "width": 128, "height": 128, "formats": "png",- },- "我想开了": {- "sticker_id": "262", "package_id": "1003", "name": "我想开了",- "description": "想开 佛系 释怀 顿悟 看淡了 无所谓",- "width": 128, "height": 128, "formats": "png",- },- "害羞": {- "sticker_id": "130", "package_id": "1003", "name": "害羞",- "description": "腼腆 不好意思 脸红 娇羞 羞涩 捂脸",- "width": 128, "height": 128, "formats": "png",- },- "比心": {- "sticker_id": "252", "package_id": "1003", "name": "比心",- "description": "笔芯 爱你 爱心手势 love heart 喜欢你",- "width": 128, "height": 128, "formats": "png",- },- "委屈": {- "sticker_id": "125", "package_id": "1003", "name": "委屈",- "description": "难过 想哭 可怜巴巴 瘪嘴 受伤 被欺负",- "width": 128, "height": 128, "formats": "png",- },- "亲亲": {- "sticker_id": "146", "package_id": "1003", "name": "亲亲",- "description": "么么 mua 亲一下 kiss 飞吻 啵",- "width": 128, "height": 128, "formats": "png",- },- "酷": {- "sticker_id": "131", "package_id": "1003", "name": "酷",- "description": "帅 墨镜 cool 高冷 有型 swagger",- "width": 128, "height": 128, "formats": "png",- },- "睡": {- "sticker_id": "145", "package_id": "1003", "name": "睡",- "description": "睡觉 困 zzZ 打盹 躺平 休眠 sleepy",- "width": 128, "height": 128, "formats": "png",- },- "发呆": {- "sticker_id": "152", "package_id": "1003", "name": "发呆",- "description": "懵 愣住 放空 呆滞 出神 脑子空白",- "width": 128, "height": 128, "formats": "png",- },- "可怜": {- "sticker_id": "157", "package_id": "1003", "name": "可怜",- "description": "卖萌 求饶 委屈巴巴 弱小 拜托 眼巴巴",- "width": 128, "height": 128, "formats": "png",- },- "摊手": {- "sticker_id": "200", "package_id": "1003", "name": "摊手",- "description": "无奈 没办法 耸肩 随便 那咋整 whatever",- "width": 128, "height": 128, "formats": "png",- },- "头大": {- "sticker_id": "213", "package_id": "1003", "name": "头大",- "description": "头疼 烦恼 郁闷 难搞 崩溃 一团乱",- "width": 128, "height": 128, "formats": "png",- },- "吓": {- "sticker_id": "256", "package_id": "1003", "name": "吓",- "description": "害怕 惊恐 震惊 吓一跳 恐怖 怂",- "width": 128, "height": 128, "formats": "png",- },- "吐血": {- "sticker_id": "203", "package_id": "1003", "name": "吐血",- "description": "无语 崩溃 被雷 内伤 一口老血 屮",- "width": 128, "height": 128, "formats": "png",- },- "哼": {- "sticker_id": "185", "package_id": "1003", "name": "哼",- "description": "傲娇 生气 不满 撇嘴 不理 赌气",- "width": 128, "height": 128, "formats": "png",- },- "嘿嘿": {- "sticker_id": "220", "package_id": "1003", "name": "嘿嘿",- "description": "坏笑 猥琐笑 偷笑 憨笑 得意 你懂的",- "width": 128, "height": 128, "formats": "png",- },- "头秃": {- "sticker_id": "218", "package_id": "1003", "name": "头秃",- "description": "程序员 加班 焦虑 没头发 秃了 肝爆",- "width": 128, "height": 128, "formats": "png",- },- "暗中观察": {- "sticker_id": "221", "package_id": "1003", "name": "暗中观察",- "description": "窥屏 潜水 偷偷看 角落 围观 屏住呼吸",- "width": 128, "height": 128, "formats": "png",- },- "我酸了": {- "sticker_id": "224", "package_id": "1003", "name": "我酸了",- "description": "嫉妒 柠檬精 羡慕 吃柠檬 眼红 恰柠檬",- "width": 128, "height": 128, "formats": "png",- },- "打call": {- "sticker_id": "246", "package_id": "1003", "name": "打call",- "description": "应援 加油 支持 喝彩 助威 call",- "width": 128, "height": 128, "formats": "png",- },- "庆祝": {- "sticker_id": "251", "package_id": "1003", "name": "庆祝",- "description": "祝贺 开心 耶 party 胜利 干杯",- "width": 128, "height": 128, "formats": "png",- },- "奋斗": {- "sticker_id": "151", "package_id": "1003", "name": "奋斗",- "description": "努力 加油 拼搏 冲 干劲 卷起来",- "width": 128, "height": 128, "formats": "png",- },- "惊讶": {- "sticker_id": "143", "package_id": "1003", "name": "惊讶",- "description": "震惊 哇 不敢相信 OMG 居然 这么离谱",- "width": 128, "height": 128, "formats": "png",- },- "疑问": {- "sticker_id": "144", "package_id": "1003", "name": "疑问",- "description": "问号 不懂 啥 为什么 啥情况 懵逼问",- "width": 128, "height": 128, "formats": "png",- },- "仔细分析": {- "sticker_id": "248", "package_id": "1003", "name": "仔细分析",- "description": "思考 推敲 认真 研究 琢磨 让我想想",- "width": 128, "height": 128, "formats": "png",- },- "撅嘴": {- "sticker_id": "184", "package_id": "1003", "name": "撅嘴",- "description": "嘟嘴 卖萌 不高兴 撒娇 嘴翘",- "width": 128, "height": 128, "formats": "png",- },- "泪奔": {- "sticker_id": "199", "package_id": "1003", "name": "泪奔",- "description": "大哭 伤心 破防 感动哭 泪流满面 呜呜",- "width": 128, "height": 128, "formats": "png",- },- "尊嘟假嘟": {- "sticker_id": "276", "package_id": "1003", "name": "尊嘟假嘟",- "description": "真的假的 真假 可爱问 你骗我 是不是",- "width": 128, "height": 128, "formats": "png",- },- "略略略": {- "sticker_id": "113", "package_id": "1003", "name": "略略略",- "description": "调皮 吐舌 不服 略 气死你 鬼脸",- "width": 128, "height": 128, "formats": "png",- },- "困": {- "sticker_id": "180", "package_id": "1003", "name": "困",- "description": "想睡 倦 打哈欠 睁不开眼 好困啊 sleepy",- "width": 128, "height": 128, "formats": "png",- },- "折磨": {- "sticker_id": "181", "package_id": "1003", "name": "折磨",- "description": "难受 痛苦 煎熬 蚌埠住了 受不了 要命",- "width": 128, "height": 128, "formats": "png",- },- "抠鼻": {- "sticker_id": "182", "package_id": "1003", "name": "抠鼻",- "description": "不屑 无聊 淡定 无所谓 鄙视 挖鼻",- "width": 128, "height": 128, "formats": "png",- },- "鼓掌": {- "sticker_id": "183", "package_id": "1003", "name": "鼓掌",- "description": "拍手 叫好 赞同 666 喝彩 掌声",- "width": 128, "height": 128, "formats": "png",- },- "斜眼笑": {- "sticker_id": "204", "package_id": "1003", "name": "斜眼笑",- "description": "滑稽 坏笑 doge 意味深长 阴阳怪气 嘿嘿嘿",- "width": 128, "height": 128, "formats": "png",- },- "辣眼睛": {- "sticker_id": "216", "package_id": "1003", "name": "辣眼睛",- "description": "看不下去 cringe 毁三观 太丑了 瞎了",- "width": 128, "height": 128, "formats": "png",- },- "哦哟": {- "sticker_id": "217", "package_id": "1003", "name": "哦哟",- "description": "惊讶 起哄 哇哦 有戏 不简单 哟",- "width": 128, "height": 128, "formats": "png",- },- "吃瓜": {- "sticker_id": "222", "package_id": "1003", "name": "吃瓜",- "description": "围观 看戏 八卦 路人 看热闹 板凳",- "width": 128, "height": 128, "formats": "png",- },- "狗头": {- "sticker_id": "225", "package_id": "1003", "name": "狗头",- "description": "doge 保命 开玩笑 滑稽 反讽 懂的都懂",- "width": 128, "height": 128, "formats": "png",- },- "敬礼": {- "sticker_id": "227", "package_id": "1003", "name": "敬礼",- "description": "salute 尊重 收到 遵命 致敬 报告",+ name: {+ "sticker_id": sid, "package_id": "1003", "name": name, "description": desc,"width": 128, "height": 128, "formats": "png",- },- "哦": {- "sticker_id": "231", "package_id": "1003", "name": "哦",- "description": "知道了 明白 敷衍 嗯 这样啊 收到",- "width": 128, "height": 128, "formats": "png",- },- "拿到红包": {- "sticker_id": "236", "package_id": "1003", "name": "拿到红包",- "description": "红包 谢谢老板 发财 开心 抢到了 欧气",- "width": 128, "height": 128, "formats": "png",- },- "牛吖": {- "sticker_id": "239", "package_id": "1003", "name": "牛吖",- "description": "牛 厉害 强 666 佩服 大佬",- "width": 128, "height": 128, "formats": "png",- },- "贴贴": {- "sticker_id": "272", "package_id": "1003", "name": "贴贴",- "description": "抱抱 亲昵 蹭蹭 亲密 靠靠 撒娇贴",- "width": 128, "height": 128, "formats": "png",- },- "爱心": {- "sticker_id": "138", "package_id": "1003", "name": "爱心",- "description": "心 love 喜欢你 红心 示爱 么么哒",- "width": 128, "height": 128, "formats": "png",- },- "晚安": {- "sticker_id": "170", "package_id": "1003", "name": "晚安",- "description": "好梦 睡了 night 早点休息 安啦 moon",- "width": 128, "height": 128, "formats": "png",- },- "太阳": {- "sticker_id": "176", "package_id": "1003", "name": "太阳",- "description": "晴天 早上好 阳光 morning 好天气 日",- "width": 128, "height": 128, "formats": "png",- },- "柠檬": {- "sticker_id": "266", "package_id": "1003", "name": "柠檬",- "description": "酸 嫉妒 柠檬精 羡慕 我酸 恰柠檬",- "width": 128, "height": 128, "formats": "png",- },- "大冤种": {- "sticker_id": "267", "package_id": "1003", "name": "大冤种",- "description": "倒霉 吃亏 自嘲 好心没好报 背锅 工具人",- "width": 128, "height": 128, "formats": "png",- },- "吐了": {- "sticker_id": "132", "package_id": "1003", "name": "吐了",- "description": "恶心 yue 受不了 嫌弃 想吐 生理不适",- "width": 128, "height": 128, "formats": "png",- },- "怒": {- "sticker_id": "134", "package_id": "1003", "name": "怒",- "description": "生气 愤怒 火大 暴躁 气炸 怼",- "width": 128, "height": 128, "formats": "png",- },- "玫瑰": {- "sticker_id": "165", "package_id": "1003", "name": "玫瑰",- "description": "花 示爱 表白 浪漫 送你花 情人节",- "width": 128, "height": 128, "formats": "png",- },- "凋谢": {- "sticker_id": "119", "package_id": "1003", "name": "凋谢",- "description": "花谢 失恋 难过 枯萎 心碎 凉了",- "width": 128, "height": 128, "formats": "png",- },- "点赞": {- "sticker_id": "159", "package_id": "1003", "name": "点赞",- "description": "赞 认同 好棒 good like 大拇指 顶",- "width": 128, "height": 128, "formats": "png",- },- "握手": {- "sticker_id": "164", "package_id": "1003", "name": "握手",- "description": "合作 你好 商务 hello deal 成交 友好",- "width": 128, "height": 128, "formats": "png",- },- "抱拳": {- "sticker_id": "163", "package_id": "1003", "name": "抱拳",- "description": "谢谢 失敬 江湖 承让 拜托 有礼",- "width": 128, "height": 128, "formats": "png",- },- "ok": {- "sticker_id": "169", "package_id": "1003", "name": "ok",- "description": "好的 收到 没问题 okay 行 可以 懂了",- "width": 128, "height": 128, "formats": "png",- },- "拳头": {- "sticker_id": "174", "package_id": "1003", "name": "拳头",- "description": "加油 干 冲 fight 力量 击拳 硬气",- "width": 128, "height": 128, "formats": "png",- },- "鞭炮": {- "sticker_id": "191", "package_id": "1003", "name": "鞭炮",- "description": "过年 喜庆 爆竹 春节 噼里啪啦 红",- "width": 128, "height": 128, "formats": "png",- },- "烟花": {- "sticker_id": "258", "package_id": "1003", "name": "烟花",- "description": "庆典 漂亮 新年 嘭 绽放 节日快乐",- "width": 128, "height": 128, "formats": "png",- },+ }+ for name, sid, desc in _STICKERS}def get_sticker_by_name(name: str) -> Optional[dict]:- """- 按名称查找贴纸,支持模糊匹配。+ """按名称查找贴纸,支持模糊匹配。- 匹配优先级:- 1. 完全相等(name)- 2. name 包含查询词(前缀/子串)- 3. description 包含查询词(同义词搜索)- 4. 通用模糊评分(与 sticker-search 同算法),命中即返回得分最高的一条-- 返回 sticker dict,找不到返回 None。+ 匹配优先级:完全相等 → name 与查询词互为子串 → description 包含查询词 →+ search_stickers 模糊评分最高的一条。找不到返回 None。"""if not name:return None-query = name.strip()-if query in STICKER_MAP:return STICKER_MAP[query]-for key, sticker in STICKER_MAP.items():if query in key or key in query:return sticker-for sticker in STICKER_MAP.values():- desc = sticker.get("description", "")- if query in desc:+ if query in sticker.get("description", ""):return sticker-matches = search_stickers(query, limit=1)return matches[0] if matches else Nonedef get_random_sticker(category: str = None) -> dict:- """- 随机返回一个贴纸。-- 若指定 category,则在 description 中含有该关键词的贴纸里随机选取;- category 为 None 时从全表随机。- """+ """随机贴纸;指定 category 时优先在 description/name 含该词的贴纸中选取。"""if category:candidates = [s for s in STICKER_MAP.values()@@ -383,10 +127,7 @@ def get_sticker_by_id(sticker_id: str) -> Optional[dict]:if not sticker_id:return Nonesid = str(sticker_id).strip()- for sticker in STICKER_MAP.values():- if sticker.get("sticker_id") == sid:- return sticker- return None+ return next((s for s in STICKER_MAP.values() if s.get("sticker_id") == sid), None)# ---------------------------------------------------------------------------@@ -466,70 +207,43 @@ def _score_field(haystack: str, query: str) -> float:def search_stickers(query: str, limit: int = 10) -> list[dict]:- """- 在内置贴纸表中按模糊匹配排序返回前 N 条结果。+ """内置贴纸表按模糊匹配排序返回前 N 条。- 评分综合 name/description 字段的子串、字符多重集覆盖、bigram Jaccard、子序列比例。- name 权重略高于 description(×0.88)。空 query 时按字典顺序返回前 N 条。+ 评分综合 name/description 的子串、字符多重集覆盖、bigram Jaccard、子序列比例,+ name 权重高于 description(×0.88);sticker_id 精确/子串命中另计。空 query 按表顺序返回。"""safe_limit = max(1, min(500, int(limit) if limit else 10))- if not query or not _normalize_text(query):+ q_norm = _normalize_text(query)+ if not query or not q_norm:return list(STICKER_MAP.values())[:safe_limit]scored: list[tuple[float, dict]] = []for sticker in STICKER_MAP.values():name_s = _score_field(sticker.get("name", ""), query)desc_s = _score_field(sticker.get("description", ""), query) * 0.88- sid = str(sticker.get("sticker_id", "")).strip()- q_norm = _normalize_text(query)- id_s = 0.0- if sid and q_norm:- sid_norm = _normalize_text(sid)- if sid_norm == q_norm:- id_s = 100.0- elif q_norm in sid_norm:- id_s = 84.0+ sid_norm = _normalize_text(str(sticker.get("sticker_id", "")).strip())+ id_s = 100.0 if sid_norm == q_norm else 84.0 if sid_norm and q_norm in sid_norm else 0.0scored.append((max(name_s, desc_s, id_s), sticker))scored.sort(key=lambda x: x[0], reverse=True)top = scored[0][0] if scored else 0if top <= 0:return [s for _, s in scored[:safe_limit]]-if top >= 22:floor = 18.0elif top >= 12:floor = max(10.0, top * 0.5)else:floor = max(6.0, top * 0.35)-filtered = [pair for pair in scored if pair[0] >= floor]- out = filtered if filtered else scored- return [s for _, s in out[:safe_limit]]---def build_face_msg_body(- face_index: int,- face_type: int = 1,- data: Optional[str] = None,-) -> list:- """- 构造 TIMFaceElem 消息体。-- Yuanbao 约定:- - index 固定传 0(服务端通过 data 字段识别具体表情)- - data 为 JSON 字符串,包含 sticker_id / package_id 等字段+ return [s for _, s in (filtered or scored)[:safe_limit]]- Args:- face_index: 保留字段,暂时不影响 wire format(Yuanbao 固定 index=0)。- 当 face_index > 0 时视为旧版 QQ 表情 ID,直接放入 index。- face_type: 保留字段(兼容旧接口,当前未使用)。- data: 已序列化的 JSON 字符串;为 None 时仅传 index。- Returns:- 符合 Yuanbao TIM 协议的 msg_body list,如::+def build_face_msg_body(face_index: int, face_type: int = 1, data: Optional[str] = None) -> list:+ """构造 TIMFaceElem 消息体。- [{"msg_type": "TIMFaceElem", "msg_content": {"index": 0, "data": "..."}}]+ Yuanbao 约定 index 固定 0(服务端通过 data 字段识别表情);face_index > 0 视为旧版 QQ 表情 ID。+ face_type 为兼容旧接口保留,不影响 wire format。data 为 None 时仅传 index。"""msg_content: dict = {"index": face_index}if data is not None:@@ -538,11 +252,7 @@ def build_face_msg_body(def build_sticker_msg_body(sticker: dict) -> list:- """- 从 STICKER_MAP 中的 sticker dict 直接构造 TIMFaceElem 消息体。-- 这是 send_sticker() 的内部辅助,确保 data 字段与原始 JS 插件一致。- """+ """从 STICKER_MAP 的 sticker dict 构造 TIMFaceElem 消息体(data 字段与原始 JS 插件一致)。"""data_payload = json.dumps({"sticker_id": sticker["sticker_id"],