adapter.py 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672
  1. """QQ Bot platform adapter (Official QQ Bot API v2): WebSocket gateway for inbound
  2. events, REST (``api.sgroup.qq.com``) for outbound messages and media uploads.
  3. config.yaml ``platforms.qq.extra``: app_id / client_secret (or QQ_APP_ID /
  4. QQ_CLIENT_SECRET), markdown_support, dm_policy + allow_from, group_policy +
  5. group_allow_from (open | allowlist | disabled | pairing), and optional ``stt``
  6. {provider, baseUrl, apiKey, model} (or QQ_STT_* env vars). Voice transcription
  7. tries QQ's free ``asr_refer_text`` first, then the configured STT provider.
  8. """
  9. from __future__ import annotations
  10. from pm import install_hint
  11. import asyncio
  12. import contextlib
  13. import json
  14. import logging
  15. import os
  16. import re
  17. import time
  18. import uuid
  19. from datetime import datetime, timezone, UTC
  20. from pathlib import Path
  21. from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple
  22. from urllib.parse import urlparse
  23. try:
  24. import aiohttp
  25. AIOHTTP_AVAILABLE = True
  26. except ImportError:
  27. AIOHTTP_AVAILABLE = False
  28. aiohttp = None # type: ignore[assignment]
  29. try:
  30. import httpx
  31. HTTPX_AVAILABLE = True
  32. except ImportError:
  33. HTTPX_AVAILABLE = False
  34. httpx = None # type: ignore[assignment]
  35. from gateway.config import Platform, PlatformConfig
  36. from gateway.platforms.base import (
  37. gateway_trust_env, BasePlatformAdapter, ExecApprovalPrompt, SendResult,
  38. cache_document_from_bytes_async, cache_image_from_bytes_async,
  39. )
  40. from gateway.platforms.event import MessageEvent, MessageType
  41. from gateway.platforms.helpers import strip_markdown
  42. from gateway.platforms.helpers import MessageDeduplicator, cancel_task, platform_http_client
  43. from gateway.platforms.access_policy_mixin import OwnAccessPolicyMixin
  44. from gateway.platforms.media_cache import ext_for_mime
  45. logger = logging.getLogger(__name__)
  46. class QQCloseError(Exception):
  47. """Raised when the QQ WebSocket closes; carries code + reason for the reconnect loop."""
  48. def __init__(self, code, reason=""):
  49. self.code = int(code) if code else None
  50. self.reason = str(reason) if reason else ""
  51. super().__init__(f"WebSocket closed (code={self.code}, reason={self.reason})")
  52. from .constants import (
  53. API_BASE, TOKEN_URL, GATEWAY_URL_PATH, DEFAULT_API_TIMEOUT, FILE_UPLOAD_TIMEOUT,
  54. CONNECT_TIMEOUT_SECONDS, RECONNECT_BACKOFF, MAX_RECONNECT_ATTEMPTS, RATE_LIMIT_DELAY,
  55. QUICK_DISCONNECT_THRESHOLD, MAX_QUICK_DISCONNECT_COUNT, MAX_MESSAGE_LENGTH,
  56. DEDUP_WINDOW_SECONDS, DEDUP_MAX_SIZE, MSG_TYPE_TEXT, MSG_TYPE_MARKDOWN, MSG_TYPE_MEDIA,
  57. MSG_TYPE_INPUT_NOTIFY, MEDIA_TYPE_IMAGE, MEDIA_TYPE_VIDEO, MEDIA_TYPE_VOICE, MEDIA_TYPE_FILE)
  58. from .utils import coerce_list as _coerce_list, build_user_agent
  59. from .chunked_upload import (
  60. ChunkedUploader, UploadDailyLimitExceededError, UploadFileTooLargeError)
  61. from .keyboards import (
  62. ApprovalRequest, InlineKeyboard, InteractionEvent, build_approval_keyboard,
  63. build_update_prompt_keyboard, parse_approval_button_data, parse_interaction_event,
  64. parse_update_prompt_button_data)
  65. from gateway.platforms._shared import get_scoped_secret as _resolve_qq_secret
  66. def check_qq_requirements() -> bool:
  67. return AIOHTTP_AVAILABLE and HTTPX_AVAILABLE
  68. _VOICE_EXTENSIONS = (".silk", ".amr", ".mp3", ".wav", ".ogg", ".m4a", ".aac", ".speex", ".flac")
  69. _STT_PROVIDER_BASE_URLS = {
  70. "zai": "https://open.bigmodel.cn/api/coding/paas/v4",
  71. # Aliases that target direct REST APIs not modeled as first-class providers in PROVIDER_REGISTRY. Used
  72. # for ``auxiliary.<task>.provider`` so users can write the obvious name and have it resolve to a working
  73. # ``custom`` endpoint without needing to know our internal provider IDs. Why these specifically:
  74. # PROVIDER_REGISTRY has ``openai-codex`` (OAuth) and ``custom`` (manual base_url + OPENAI_API_KEY) but
  75. # no plain ``openai`` for direct API-key access. Users predictably type ``provider: openai`` and expect
  76. # it to use OPENAI_API_KEY against api.openai.com. Previously this silently fell back to the user's main
  77. # provider, sending OpenAI model names to e.g. DeepSeek and producing cryptic ``unknown variant
  78. # 'image_url'`` errors (issue #31179).
  79. "openai": "https://api.openai.com/v1",
  80. "glm": "https://open.bigmodel.cn/api/coding/paas/v4"}
  81. _AUDIO_URL_EXTENSIONS = {".silk", ".amr", ".mp3", ".wav", ".ogg", ".m4a", ".aac", ".flac"}
  82. class QQAdapter(OwnAccessPolicyMixin, BasePlatformAdapter):
  83. """QQ Bot adapter backed by the official QQ Bot WebSocket Gateway + REST API."""
  84. # QQ Bot API does not support editing sent messages.
  85. SUPPORTS_MESSAGE_EDITING = False
  86. MAX_MESSAGE_LENGTH = MAX_MESSAGE_LENGTH
  87. ALLOW_ALL_ENV_PREFIX = "QQ"
  88. _TYPING_INPUT_SECONDS = 60 # input_notify duration reported to QQ
  89. _TYPING_DEBOUNCE_SECONDS = 50 # refresh before it expires
  90. # WS close codes that are unrecoverable → stop reconnecting.
  91. _FATAL_CLOSE_CODES = {
  92. 4001: "invalid opcode", 4002: "invalid payload", 4010: "invalid shard",
  93. 4011: "sharding required", 4012: "invalid API version", 4013: "invalid intent",
  94. 4014: "intent not authorized", 4914: "offline/sandbox-only", 4915: "banned"}
  95. # WS close codes that invalidate the session → clear it and re-identify on
  96. # the next Hello. 4009 (connection timeout) is deliberately absent: it is
  97. # resumable per the QQ protocol and must keep session state.
  98. _SESSION_INVALID_CLOSE_CODES = {4006, 4007} | set(range(4900, 4914))
  99. @property
  100. def _log_tag(self) -> str:
  101. """Log prefix including app_id for multi-instance disambiguation."""
  102. app_id = getattr(self, "_app_id", None)
  103. return f"QQBot:{app_id}" if app_id else "QQBot"
  104. def _fail_pending(self, reason: str) -> None:
  105. for fut in self._pending_responses.values():
  106. if not fut.done():
  107. fut.set_exception(RuntimeError(reason))
  108. self._pending_responses.clear()
  109. def _mark_transport_disconnected(self) -> None:
  110. """Mark QQ WS down without stopping the reconnect loop (base's _running
  111. doubles as lifecycle flag; the listener must survive transient drops)."""
  112. if self.has_fatal_error:
  113. return
  114. self._write_runtime_status_safe(
  115. "disconnected", platform_state="disconnected", error_code=None, error_message=None)
  116. @property
  117. def is_connected(self) -> bool:
  118. """Return True only when the QQ WebSocket transport is usable."""
  119. return bool(self._running and self._ws and not self._ws.closed)
  120. def __init__(self, config: PlatformConfig):
  121. super().__init__(config, Platform.QQBOT)
  122. extra = config.extra or {}
  123. self._app_id = str(extra.get("app_id") or _resolve_qq_secret("QQ_APP_ID", "")).strip()
  124. self._client_secret = str(extra.get("client_secret") or _resolve_qq_secret("QQ_CLIENT_SECRET", "")).strip()
  125. self._markdown_support = bool(extra.get("markdown_support", True))
  126. self._dm_policy = str(extra.get("dm_policy", "pairing")).strip().lower()
  127. self._allow_from = _coerce_list(extra.get("allow_from") or extra.get("allowFrom"))
  128. self._group_policy = str(extra.get("group_policy", "pairing")).strip().lower()
  129. self._group_allow_from = _coerce_list(extra.get("group_allow_from") or extra.get("groupAllowFrom"))
  130. self._session: Optional[aiohttp.ClientSession] = None
  131. self._ws: Optional[aiohttp.ClientWebSocketResponse] = None
  132. self._http_client: Optional[httpx.AsyncClient] = None
  133. self._listen_task: Optional[asyncio.Task] = None
  134. self._heartbeat_task: Optional[asyncio.Task] = None
  135. self._heartbeat_interval: float = 30.0 # seconds, updated by Hello
  136. self._session_id: Optional[str] = None
  137. self._last_seq: Optional[int] = None
  138. self._chat_type_map: dict[str, str] = {} # chat_id → "c2c"|"group"|"guild"|"dm"
  139. self._pending_responses: dict[str, asyncio.Future] = {} # request/response correlation
  140. self._dedup = MessageDeduplicator(max_size=DEDUP_MAX_SIZE, ttl_seconds=DEDUP_WINDOW_SECONDS)
  141. self._last_msg_id: dict[str, str] = {} # last inbound message ID per chat (send_typing)
  142. self._typing_sent_at: dict[str, float] = {} # typing debounce: chat_id → last send_typing ts
  143. self._access_token: Optional[str] = None
  144. self._token_expires_at: float = 0.0
  145. self._token_lock = asyncio.Lock()
  146. # Inline-keyboard interaction routing: invoked for every INTERACTION_CREATE
  147. # after the adapter ACKed it. Defaults to the approval/update-prompt
  148. # dispatcher; override via set_interaction_callback() (None drops clicks).
  149. self._interaction_callback: Optional[Callable[[InteractionEvent], Awaitable[None]]] = (
  150. self._default_interaction_dispatch)
  151. # ── Properties ──
  152. @property
  153. def name(self) -> str:
  154. return "QQBot"
  155. # ── Connection lifecycle ──
  156. async def connect(self, *, is_reconnect: bool = False) -> bool:
  157. """Authenticate, obtain gateway URL, and open the WebSocket. ``is_reconnect``
  158. is accepted for interface conformance only (QQBot has no server-side update queue)."""
  159. for ok, code, what, hint in (
  160. (AIOHTTP_AVAILABLE, "qq_missing_dependency", "aiohttp not installed",
  161. f". Run: {install_hint('messaging')}"),
  162. (HTTPX_AVAILABLE, "qq_missing_dependency", "httpx not installed", ". Run: hermes pm repair"),
  163. (self._app_id and self._client_secret, "qq_missing_credentials",
  164. "QQ_APP_ID and QQ_CLIENT_SECRET are required", "")):
  165. if not ok:
  166. message = f"QQ startup failed: {what}"
  167. self._set_fatal_error(code, message, retryable=True)
  168. logger.warning("[%s] %s%s", self._log_tag, message, hint)
  169. return False
  170. if not self._acquire_platform_lock("qqbot-appid", self._app_id, "QQBot app ID"):
  171. return False
  172. try:
  173. # Tighter keepalive pool so idle CLOSE_WAIT sockets drain faster behind proxies.
  174. # See #18451.
  175. self._http_client = platform_http_client()
  176. await self._open_gateway_ws(log_url=True)
  177. self._listen_task = asyncio.create_task(self._listen_loop())
  178. self._heartbeat_task = asyncio.create_task(self._heartbeat_loop())
  179. self._mark_connected()
  180. logger.info("[%s] Connected", self._log_tag)
  181. self._wire_plugin_handlers(None)
  182. return True
  183. except Exception as exc:
  184. message = f"QQ startup failed: {exc}"
  185. self._set_fatal_error("qq_connect_error", message, retryable=True)
  186. logger.error("[%s] %s", self._log_tag, message, exc_info=True)
  187. await self._cleanup()
  188. self._release_platform_lock()
  189. return False
  190. async def disconnect(self) -> None:
  191. self._running = False
  192. self._mark_disconnected()
  193. await cancel_task(self._listen_task)
  194. await cancel_task(self._heartbeat_task)
  195. self._listen_task = self._heartbeat_task = None
  196. await self._cleanup()
  197. self._release_platform_lock()
  198. logger.info("[%s] Disconnected", self._log_tag)
  199. async def _close_ws(self) -> None:
  200. """Close the WebSocket + its aiohttp session (keeps _http_client alive)."""
  201. if self._ws and not self._ws.closed:
  202. await self._ws.close()
  203. self._ws = None
  204. if self._session and not self._session.closed:
  205. await self._session.close()
  206. self._session = None
  207. async def _cleanup(self) -> None:
  208. """Close WebSocket, HTTP session, and client; fail pending futures."""
  209. await self._close_ws()
  210. if self._http_client:
  211. await self._http_client.aclose()
  212. self._http_client = None
  213. self._fail_pending("Disconnected")
  214. # ── Token management ──
  215. async def _fetch_json(self, what: str, request: Callable[[], Awaitable[Any]]) -> dict[str, Any]:
  216. """Run an httpx request and return its JSON; any failure → RuntimeError."""
  217. try:
  218. resp = await request()
  219. resp.raise_for_status()
  220. return resp.json()
  221. except Exception as exc:
  222. raise RuntimeError(f"Failed to get QQ Bot {what}: {exc}") from exc
  223. def _token_fresh(self) -> bool:
  224. return bool(self._access_token) and time.time() < self._token_expires_at - 60
  225. async def _ensure_token(self) -> str:
  226. """Return a valid access token, refreshing if needed (with singleflight)."""
  227. if self._token_fresh():
  228. return self._access_token
  229. async with self._token_lock:
  230. if self._token_fresh(): # double-check after acquiring lock
  231. return self._access_token
  232. data = await self._fetch_json("access token", lambda: self._http_client.post(
  233. TOKEN_URL, json={"appId": self._app_id, "clientSecret": self._client_secret},
  234. timeout=DEFAULT_API_TIMEOUT))
  235. token = data.get("access_token")
  236. if not token:
  237. raise RuntimeError(f"QQ Bot token response missing access_token: {data}")
  238. expires_in = int(data.get("expires_in", 7200))
  239. self._access_token = token
  240. self._token_expires_at = time.time() + expires_in
  241. logger.info("[%s] Access token refreshed, expires in %ds", self._log_tag, expires_in)
  242. return self._access_token
  243. async def _get_gateway_url(self) -> str:
  244. token = await self._ensure_token()
  245. data = await self._fetch_json("gateway URL", lambda: self._http_client.get(
  246. f"{API_BASE}{GATEWAY_URL_PATH}",
  247. headers={"Authorization": f"QQBot {token}", "User-Agent": build_user_agent()},
  248. timeout=DEFAULT_API_TIMEOUT))
  249. url = data.get("url")
  250. if not url:
  251. raise RuntimeError(f"QQ Bot gateway response missing url: {data}")
  252. return url
  253. # ── WebSocket lifecycle ──
  254. async def _open_gateway_ws(self, *, log_url: bool = False) -> None:
  255. """Token → gateway URL → WebSocket (shared by connect and _reconnect)."""
  256. await self._ensure_token()
  257. gateway_url = await self._get_gateway_url()
  258. if log_url:
  259. logger.info("[%s] Gateway URL: %s", self._log_tag, gateway_url)
  260. await self._open_ws(gateway_url)
  261. async def _open_ws(self, gateway_url: str) -> None:
  262. await self._close_ws()
  263. # Honor proxy env vars for the WebSocket (WSL setups need this).
  264. self._session = aiohttp.ClientSession(trust_env=gateway_trust_env())
  265. proxy_vars = ("WSS_PROXY", "wss_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy")
  266. ws_proxy = next((v for v in map(os.getenv, proxy_vars) if v), None)
  267. self._ws = await self._session.ws_connect(
  268. gateway_url, headers={"User-Agent": build_user_agent()}, timeout=CONNECT_TIMEOUT_SECONDS, proxy=ws_proxy,
  269. )
  270. logger.info("[%s] WebSocket connected to %s", self._log_tag, gateway_url)
  271. async def _listen_loop(self) -> None:
  272. """Read WebSocket events and reconnect on errors. Close codes: 4004 → refresh
  273. token; 4006/4007/49xx → clear session and re-identify; 4008 → rate limited,
  274. back off; _FATAL_CLOSE_CODES → stop."""
  275. backoff_idx = 0
  276. connect_time = 0.0
  277. quick_disconnect_count = 0
  278. async def reconnect() -> None:
  279. nonlocal backoff_idx, quick_disconnect_count
  280. if await self._reconnect(backoff_idx):
  281. backoff_idx = quick_disconnect_count = 0
  282. else:
  283. backoff_idx += 1
  284. while self._running:
  285. try:
  286. connect_time = time.monotonic()
  287. await self._read_events()
  288. backoff_idx = quick_disconnect_count = 0
  289. except asyncio.CancelledError:
  290. return
  291. except QQCloseError as exc:
  292. if not self._running:
  293. return
  294. code = exc.code
  295. logger.warning("[%s] WebSocket closed: code=%s reason=%s", self._log_tag, code, exc.reason)
  296. # Quick disconnect detection (permission issues, misconfiguration)
  297. duration = time.monotonic() - connect_time
  298. if duration < QUICK_DISCONNECT_THRESHOLD and connect_time > 0:
  299. quick_disconnect_count += 1
  300. logger.info(
  301. "[%s] Quick disconnect (%.1fs), count: %d", self._log_tag, duration, quick_disconnect_count
  302. )
  303. if quick_disconnect_count >= MAX_QUICK_DISCONNECT_COUNT:
  304. logger.error(
  305. "[%s] Too many quick disconnects. "
  306. "Check: 1) AppID/Secret correct 2) Bot permissions on QQ Open Platform",
  307. self._log_tag)
  308. self._set_fatal_error(
  309. "qq_quick_disconnect", "Too many quick disconnects — check bot permissions", retryable=True
  310. )
  311. return
  312. else:
  313. quick_disconnect_count = 0
  314. self._mark_transport_disconnected()
  315. self._fail_pending("Connection closed")
  316. desc = self._FATAL_CLOSE_CODES.get(code)
  317. if desc:
  318. logger.error("[%s] Bot is %s. Check QQ Open Platform.", self._log_tag, desc)
  319. self._set_fatal_error(f"qq_{desc}", f"Bot is {desc}", retryable=False)
  320. return
  321. if code == 4008:
  322. logger.info("[%s] Rate limited (4008), waiting %ds", self._log_tag, RATE_LIMIT_DELAY)
  323. if backoff_idx >= MAX_RECONNECT_ATTEMPTS:
  324. self._mark_disconnected()
  325. return
  326. await asyncio.sleep(RATE_LIMIT_DELAY)
  327. await reconnect()
  328. continue
  329. if code == 4004:
  330. logger.info("[%s] Invalid token (4004), will refresh and reconnect", self._log_tag)
  331. self._access_token = None
  332. self._token_expires_at = 0.0
  333. if code in self._SESSION_INVALID_CLOSE_CODES:
  334. logger.info("[%s] Session error (%d), clearing session for re-identify", self._log_tag, code)
  335. self._session_id = None
  336. self._last_seq = None
  337. await reconnect()
  338. if backoff_idx >= MAX_RECONNECT_ATTEMPTS:
  339. logger.error("[%s] Max reconnect attempts reached (QQCloseError)", self._log_tag)
  340. self._mark_disconnected()
  341. return
  342. except Exception as exc:
  343. if not self._running:
  344. return
  345. logger.warning("[%s] WebSocket error: %s", self._log_tag, exc)
  346. self._mark_transport_disconnected()
  347. self._fail_pending("Connection interrupted")
  348. if backoff_idx >= MAX_RECONNECT_ATTEMPTS:
  349. logger.error("[%s] Max reconnect attempts reached", self._log_tag)
  350. self._mark_disconnected()
  351. return
  352. await reconnect()
  353. async def _reconnect(self, backoff_idx: int) -> bool:
  354. delay = RECONNECT_BACKOFF[min(backoff_idx, len(RECONNECT_BACKOFF) - 1)]
  355. logger.info("[%s] Reconnecting in %ds (attempt %d)...", self._log_tag, delay, backoff_idx + 1)
  356. await asyncio.sleep(delay)
  357. self._heartbeat_interval = 30.0 # reset until Hello
  358. try:
  359. await self._open_gateway_ws()
  360. self._mark_connected()
  361. logger.info("[%s] Reconnected", self._log_tag)
  362. return True
  363. except Exception as exc:
  364. logger.warning("[%s] Reconnect failed: %s", self._log_tag, exc)
  365. return False
  366. async def _read_events(self) -> None:
  367. if not self._ws:
  368. raise RuntimeError("WebSocket not connected")
  369. if self._ws.closed:
  370. # Returning normally here would make _listen_loop treat it as a clean
  371. # read and retry with backoff reset → 100% CPU spin. Raise instead.
  372. raise RuntimeError("WebSocket closed")
  373. while self._running and self._ws and not self._ws.closed:
  374. msg = await self._ws.receive()
  375. if msg.type == aiohttp.WSMsgType.TEXT:
  376. payload = self._parse_json(msg.data)
  377. if payload:
  378. self._dispatch_payload(payload)
  379. elif msg.type == aiohttp.WSMsgType.CLOSE:
  380. raise QQCloseError(msg.data, msg.extra)
  381. elif msg.type in {aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR}:
  382. raise RuntimeError("WebSocket closed")
  383. async def _heartbeat_loop(self) -> None:
  384. """Send op 1 heartbeats with the latest seq at 80% of the Hello interval."""
  385. with contextlib.suppress(asyncio.CancelledError):
  386. while self._running:
  387. await asyncio.sleep(self._heartbeat_interval)
  388. if not self._ws or self._ws.closed:
  389. continue
  390. try:
  391. await self._ws.send_json({"op": 1, "d": self._last_seq})
  392. except Exception as exc:
  393. logger.debug("[%s] Heartbeat failed: %s", self._log_tag, exc)
  394. async def _send_ws_auth(self, name: str, payload: dict[str, Any], sent_msg: str, *log_args) -> bool:
  395. """Send an Identify/Resume payload; returns False if the send raised."""
  396. try:
  397. if self._ws and not self._ws.closed:
  398. await self._ws.send_json(payload)
  399. logger.info("[%s] " + sent_msg, self._log_tag, *log_args)
  400. else:
  401. logger.warning("[%s] Cannot send %s: WebSocket not connected", self._log_tag, name)
  402. except Exception as exc:
  403. logger.error("[%s] Failed to send %s: %s", self._log_tag, name, exc)
  404. return False
  405. return True
  406. async def _send_identify(self) -> None:
  407. """Send op 2 Identify (reply to Hello); server answers with READY. Intents:
  408. C2C_GROUP_AT_MESSAGES | PUBLIC_GUILD_MESSAGES | DIRECT_MESSAGE | INTERACTION."""
  409. token = await self._ensure_token()
  410. payload = {"op": 2, "d": {
  411. "token": f"QQBot {token}",
  412. "intents": (1 << 25) | (1 << 30) | (1 << 12) | (1 << 26),
  413. "shard": [0, 1],
  414. "properties": {"$os": "macOS", "$browser": "hermes-agent", "$device": "hermes-agent"}}}
  415. await self._send_ws_auth("Identify", payload, "Identify sent")
  416. async def _send_resume(self) -> None:
  417. """Send op 6 Resume after a reconnect; on failure clear session → Identify next Hello."""
  418. token = await self._ensure_token()
  419. payload = {"op": 6, "d": {"token": f"QQBot {token}", "session_id": self._session_id, "seq": self._last_seq}}
  420. if not await self._send_ws_auth(
  421. "Resume", payload, "Resume sent (session_id=%s, seq=%s)", self._session_id, self._last_seq
  422. ):
  423. self._session_id = None
  424. self._last_seq = None
  425. @staticmethod
  426. def _create_task(coro):
  427. """Schedule a coroutine; returns None (no error) when no loop is running
  428. (tests call _dispatch_payload synchronously)."""
  429. try:
  430. return asyncio.get_running_loop().create_task(coro)
  431. except RuntimeError:
  432. return None
  433. def _close_ws_soon(self) -> None:
  434. """Close the WS so _read_events raises and _listen_loop reconnects (with Resume)."""
  435. if self._ws and not self._ws.closed:
  436. self._create_task(self._ws.close())
  437. def _dispatch_payload(self, payload: dict[str, Any]) -> None:
  438. """Route inbound WebSocket payloads (dispatch synchronously, spawn async handlers)."""
  439. op, t, s, d = payload.get("op"), payload.get("t"), payload.get("s"), payload.get("d")
  440. if isinstance(s, int) and (self._last_seq is None or s > self._last_seq):
  441. self._last_seq = s
  442. if op == 10: # Hello — reply with Resume (have session) or Identify
  443. interval_ms = (d if isinstance(d, dict) else {}).get("heartbeat_interval", 30000)
  444. self._heartbeat_interval = interval_ms / 1000.0 * 0.8 # 80% of server interval
  445. logger.debug(
  446. "[%s] Hello received, heartbeat_interval=%dms (sending every %.1fs)",
  447. self._log_tag, interval_ms, self._heartbeat_interval)
  448. resume = self._session_id and self._last_seq is not None
  449. self._create_task(self._send_resume() if resume else self._send_identify())
  450. elif op == 0 and t: # Dispatch
  451. if t == "READY":
  452. if isinstance(d, dict): # store session_id for resume
  453. self._session_id = d.get("session_id")
  454. logger.info("[%s] Ready, session_id=%s", self._log_tag, self._session_id)
  455. elif t == "RESUMED":
  456. logger.info("[%s] Session resumed", self._log_tag)
  457. elif t in self._INBOUND_HANDLERS:
  458. asyncio.create_task(self._on_message(t, d))
  459. elif t == "INTERACTION_CREATE":
  460. self._create_task(self._on_interaction(d))
  461. else:
  462. logger.debug("[%s] Unhandled dispatch: %s", self._log_tag, t)
  463. elif op == 11: # Heartbeat ACK
  464. pass
  465. elif op == 7: # Server Reconnect
  466. logger.info("[%s] Server requested reconnect (op 7)", self._log_tag)
  467. self._close_ws_soon()
  468. elif op == 9: # Invalid Session — d=True resumable, d=False re-identify from scratch
  469. if d is not None and bool(d):
  470. logger.info("[%s] Invalid session (op 9, resumable)", self._log_tag)
  471. else:
  472. logger.info("[%s] Invalid session (op 9, not resumable), clearing session", self._log_tag)
  473. self._session_id = None
  474. self._last_seq = None
  475. self._close_ws_soon()
  476. else:
  477. logger.debug("[%s] Unknown op: %s", self._log_tag, op)
  478. # ── JSON helpers ──
  479. @staticmethod
  480. def _parse_json(raw: Any) -> Optional[dict[str, Any]]:
  481. try:
  482. payload = json.loads(raw)
  483. except Exception:
  484. logger.warning("[QQBot] Failed to parse JSON: %r", raw)
  485. return None
  486. return payload if isinstance(payload, dict) else None
  487. @staticmethod
  488. def _next_msg_seq(msg_id: str) -> int:
  489. """Generate a message sequence number in 0..65535 range."""
  490. time_part = int(time.time()) % 100000000
  491. rand = int(uuid.uuid4().hex[:4], 16)
  492. return (time_part ^ rand) % 65536
  493. # ── Inbound message handling ──
  494. async def handle_message(self, event: MessageEvent) -> None:
  495. """Cache the last message ID per chat, then delegate to base."""
  496. if event.message_id and event.source.chat_id:
  497. self._last_msg_id[event.source.chat_id] = event.message_id
  498. await super().handle_message(event)
  499. async def _on_message(self, event_type: str, d: Any) -> None:
  500. if not isinstance(d, dict):
  501. return
  502. msg_id = str(d.get("id", ""))
  503. if not msg_id or self._dedup.is_duplicate(msg_id):
  504. logger.debug("[%s] Duplicate or missing message id: %s", self._log_tag, msg_id)
  505. return
  506. handler = self._INBOUND_HANDLERS.get(event_type)
  507. if handler:
  508. author = d.get("author") if isinstance(d.get("author"), dict) else {}
  509. await getattr(self, handler)(
  510. d, msg_id, str(d.get("content", "")).strip(), author, str(d.get("timestamp", "")))
  511. # ── Inline-keyboard interactions (INTERACTION_CREATE) ──
  512. def set_interaction_callback(self, callback: Optional[Callable[[InteractionEvent], Awaitable[None]]]) -> None:
  513. """Register (or clear) the callback invoked per ACKed INTERACTION_CREATE."""
  514. self._interaction_callback = callback
  515. async def _on_interaction(self, d: Any) -> None:
  516. """Parse INTERACTION_CREATE, ACK it promptly (else the client shows an error
  517. icon on the button), then dispatch to the registered callback."""
  518. if not isinstance(d, dict):
  519. return
  520. try:
  521. event = parse_interaction_event(d)
  522. except Exception as exc:
  523. logger.warning("[%s] Failed to parse INTERACTION_CREATE: %s", self._log_tag, exc)
  524. return
  525. if not event.id:
  526. logger.warning("[%s] INTERACTION_CREATE missing id, skipping ACK", self._log_tag)
  527. return
  528. try:
  529. await self._acknowledge_interaction(event.id)
  530. except Exception as exc:
  531. logger.warning("[%s] Failed to ACK interaction %s: %s", self._log_tag, event.id, exc)
  532. logger.info(
  533. "[%s] Interaction: scene=%s button_data=%r operator=%s",
  534. self._log_tag, event.scene, event.button_data, event.operator_openid)
  535. callback = self._interaction_callback
  536. if callback is None:
  537. logger.debug(
  538. "[%s] No interaction callback registered; dropping button click %r", self._log_tag, event.button_data
  539. )
  540. return
  541. try:
  542. await callback(event)
  543. except Exception as exc:
  544. logger.error("[%s] Interaction callback raised: %s", self._log_tag, exc, exc_info=True)
  545. async def _acknowledge_interaction(self, interaction_id: str, code: int = 0) -> None:
  546. """ACK a button interaction via ``PUT /interactions/{id}`` (code 0 = success)."""
  547. resp = await self._require_http_client().put(
  548. f"{API_BASE}/interactions/{interaction_id}",
  549. headers=await self._auth_headers(), json={"code": code}, timeout=DEFAULT_API_TIMEOUT)
  550. if resp.status_code >= 400:
  551. raise RuntimeError(f"Interaction ACK failed [{resp.status_code}]: {resp.text[:200]}")
  552. # Button decision → ``choice`` for tools.approval.resolve_gateway_approval. The
  553. # 3-button layout folds "session" into "always"; ``/approve session`` still works.
  554. _APPROVAL_BUTTON_TO_CHOICE = {"allow-once": "once", "allow-always": "always", "deny": "deny"}
  555. @staticmethod
  556. def _parse_gateway_session_key(session_key: str) -> Optional[dict[str, str]]:
  557. """Parse ``agent:<namespace>:<platform>:<chat_type>:<chat_id>[:<user_id>]``.
  558. The namespace slot carries the multiplex profile ("main" for the
  559. default profile — see ``gateway.session._session_key_namespace``);
  560. it takes no part in any authorization decision, so any non-empty
  561. value is accepted and every later slot keeps its position.
  562. """
  563. parts = str(session_key or "").split(":")
  564. if len(parts) < 5 or parts[0] != "agent" or not parts[1]:
  565. return None
  566. parsed = {"platform": parts[2], "chat_type": parts[3], "chat_id": parts[4]}
  567. if len(parts) > 5:
  568. parsed["user_id"] = parts[5]
  569. return parsed
  570. def _is_authorized_interaction_for_session(self, event: InteractionEvent, session_key: str) -> bool:
  571. """Authorize approval/update interactions against session + operator."""
  572. parsed = self._parse_gateway_session_key(session_key)
  573. operator = str(event.operator_openid or "").strip()
  574. if not parsed or parsed.get("platform") != "qqbot" or not operator:
  575. return False
  576. chat_type = parsed.get("chat_type", "")
  577. chat_id = parsed.get("chat_id", "")
  578. # Approval keys come from build_source (chat_type="dm"); update-prompt keys from event.scene ("c2c").
  579. if chat_type in {"c2c", "dm"}:
  580. return bool(chat_id) and operator == chat_id
  581. if chat_type in {"group", "guild"}:
  582. event_chat = str(event.group_openid or event.guild_id or "").strip()
  583. if not event_chat or event_chat != chat_id:
  584. return False
  585. session_user = str(parsed.get("user_id", "")).strip()
  586. return bool(session_user) and operator == session_user
  587. return False
  588. def _update_prompt_session_key(self, event: InteractionEvent, chat: str) -> str:
  589. """Session key an update-prompt click is authorized against, built by the ONE key builder so
  590. it carries the profile namespace (a hard-coded ``agent:main:`` prefix never matched a
  591. multiplexed secondary bot's lane). No participant: ``c2c`` authorizes on chat == operator."""
  592. return self._source_session_key(self.build_source(chat_id=chat, chat_type=event.scene))
  593. async def _default_interaction_dispatch(self, event: InteractionEvent) -> None:
  594. """Default interaction callback: ``approve:<session_key>:<decision>`` →
  595. tools.approval.resolve_gateway_approval; ``update_prompt:<answer>`` →
  596. ``~/.hermes/.update_response``; anything else is ignored at DEBUG."""
  597. button_data = event.button_data
  598. if not button_data:
  599. return
  600. approval = parse_approval_button_data(button_data)
  601. if approval is not None:
  602. session_key, decision = approval
  603. choice = self._APPROVAL_BUTTON_TO_CHOICE.get(decision)
  604. if choice is None:
  605. logger.warning("[%s] Unknown approval decision %r (session=%s)", self._log_tag, decision, session_key)
  606. return
  607. if not self._is_authorized_interaction_for_session(event, session_key):
  608. logger.warning(
  609. "[%s] Rejected unauthorized approval click for session %s (operator=%s)",
  610. self._log_tag, session_key, event.operator_openid)
  611. return
  612. try:
  613. from tools.approval import resolve_gateway_approval # lazy: keep adapter light
  614. count = resolve_gateway_approval(session_key, choice)
  615. logger.info(
  616. "[%s] Button resolved %d approval(s) for session %s (choice=%s, operator=%s)",
  617. self._log_tag, count, session_key, choice, event.operator_openid)
  618. except Exception as exc:
  619. logger.error("[%s] resolve_gateway_approval failed for session %s: %s", self._log_tag, session_key, exc)
  620. return
  621. update_answer = parse_update_prompt_button_data(button_data)
  622. if update_answer is not None:
  623. chat = event.group_openid or event.guild_id or event.user_openid
  624. if not self._is_authorized_interaction_for_session(event, self._update_prompt_session_key(event, chat)):
  625. logger.warning(
  626. "[%s] Rejected unauthorized update prompt click (operator=%s)", self._log_tag, event.operator_openid
  627. )
  628. return
  629. self._write_update_response(update_answer, event.operator_openid)
  630. return
  631. logger.debug("[%s] Unrecognised button_data %r from interaction %s", self._log_tag, button_data, event.id)
  632. @staticmethod
  633. def _write_update_response(answer: str, operator: str = "") -> None:
  634. """Atomically (tmp + rename) write the update-prompt answer to
  635. ``.update_response``, polled by the detached ``hermes update --gateway`` watcher."""
  636. try:
  637. from hermes_constants import get_hermes_home
  638. response_path = get_hermes_home() / ".update_response"
  639. tmp = response_path.with_suffix(".tmp")
  640. tmp.write_text(answer, encoding="utf-8")
  641. tmp.replace(response_path)
  642. logger.info("QQ update prompt answered %r by %s", answer, operator or "(unknown)")
  643. except Exception as exc:
  644. logger.error("Failed to write update response: %s", exc)
  645. async def _handle_c2c_message(self, d, msg_id, content, author, timestamp) -> None:
  646. user_openid = str(author.get("user_openid", ""))
  647. if not user_openid or not self._is_dm_intake_allowed(user_openid):
  648. return
  649. attachments_raw = d.get("attachments")
  650. logger.info(
  651. "[%s] C2C message: id=%s content=%r attachments=%s",
  652. self._log_tag, msg_id, content[:50] if content else "",
  653. f"{len(attachments_raw) if isinstance(attachments_raw, list) else 0} items" if attachments_raw else "None",
  654. )
  655. if attachments_raw and isinstance(attachments_raw, list):
  656. for _i, _att in enumerate(attachments_raw):
  657. if isinstance(_att, dict):
  658. logger.info(
  659. "[%s] attachment[%d]: content_type=%s url=%s filename=%s",
  660. self._log_tag, _i, _att.get("content_type", ""),
  661. str(_att.get("url", ""))[:80], _att.get("filename", ""))
  662. await self._ingest(
  663. d, msg_id, content, attachments_raw, timestamp, verbose=True,
  664. chat_id=user_openid, qq_chat_type="c2c", user_id=user_openid, chat_type="dm")
  665. async def _handle_group_message(self, d, msg_id, content, author, timestamp) -> None:
  666. group_openid = str(d.get("group_openid", ""))
  667. member = str(author.get("member_openid", ""))
  668. if not group_openid or not self._is_group_allowed(group_openid, member):
  669. return
  670. await self._ingest(
  671. d, msg_id, self._strip_at_mention(content), d.get("attachments"), timestamp,
  672. chat_id=group_openid, qq_chat_type="group", user_id=member, chat_type="group")
  673. async def _handle_guild_message(self, d, msg_id, content, author, timestamp) -> None:
  674. channel_id = str(d.get("channel_id", ""))
  675. if not channel_id:
  676. return
  677. # group_policy ACL — guild channels are group-like; without it any guild
  678. # member could bypass the allowlist.
  679. guild_id = str(d.get("guild_id", ""))
  680. author_id = str(author.get("id", ""))
  681. if not self._is_group_allowed(guild_id or channel_id, author_id):
  682. logger.debug("[%s] Guild message blocked by ACL: channel=%s user=%s", self._log_tag, channel_id, author_id)
  683. return
  684. member = d.get("member") if isinstance(d.get("member"), dict) else {}
  685. nick = str(member.get("nick", "")) or str(author.get("username", ""))
  686. await self._ingest(
  687. d, msg_id, content, d.get("attachments"), timestamp,
  688. chat_id=channel_id, qq_chat_type="guild", user_id=author_id, user_name=nick or None, chat_type="group",
  689. is_bot=bool(author.get("bot")))
  690. async def _handle_dm_message(self, d, msg_id, content, author, timestamp) -> None:
  691. guild_id = str(d.get("guild_id", ""))
  692. if not guild_id:
  693. return
  694. # dm_policy ACL — without it any guild member could bypass the allowlist via DM.
  695. author_id = str(author.get("id", ""))
  696. if not self._is_dm_intake_allowed(author_id):
  697. logger.debug("[%s] Guild DM blocked by ACL: guild=%s user=%s", self._log_tag, guild_id, author_id)
  698. return
  699. await self._ingest(
  700. d, msg_id, content, d.get("attachments"), timestamp,
  701. chat_id=guild_id, qq_chat_type="dm", user_id=author_id, chat_type="dm",
  702. is_bot=bool(author.get("bot")))
  703. _INBOUND_HANDLERS = {
  704. "C2C_MESSAGE_CREATE": "_handle_c2c_message",
  705. "GROUP_AT_MESSAGE_CREATE": "_handle_group_message",
  706. "GUILD_MESSAGE_CREATE": "_handle_guild_message",
  707. "GUILD_AT_MESSAGE_CREATE": "_handle_guild_message",
  708. "DIRECT_MESSAGE_CREATE": "_handle_dm_message"}
  709. # ── Shared inbound pipeline (all four message kinds) ──
  710. @staticmethod
  711. def _append_block(text: str, block: str) -> str:
  712. """Append *block* to *text* after a blank line (or return block alone if text is blank)."""
  713. return (text + "\n\n" + block).strip() if text.strip() else block
  714. async def _ingest(
  715. self, d: dict[str, Any], msg_id: str, content: str, attachments: Any, timestamp: str, *,
  716. chat_id: str, qq_chat_type: str, verbose: bool = False, **source_kwargs: Any) -> None:
  717. """Shared inbound tail: fold attachment transcripts/file info and quoted context
  718. into the text, drop empty events, remember the QQ chat kind and dispatch."""
  719. att = await self._process_attachments(attachments)
  720. text = content
  721. voice_transcripts = att["voice_transcripts"]
  722. if voice_transcripts:
  723. text = self._append_block(text, "\n".join(voice_transcripts))
  724. if att["attachment_info"]:
  725. text = self._append_block(text, att["attachment_info"])
  726. image_urls, image_media_types = att["image_urls"], att["image_media_types"]
  727. if verbose:
  728. logger.info("[%s] After processing: images=%d, voice=%d", self._log_tag, len(image_urls), len(voice_transcripts))
  729. quoted = await self._process_quoted_context(d)
  730. text = self._merge_quote_into(text, quoted["quote_block"])
  731. if quoted["image_urls"]:
  732. image_urls = image_urls + quoted["image_urls"]
  733. image_media_types = image_media_types + quoted["image_media_types"]
  734. if not text.strip() and not image_urls:
  735. return
  736. self._chat_type_map[chat_id] = qq_chat_type
  737. event = MessageEvent(
  738. source=self.build_source(chat_id=chat_id,** source_kwargs), text=text,
  739. message_type=self._detect_message_type(image_urls, image_media_types), raw_message=d,
  740. message_id=msg_id, media_urls=image_urls, media_types=image_media_types,
  741. timestamp=self._parse_qq_timestamp(timestamp),
  742. )
  743. await self.handle_message(event)
  744. # ── Quoted-message handling ──
  745. async def _process_quoted_context(self, d: dict[str, Any]) -> dict[str, Any]:
  746. """Process the quoted message a user is replying to (``message_type == 103``;
  747. referenced content + attachments live in ``msg_elements``). Quoted attachments
  748. go through _process_attachments so quoted voice gets STT and quoted images are
  749. cached identically. Returns ``{"quote_block", "image_urls", "image_media_types"}``;
  750. quote_block is "" when nothing is quoted."""
  751. empty = {"quote_block": "", "image_urls": [], "image_media_types": []}
  752. try:
  753. is_quote = int(d.get("message_type", 0) or 0) == 103
  754. except (TypeError, ValueError):
  755. is_quote = False
  756. elements = d.get("msg_elements")
  757. if not is_quote or not isinstance(elements, list) or not elements:
  758. return empty
  759. elements = [e for e in elements if isinstance(e, dict)]
  760. quoted_text_parts = [t for t in (str(e.get("content", "")).strip() for e in elements) if t]
  761. all_attachments = [
  762. a for e in elements if isinstance(e.get("attachments"), list) for a in e["attachments"] if isinstance(a, dict)]
  763. att_result = await self._process_attachments(all_attachments)
  764. quoted_images = att_result.get("image_urls") or []
  765. lines: list[str] = [" ".join(quoted_text_parts)] if quoted_text_parts else []
  766. lines.extend(att_result.get("voice_transcripts") or [])
  767. if att_result.get("attachment_info"):
  768. lines.append(att_result["attachment_info"])
  769. if not lines and not quoted_images:
  770. return empty
  771. # Images-only quote still gets a marker so the LLM knows context was referenced.
  772. return {
  773. "quote_block": "[Quoted message]:\n" + "\n".join(lines) if lines else "[Quoted message]: (image)",
  774. "image_urls": quoted_images,
  775. "image_media_types": att_result.get("image_media_types") or []}
  776. @staticmethod
  777. def _merge_quote_into(text: str, quote_block: str) -> str:
  778. """Prepend ``quote_block`` to *text*, separated by a blank line."""
  779. if not quote_block:
  780. return text
  781. return f"{quote_block}\n\n{text}".strip() if text.strip() else quote_block
  782. # ── Attachment processing ──
  783. @staticmethod
  784. def _detect_message_type(media_urls: list, media_types: list):
  785. if not media_urls:
  786. return MessageType.TEXT
  787. if not media_types:
  788. return MessageType.PHOTO
  789. first_type = media_types[0].lower()
  790. if "audio" in first_type or "voice" in first_type or "silk" in first_type:
  791. return MessageType.VOICE
  792. if "video" in first_type:
  793. return MessageType.VIDEO
  794. if "image" in first_type or "photo" in first_type:
  795. return MessageType.PHOTO
  796. logger.debug("Unknown media content_type '%s', defaulting to TEXT", first_type)
  797. return MessageType.TEXT
  798. async def _process_attachments(self, attachments: Any) -> dict[str, Any]:
  799. """Process inbound attachments uniformly. Returns ``{"image_urls",
  800. "image_media_types", "voice_transcripts", "attachment_info"}`` (cached image
  801. paths + MIME types, "[Voice] ..." transcripts, text description of other files)."""
  802. image_urls: list[str] = []
  803. image_media_types: list[str] = []
  804. voice_transcripts: list[str] = []
  805. other_attachments: list[str] = []
  806. for att in attachments if isinstance(attachments, list) else ():
  807. if not isinstance(att, dict):
  808. continue
  809. ct = str(att.get("content_type", "")).strip().lower()
  810. url = str(att.get("url", "")).strip()
  811. filename = str(att.get("filename", ""))
  812. if not url:
  813. continue
  814. if url.startswith("//"):
  815. url = f"https:{url}"
  816. logger.debug(
  817. "[%s] Processing attachment: content_type=%s, url=%s, filename=%s",
  818. self._log_tag, ct, url[:80], filename)
  819. if self._is_voice_content_type(ct, filename):
  820. asr_refer, wav_url = (self._opt_str(att.get(k)) for k in ("asr_refer_text", "voice_wav_url"))
  821. transcript = await self._stt_voice_attachment(
  822. url, ct, filename, asr_refer_text=asr_refer, voice_wav_url=wav_url)
  823. if transcript:
  824. voice_transcripts.append(f"[Voice] {transcript}")
  825. logger.debug("[%s] Voice transcript: %s", self._log_tag, transcript)
  826. else:
  827. logger.warning("[%s] Voice STT failed for %s", self._log_tag, url[:60])
  828. voice_transcripts.append("[Voice] [语音识别失败]")
  829. continue
  830. is_image = ct.startswith("image/")
  831. try:
  832. cached_path = await self._download_and_cache(url, ct, filename)
  833. except Exception as exc:
  834. logger.debug("[%s] Failed to cache %s: %s", self._log_tag, "image" if is_image else "attachment", exc)
  835. continue
  836. if not cached_path:
  837. continue
  838. if not is_image:
  839. label = "video" if ct.startswith("video/") else "file"
  840. other_attachments.append(f"[{label}: {filename or ct} ({cached_path})]")
  841. elif os.path.isfile(cached_path):
  842. image_urls.append(cached_path)
  843. image_media_types.append(ct or "image/jpeg")
  844. else:
  845. logger.warning("[%s] Cached image path does not exist: %s", self._log_tag, cached_path)
  846. return {
  847. "image_urls": image_urls,
  848. "image_media_types": image_media_types,
  849. "voice_transcripts": voice_transcripts,
  850. "attachment_info": "\n".join(other_attachments)}
  851. @staticmethod
  852. def _opt_str(value: Any) -> Optional[str]:
  853. return (value.strip() if isinstance(value, str) else "") or None
  854. async def _download_and_cache(self, url: str, content_type: str, original_name: str = "") -> Optional[str]:
  855. """Download a URL and cache it locally (``original_name`` falls back to the URL basename)."""
  856. from tools.url_safety import is_safe_url
  857. if not is_safe_url(url):
  858. raise ValueError(f"Blocked unsafe URL: {url[:80]}")
  859. if not self._http_client:
  860. return None
  861. try:
  862. resp = await self._http_client.get(url, timeout=30.0, headers=self._qq_media_headers())
  863. resp.raise_for_status()
  864. data = resp.content
  865. except Exception as exc:
  866. logger.debug("[%s] Download failed for %s: %s", self._log_tag, url[:80], exc)
  867. return None
  868. if content_type.startswith("image/"):
  869. # Historical qqbot mapping: trust mimetypes' guess (never the shared table), fall back to .jpg.
  870. ext = ext_for_mime(content_type, use_defaults=False, use_mimetypes=True, fallback=".jpg") or ".jpg"
  871. return await cache_image_from_bytes_async(data, ext)
  872. if content_type == "voice" or content_type.startswith("audio/"):
  873. # QQ voice is usually .amr/.silk — convert to .wav for STT engines.
  874. return await self._convert_audio_to_wav(data, url)
  875. filename = original_name or Path(urlparse(url).path).name or "qq_attachment"
  876. return await cache_document_from_bytes_async(data, filename)
  877. @staticmethod
  878. def _is_voice_content_type(content_type: str, filename: str) -> bool:
  879. ct = content_type.strip().lower()
  880. if ct == "voice" or ct.startswith("audio/"):
  881. return True
  882. # content_type="file" is an explicit upload: never route .wav/.mp3 files into STT.
  883. if ct == "file":
  884. return False
  885. return filename.strip().lower().endswith(_VOICE_EXTENSIONS)
  886. def _qq_media_headers(self) -> dict[str, str]:
  887. """Authorization header for QQ multimedia CDN downloads (required, else non-200)."""
  888. return {"Authorization": f"QQBot {self._access_token}"} if self._access_token else {}
  889. async def _stt_voice_attachment(
  890. self, url: str, content_type: str, filename: str, *, asr_refer_text: Optional[str] = None,
  891. voice_wav_url: Optional[str] = None) -> Optional[str]:
  892. """Transcribe a voice attachment. Priority: QQ's free ``asr_refer_text`` →
  893. STT on ``voice_wav_url`` (pre-converted WAV, no SILK decode) → STT on the
  894. original URL (SILK→WAV). Returns the transcript or None."""
  895. if asr_refer_text:
  896. logger.debug("[%s] STT: using QQ asr_refer_text: %r", self._log_tag, asr_refer_text[:100])
  897. return asr_refer_text
  898. is_pre_wav = bool(voice_wav_url)
  899. download_url = url
  900. if is_pre_wav:
  901. download_url = f"https:{voice_wav_url}" if voice_wav_url.startswith("//") else voice_wav_url
  902. logger.debug("[%s] STT: using voice_wav_url (pre-converted WAV)", self._log_tag)
  903. from tools.url_safety import is_safe_url
  904. if not is_safe_url(download_url):
  905. logger.warning("[QQ] STT blocked unsafe URL: %s", download_url[:80])
  906. return None
  907. try:
  908. if not self._http_client:
  909. logger.warning("[%s] STT: no HTTP client", self._log_tag)
  910. return None
  911. download_headers = self._qq_media_headers() # QQ CDN requires Authorization
  912. logger.debug(
  913. "[%s] STT: downloading voice from %s (pre_wav=%s, headers=%s)",
  914. self._log_tag, download_url[:80], is_pre_wav, bool(download_headers))
  915. resp = await self._http_client.get(
  916. download_url, timeout=30.0, headers=download_headers, follow_redirects=True)
  917. resp.raise_for_status()
  918. audio_data = resp.content
  919. logger.debug(
  920. "[%s] STT: downloaded %d bytes, content_type=%s",
  921. self._log_tag, len(audio_data), resp.headers.get("content-type", "unknown"))
  922. if len(audio_data) < 10:
  923. logger.warning("[%s] STT: downloaded data too small (%d bytes), skipping", self._log_tag, len(audio_data))
  924. return None
  925. if is_pre_wav:
  926. wav_path = self._write_temp(audio_data, ".wav")
  927. logger.debug("[%s] STT: using pre-converted WAV directly (%d bytes)", self._log_tag, len(audio_data))
  928. else:
  929. logger.debug("[%s] STT: converting to wav, filename=%r", self._log_tag, filename)
  930. wav_path = await self._convert_audio_to_wav_file(audio_data, filename)
  931. if not wav_path or not Path(wav_path).exists():
  932. logger.warning("[%s] STT: ffmpeg conversion produced no output", self._log_tag)
  933. return None
  934. logger.debug("[%s] STT: calling ASR on %s", self._log_tag, wav_path)
  935. try:
  936. transcript = await self._call_stt(wav_path)
  937. finally:
  938. self._unlink_quiet(wav_path)
  939. if transcript:
  940. logger.debug("[%s] STT success: %r", self._log_tag, transcript[:100])
  941. else:
  942. logger.warning("[%s] STT: ASR returned empty transcript", self._log_tag)
  943. return transcript
  944. except (OSError, httpx.HTTPStatusError, httpx.TransportError) as exc:
  945. logger.warning("[%s] STT failed for voice attachment: %s: %s", self._log_tag, type(exc).__name__, exc)
  946. return None
  947. @staticmethod
  948. def _write_temp(data: bytes, suffix: str) -> str:
  949. """Write *data* to a persistent NamedTemporaryFile and return its path."""
  950. import tempfile
  951. with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
  952. tmp.write(data)
  953. return tmp.name
  954. @staticmethod
  955. def _unlink_quiet(path: str) -> None:
  956. with contextlib.suppress(OSError):
  957. os.unlink(path)
  958. @staticmethod
  959. def _wav_ok(wav_path: str) -> bool:
  960. """True when *wav_path* exists and holds more than a bare 44-byte header."""
  961. return Path(wav_path).exists() and Path(wav_path).stat().st_size > 44
  962. @classmethod
  963. def _temp_pair(cls, audio_data: bytes, ext: str) -> tuple[str, str]:
  964. """Write *audio_data* to a temp ``<x>{ext}`` and return ``(src_path, sibling .wav path)``."""
  965. src_path = cls._write_temp(audio_data, ext)
  966. return src_path, src_path.rsplit(".", 1)[0] + ".wav"
  967. async def _convert_audio_to_wav_file(self, audio_data: bytes, filename: str) -> Optional[str]:
  968. """Convert audio bytes to a temp .wav: pilk (SILK, which ffmpeg can't decode)
  969. → ffmpeg → raw-PCM last resort. Returns the wav path or None."""
  970. ext = Path(filename).suffix.lower() or self._guess_ext_from_data(audio_data)
  971. logger.info(
  972. "[%s] STT: audio_data size=%d, ext=%r, first_20_bytes=%r",
  973. self._log_tag, len(audio_data), ext, audio_data[:20])
  974. src_path, wav_path = self._temp_pair(audio_data, ext)
  975. result = (
  976. await self._convert_silk_to_wav(src_path, wav_path)
  977. or await self._convert_ffmpeg_to_wav(src_path, wav_path)
  978. or await self._convert_raw_to_wav(audio_data, wav_path))
  979. self._unlink_quiet(src_path)
  980. return result
  981. _MAGIC_EXTS = (
  982. (b"#!SILK", ".silk"), (b"\x02!", ".silk"), (b"RIFF", ".wav"), (b"fLaC", ".flac"),
  983. (b"\xff\xfb", ".mp3"), (b"\xff\xf3", ".mp3"), (b"\xff\xf2", ".mp3"),
  984. (b"\x30\x26\xb2\x75", ".ogg"), (b"\x4f\x67\x67\x53", ".ogg"))
  985. @classmethod
  986. def _guess_ext_from_data(cls, data: bytes) -> str:
  987. """Guess file extension from magic bytes (unknown → .amr, QQ's most common)."""
  988. return next((ext for magic, ext in cls._MAGIC_EXTS if data.startswith(magic)), ".amr")
  989. @classmethod
  990. def _looks_like_silk(cls, data: bytes) -> bool:
  991. return cls._guess_ext_from_data(data) == ".silk"
  992. async def _convert_silk_to_wav(self, src_path: str, wav_path: str) -> Optional[str]:
  993. """Convert to WAV with pilk: as-is first, then copied to .silk (pilk checks the extension)."""
  994. try:
  995. import pilk
  996. except ImportError:
  997. logger.warning("[%s] pilk not installed — cannot decode SILK audio. Run: "
  998. f"{install_hint('silk')}", self._log_tag)
  999. return None
  1000. silk_path = src_path.rsplit(".", 1)[0] + ".silk"
  1001. try:
  1002. for path, label, how in ((src_path, "", "direct"), (silk_path, " (as .silk)", ".silk")):
  1003. try:
  1004. if path == silk_path:
  1005. import shutil
  1006. shutil.copy2(src_path, silk_path)
  1007. pilk.silk_to_wav(path, wav_path, rate=16000)
  1008. if self._wav_ok(wav_path):
  1009. logger.debug(
  1010. "[%s] pilk converted %s%s to wav (%d bytes)",
  1011. self._log_tag, Path(src_path).name, label, Path(wav_path).stat().st_size)
  1012. return wav_path
  1013. except Exception as exc:
  1014. logger.debug("[%s] pilk %s conversion failed: %s", self._log_tag, how, exc)
  1015. finally:
  1016. self._unlink_quiet(silk_path)
  1017. return None
  1018. async def _convert_raw_to_wav(self, audio_data: bytes, wav_path: str) -> Optional[str]:
  1019. """Last resort: wrap bytes as raw PCM 16-bit mono 16kHz WAV (garbage if not
  1020. PCM, but the ASR engine returns empty instead of crashing)."""
  1021. try:
  1022. import wave
  1023. with wave.open(wav_path, "w") as wf:
  1024. wf.setnchannels(1)
  1025. wf.setsampwidth(2)
  1026. wf.setframerate(16000)
  1027. wf.writeframes(audio_data)
  1028. return wav_path
  1029. except Exception as exc:
  1030. logger.debug("[%s] raw PCM fallback failed: %s", self._log_tag, exc)
  1031. return None
  1032. async def _convert_ffmpeg_to_wav(self, src_path: str, wav_path: str) -> Optional[str]:
  1033. try:
  1034. proc = await asyncio.create_subprocess_exec(
  1035. "ffmpeg", "-y", "-i", src_path, "-ar", "16000", "-ac", "1", wav_path,
  1036. stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE)
  1037. await asyncio.wait_for(proc.wait(), timeout=30)
  1038. if proc.returncode != 0:
  1039. stderr = await proc.stderr.read() if proc.stderr else b""
  1040. logger.warning(
  1041. "[%s] ffmpeg failed for %s: %s",
  1042. self._log_tag, Path(src_path).name, stderr[:200].decode(errors="replace"))
  1043. return None
  1044. except (TimeoutError, FileNotFoundError) as exc:
  1045. logger.warning("[%s] ffmpeg conversion error: %s", self._log_tag, exc)
  1046. return None
  1047. if not self._wav_ok(wav_path):
  1048. logger.warning("[%s] ffmpeg produced no/small output for %s", self._log_tag, Path(src_path).name)
  1049. return None
  1050. logger.debug(
  1051. "[%s] ffmpeg converted %s to wav (%d bytes)",
  1052. self._log_tag, Path(src_path).name, Path(wav_path).stat().st_size)
  1053. return wav_path
  1054. def _resolve_stt_config(self) -> Optional[dict[str, Any]]:
  1055. """Resolve STT backend: ``extra["stt"]`` config first, then ``QQ_STT_*`` env
  1056. vars; None when unconfigured (QQ's built-in ASR still works). ``timeout`` (seconds,
  1057. default 60) follows the shared STT client default so a self-hosted model's cold start
  1058. is not cut off at 30s (#112939)."""
  1059. from tools.transcription_common import DEFAULT_STT_TIMEOUT, _config_number # lazy: keep adapter light
  1060. stt_cfg = (self.config.extra or {}).get("stt")
  1061. if isinstance(stt_cfg, dict) and stt_cfg.get("enabled") is not False:
  1062. base_url = stt_cfg.get("baseUrl") or stt_cfg.get("base_url", "")
  1063. api_key = stt_cfg.get("apiKey") or stt_cfg.get("api_key", "")
  1064. model = stt_cfg.get("model", "")
  1065. timeout = _config_number(stt_cfg, "timeout", DEFAULT_STT_TIMEOUT)
  1066. if base_url and api_key:
  1067. return {"base_url": base_url.rstrip("/"), "api_key": api_key, "model": model or "whisper-1",
  1068. "timeout": timeout}
  1069. if api_key: # provider-only config
  1070. provider = stt_cfg.get("provider", "zai")
  1071. base_url = _STT_PROVIDER_BASE_URLS.get(provider, "")
  1072. if base_url:
  1073. default_model = "glm-asr" if provider in {"zai", "glm"} else "whisper-1"
  1074. return {"base_url": base_url, "api_key": api_key, "model": model or default_model,
  1075. "timeout": timeout}
  1076. qq_stt_key = _resolve_qq_secret("QQ_STT_API_KEY", "")
  1077. if qq_stt_key:
  1078. base_url = _resolve_qq_secret("QQ_STT_BASE_URL", _STT_PROVIDER_BASE_URLS["zai"])
  1079. model = _resolve_qq_secret("QQ_STT_MODEL", "glm-asr")
  1080. return {"base_url": base_url.rstrip("/"), "api_key": qq_stt_key, "model": model,
  1081. "timeout": DEFAULT_STT_TIMEOUT}
  1082. return None
  1083. async def _call_stt(self, wav_path: str) -> Optional[str]:
  1084. """Transcribe a wav via an OpenAI-compatible STT API; None if unconfigured/failed."""
  1085. stt_cfg = self._resolve_stt_config()
  1086. if not stt_cfg:
  1087. logger.warning("[%s] STT not configured (no stt config or QQ_STT_API_KEY)", self._log_tag)
  1088. return None
  1089. base_url, api_key, model = stt_cfg["base_url"], stt_cfg["api_key"], stt_cfg["model"]
  1090. try:
  1091. with open(wav_path, "rb") as f: # noqa: ASYNC230 -- file handle is streamed to the upload; a local open() is non-blocking in practice
  1092. resp = await self._http_client.post(
  1093. f"{base_url}/audio/transcriptions",
  1094. headers={"Authorization": f"Bearer {api_key}"},
  1095. files={"file": (Path(wav_path).name, f, "audio/wav")},
  1096. data={"model": model},
  1097. timeout=stt_cfg["timeout"])
  1098. resp.raise_for_status()
  1099. result = resp.json()
  1100. # Zhipu/GLM: {"choices": [{"message": {"content": ...}}]}; OpenAI/Whisper: {"text": ...}
  1101. choices = result.get("choices", [])
  1102. content = choices[0].get("message", {}).get("content", "") if choices else ""
  1103. return content.strip() or result.get("text", "").strip() or None
  1104. except (OSError, httpx.HTTPStatusError) as exc:
  1105. logger.warning("[%s] STT API call failed (model=%s, base=%s): %s", self._log_tag, model, base_url[:50], exc)
  1106. return None
  1107. async def _convert_audio_to_wav(self, audio_data: bytes, source_url: str) -> Optional[str]:
  1108. """Convert audio bytes to .wav (pilk for SILK, else ffmpeg) and cache the result;
  1109. on conversion failure the original bytes are cached as ``qq_voice<ext>``."""
  1110. ext = Path(urlparse(source_url).path).suffix.lower()
  1111. if ext not in _AUDIO_URL_EXTENSIONS:
  1112. ext = self._guess_ext_from_data(audio_data)
  1113. src_path, wav_path = self._temp_pair(audio_data, ext)
  1114. is_silk = ext == ".silk" or self._looks_like_silk(audio_data)
  1115. convert = self._convert_silk_to_wav if is_silk else self._convert_ffmpeg_to_wav
  1116. try:
  1117. if not await convert(src_path, wav_path):
  1118. logger.warning("[%s] audio conversion failed for %s (format=%s)", self._log_tag, source_url[:60], ext)
  1119. return await cache_document_from_bytes_async(audio_data, f"qq_voice{ext}")
  1120. except Exception:
  1121. return await cache_document_from_bytes_async(audio_data, f"qq_voice{ext}")
  1122. finally:
  1123. self._unlink_quiet(src_path)
  1124. try:
  1125. wav_data = Path(wav_path).read_bytes()
  1126. os.unlink(wav_path)
  1127. return await cache_document_from_bytes_async(wav_data, "qq_voice.wav")
  1128. except Exception as exc:
  1129. logger.debug("[%s] Failed to read converted wav: %s", self._log_tag, exc)
  1130. return None
  1131. # ── Outbound messaging — REST API ──
  1132. def _require_http_client(self) -> httpx.AsyncClient:
  1133. if not self._http_client:
  1134. raise RuntimeError("HTTP client not initialized — not connected?")
  1135. return self._http_client
  1136. async def _api_request(
  1137. self, method: str, path: str, body: Optional[dict[str, Any]] = None, timeout: float = DEFAULT_API_TIMEOUT,
  1138. ) -> dict[str, Any]:
  1139. client = self._require_http_client()
  1140. headers = await self._auth_headers()
  1141. try:
  1142. resp = await client.request(method, f"{API_BASE}{path}", headers=headers, json=body, timeout=timeout)
  1143. data = resp.json()
  1144. if resp.status_code >= 400:
  1145. raise RuntimeError(f"QQ Bot API error [{resp.status_code}] {path}: {data.get('message', data)}")
  1146. return data
  1147. except httpx.TimeoutException as exc:
  1148. raise RuntimeError(f"QQ Bot API timeout [{path}]: {exc}") from exc
  1149. async def _auth_headers(self) -> dict[str, str]:
  1150. """JSON REST headers with a fresh bot token."""
  1151. token = await self._ensure_token()
  1152. return {"Authorization": f"QQBot {token}", "Content-Type": "application/json", "User-Agent": build_user_agent()}
  1153. async def _upload_media(
  1154. self, target_type: str, target_id: str, file_type: int, url: Optional[str] = None,
  1155. file_data: Optional[str] = None, srv_send_msg: bool = False, file_name: Optional[str] = None,
  1156. ) -> dict[str, Any]:
  1157. path = self._rest_path(target_type, target_id, "files")
  1158. body: dict[str, Any] = {"file_type": file_type, "srv_send_msg": srv_send_msg}
  1159. if url:
  1160. body["url"] = url
  1161. elif file_data:
  1162. body["file_data"] = file_data
  1163. if file_type == MEDIA_TYPE_FILE and file_name:
  1164. body["file_name"] = file_name
  1165. for attempt in range(3): # retry transient upload failures
  1166. try:
  1167. return await self._api_request("POST", path, body, timeout=FILE_UPLOAD_TIMEOUT)
  1168. except RuntimeError as exc:
  1169. if attempt == 2 or any(kw in str(exc) for kw in ("400", "401", "Invalid", "timeout", "Timeout")):
  1170. raise
  1171. await asyncio.sleep(1.5 * (attempt + 1))
  1172. _RECONNECT_WAIT_SECONDS = 15.0 # max wait for reconnection before giving up on send
  1173. _RECONNECT_POLL_INTERVAL = 0.5 # is_connected poll interval while waiting
  1174. async def _wait_for_reconnection(self) -> bool:
  1175. """Poll is_connected for up to _RECONNECT_WAIT_SECONDS — covers the race where
  1176. send() lands between a disconnect and _listen_loop's reconnect."""
  1177. logger.info(
  1178. "[%s] Not connected — waiting for reconnection (up to %.0fs)", self._log_tag, self._RECONNECT_WAIT_SECONDS
  1179. )
  1180. waited = 0.0
  1181. while waited < self._RECONNECT_WAIT_SECONDS:
  1182. await asyncio.sleep(self._RECONNECT_POLL_INTERVAL)
  1183. waited += self._RECONNECT_POLL_INTERVAL
  1184. if self.is_connected:
  1185. logger.info("[%s] Reconnected after %.1fs", self._log_tag, waited)
  1186. return True
  1187. logger.warning("[%s] Still not connected after %.0fs", self._log_tag, self._RECONNECT_WAIT_SECONDS)
  1188. return False
  1189. @property
  1190. def _NOT_CONNECTED(self) -> SendResult:
  1191. return SendResult(success=False, error="Not connected", retryable=True)
  1192. async def _ensure_connected(self) -> bool:
  1193. """True when connected now or after waiting for the listener to reconnect."""
  1194. return self.is_connected or await self._wait_for_reconnection()
  1195. async def send(
  1196. self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[dict[str, Any]] = None,
  1197. ) -> SendResult:
  1198. """Send text/markdown: format, split via truncate_message(), retry transient failures."""
  1199. del metadata
  1200. if not await self._ensure_connected():
  1201. return self._NOT_CONNECTED
  1202. if not content or not content.strip():
  1203. return SendResult(success=True)
  1204. chunks = self.truncate_message(self.format_message(content), self.MAX_MESSAGE_LENGTH)
  1205. last_result = SendResult(success=False, error="No chunks")
  1206. for chunk in chunks:
  1207. last_result = await self._send_chunk(chat_id, chunk, reply_to)
  1208. if not last_result.success:
  1209. return last_result
  1210. reply_to = None # only reply_to the first chunk
  1211. return last_result
  1212. _PERMANENT_SEND_ERRORS = ("invalid", "forbidden", "not found")
  1213. async def _send_chunk(self, chat_id: str, content: str, reply_to: Optional[str] = None) -> SendResult:
  1214. last_exc: Optional[Exception] = None
  1215. sender = self._text_sender(self._guess_chat_type(chat_id))
  1216. if sender is None:
  1217. return SendResult(success=False, error=f"Unknown chat type for {chat_id}")
  1218. for attempt in range(3):
  1219. try:
  1220. return await sender(chat_id, content, reply_to)
  1221. except Exception as exc:
  1222. last_exc = exc
  1223. if any(k in str(exc).lower() for k in self._PERMANENT_SEND_ERRORS + ("bad request",)):
  1224. break # permanent — don't retry
  1225. if attempt < 2:
  1226. delay = 1.0 * (2 ** attempt)
  1227. logger.warning("[%s] send retry %d/3 after %.1fs: %s", self._log_tag, attempt + 1, delay, exc)
  1228. await asyncio.sleep(delay)
  1229. error_msg = (str(last_exc) or type(last_exc).__name__) if last_exc else "Unknown error"
  1230. logger.error("[%s] Send failed: %s", self._log_tag, error_msg)
  1231. retryable = not any(k in error_msg.lower() for k in self._PERMANENT_SEND_ERRORS)
  1232. return SendResult(success=False, error=error_msg, retryable=retryable)
  1233. @staticmethod
  1234. def _rest_path(chat_type: str, target_id: str, endpoint: str) -> str:
  1235. """``/v2/{users|groups}/{id}/{endpoint}`` for a c2c user or a group."""
  1236. kind = "users" if chat_type == "c2c" else "groups"
  1237. return f"/v2/{kind}/{target_id}/{endpoint}"
  1238. @classmethod
  1239. def _messages_path(cls, chat_type: str, target_id: str) -> str:
  1240. return cls._rest_path(chat_type, target_id, "messages")
  1241. async def _post_message(self, path: str, body: dict[str, Any]) -> SendResult:
  1242. """POST a message body and wrap the response as a successful SendResult."""
  1243. data = await self._api_request("POST", path, body)
  1244. return SendResult(success=True, message_id=str(data.get("id", uuid.uuid4().hex[:12])), raw_response=data)
  1245. async def _send_text_to(
  1246. self, chat_type: str, target_id: str, content: str, reply_to: Optional[str] = None,
  1247. keyboard: Optional[InlineKeyboard] = None) -> SendResult:
  1248. """Send text (optionally with an inline keyboard) to a c2c user or group."""
  1249. self._next_msg_seq(reply_to or target_id)
  1250. body = self._build_text_body(content, reply_to)
  1251. if reply_to:
  1252. body["msg_id"] = reply_to
  1253. if keyboard is not None:
  1254. body["keyboard"] = keyboard.to_dict()
  1255. return await self._post_message(self._messages_path(chat_type, target_id), body)
  1256. async def _send_c2c_text(self, openid, content, reply_to=None, keyboard=None) -> SendResult:
  1257. return await self._send_text_to("c2c", openid, content, reply_to, keyboard)
  1258. async def _send_group_text(self, group_openid, content, reply_to=None, keyboard=None) -> SendResult:
  1259. return await self._send_text_to("group", group_openid, content, reply_to, keyboard)
  1260. _TEXT_SENDERS = {"c2c": "_send_c2c_text", "group": "_send_group_text", "guild": "_send_guild_text"}
  1261. def _text_sender(self, chat_type: str, *, keyboard_ok: bool = False):
  1262. """Bound text sender for *chat_type* (None if unsupported); guild lacks keyboards."""
  1263. if keyboard_ok and chat_type == "guild":
  1264. return None
  1265. name = self._TEXT_SENDERS.get(chat_type)
  1266. return getattr(self, name) if name else None
  1267. async def _send_guild_text(self, channel_id: str, content: str, reply_to: Optional[str] = None) -> SendResult:
  1268. body: dict[str, Any] = {"content": content[: self.MAX_MESSAGE_LENGTH]}
  1269. if reply_to:
  1270. body["msg_id"] = reply_to
  1271. return await self._post_message(f"/channels/{channel_id}/messages", body)
  1272. # ── Inline-keyboard outbound helpers (approval / update-prompt flows) ──
  1273. async def send_with_keyboard(
  1274. self, chat_id: str, content: str, keyboard: InlineKeyboard, reply_to: Optional[str] = None,
  1275. ) -> SendResult:
  1276. """Send ONE text message with an inline keyboard (no chunking — splitting
  1277. would orphan the buttons; keep bodies short). Guild chats are unsupported."""
  1278. if not await self._ensure_connected():
  1279. return self._NOT_CONNECTED
  1280. chat_type = self._guess_chat_type(chat_id)
  1281. sender = self._text_sender(chat_type, keyboard_ok=True)
  1282. if sender is None:
  1283. return SendResult(
  1284. success=False, error=f"Inline keyboards not supported for chat_type {chat_type!r}", retryable=False)
  1285. truncated = self.format_message(content)[: self.MAX_MESSAGE_LENGTH]
  1286. try:
  1287. return await sender(chat_id, truncated, reply_to, keyboard=keyboard)
  1288. except Exception as exc:
  1289. logger.error("[%s] send_with_keyboard failed: %s", self._log_tag, exc)
  1290. return SendResult(success=False, error=str(exc) or type(exc).__name__)
  1291. async def send_approval_request(
  1292. self, chat_id: str, req: ApprovalRequest, reply_to: Optional[str] = None) -> SendResult:
  1293. """Send a 3-button approval request (allow-once / allow-always / deny);
  1294. clicks come back as INTERACTION_CREATE decoded by parse_approval_button_data."""
  1295. from .keyboards import build_approval_text
  1296. keyboard = build_approval_keyboard(req.session_key, allow_permanent=getattr(req, "allow_permanent", True))
  1297. return await self.send_with_keyboard(chat_id, build_approval_text(req), keyboard, reply_to=reply_to)
  1298. # Cross-adapter gateway contract: gateway/run.py detects send_exec_approval /
  1299. # send_update_prompt on the adapter class for button-based approval/update UX.
  1300. _APPROVAL_TIMEOUT_SECONDS = 300 # matches gateway's default gateway_timeout
  1301. async def _send_exec_approval_prompt(self, prompt: ExecApprovalPrompt) -> SendResult:
  1302. """Keyboard-card approval (called while the agent blocks on approval); clicks resolve via
  1303. _default_interaction_dispatch. QQ's 3-button keyboard has no session tier and no thread /
  1304. DM targeting, so only the ``always`` choice and the raw command/reason are used."""
  1305. description = prompt.description
  1306. if prompt.smart_denied:
  1307. description += " Owner override applies to this one operation only."
  1308. req = ApprovalRequest(
  1309. session_key=prompt.session_key, title="Execute this command?", description=description,
  1310. command_preview=prompt.command, timeout_sec=self._APPROVAL_TIMEOUT_SECONDS,
  1311. allow_permanent="always" in prompt.choices)
  1312. # QQ requires a msg_id for passive replies; the last inbound id is the natural one.
  1313. return await self.send_approval_request(
  1314. prompt.chat_id, req, reply_to=self._last_msg_id.get(prompt.chat_id))
  1315. async def send_update_prompt(
  1316. self, chat_id: str, prompt: str, default: str = "", session_key: str = "",
  1317. metadata: Optional[dict[str, Any]] = None) -> SendResult:
  1318. """Yes/No update-confirmation prompt; button clicks (``update_prompt:y|n``)
  1319. are written to ``~/.hermes/.update_response`` by the interaction callback."""
  1320. del session_key, metadata # present for contract parity only.
  1321. default_hint = f" (default: {default})" if default else ""
  1322. content = f"☤ **Update Needs Your Input**\n\n{prompt}{default_hint}"
  1323. return await self.send_with_keyboard(
  1324. chat_id, content, build_update_prompt_keyboard(), reply_to=self._last_msg_id.get(chat_id)
  1325. )
  1326. def _build_text_body(self, content: str, reply_to: Optional[str] = None) -> dict[str, Any]:
  1327. msg_seq = self._next_msg_seq(reply_to or "default")
  1328. text = content[: self.MAX_MESSAGE_LENGTH]
  1329. if self._markdown_support:
  1330. return {"markdown": {"content": text}, "msg_type": MSG_TYPE_MARKDOWN, "msg_seq": msg_seq}
  1331. body: dict[str, Any] = {"content": text, "msg_type": MSG_TYPE_TEXT, "msg_seq": msg_seq}
  1332. if reply_to:
  1333. body["message_reference"] = {"message_id": reply_to}
  1334. return body
  1335. # ── Native media sending ──
  1336. async def send_image(
  1337. self, chat_id: str, image_url: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
  1338. metadata: Optional[dict[str, Any]] = None) -> SendResult:
  1339. """Send an image natively via QQ Bot API upload; URL sources fall back to text."""
  1340. del metadata
  1341. result = await self._send_media(chat_id, image_url, MEDIA_TYPE_IMAGE, "image", caption, reply_to)
  1342. if result.success or not self._is_url(image_url):
  1343. return result
  1344. logger.warning("[%s] Image send failed, falling back to text: %s", self._log_tag, result.error)
  1345. fallback = f"{caption}\n{image_url}" if caption else image_url
  1346. return await self.send(chat_id=chat_id, content=fallback, reply_to=reply_to)
  1347. async def send_image_file(self, chat_id, image_path, caption=None, reply_to=None, **kwargs) -> SendResult:
  1348. return await self._send_media(chat_id, image_path, MEDIA_TYPE_IMAGE, "image", caption, reply_to)
  1349. async def send_voice(self, chat_id, audio_path, caption=None, reply_to=None, **kwargs) -> SendResult:
  1350. return await self._send_media(chat_id, audio_path, MEDIA_TYPE_VOICE, "voice", caption, reply_to)
  1351. async def send_video(self, chat_id, video_path, caption=None, reply_to=None, **kwargs) -> SendResult:
  1352. return await self._send_media(chat_id, video_path, MEDIA_TYPE_VIDEO, "video", caption, reply_to)
  1353. async def send_document(
  1354. self, chat_id, file_path, caption=None, file_name=None, reply_to=None, **kwargs
  1355. ) -> SendResult:
  1356. return await self._send_media(
  1357. chat_id, file_path, MEDIA_TYPE_FILE, "file", caption, reply_to, file_name=file_name)
  1358. async def _send_media(
  1359. self, chat_id: str, media_source: str, file_type: int, kind: str, caption: Optional[str] = None,
  1360. reply_to: Optional[str] = None, file_name: Optional[str] = None) -> SendResult:
  1361. """Upload media and send as a native message. HTTP(S) URLs → single ``POST
  1362. .../files`` with ``url=`` (QQ fetches it). Local files → chunked upload
  1363. (prepare / PUT parts / complete), up to the platform's ~100 MB per-file limit."""
  1364. if not await self._ensure_connected():
  1365. return self._NOT_CONNECTED
  1366. chat_type = self._guess_chat_type(chat_id)
  1367. if chat_type == "guild":
  1368. return SendResult(success=False, error="Guild media send not supported via this path")
  1369. try:
  1370. if self._is_url(media_source):
  1371. resolved_name = file_name or Path(urlparse(media_source).path).name or "media"
  1372. upload = await self._upload_media(
  1373. chat_type, chat_id, file_type, url=media_source, srv_send_msg=False,
  1374. file_name=resolved_name if file_type == MEDIA_TYPE_FILE else None)
  1375. else:
  1376. upload = await self._upload_local_file(chat_type, chat_id, media_source, file_type, file_name)
  1377. file_info = upload.get("file_info") or (upload.get("data", {}) or {}).get("file_info")
  1378. if not file_info:
  1379. return SendResult(success=False, error=f"Upload returned no file_info: {upload}")
  1380. body: dict[str, Any] = {
  1381. "msg_type": MSG_TYPE_MEDIA, "media": {"file_info": file_info}, "msg_seq": self._next_msg_seq(chat_id)}
  1382. if caption:
  1383. body["content"] = caption[: self.MAX_MESSAGE_LENGTH]
  1384. if reply_to:
  1385. body["msg_id"] = reply_to
  1386. return await self._post_message(self._messages_path(chat_type, chat_id), body)
  1387. except UploadDailyLimitExceededError as exc:
  1388. # Non-retryable quota hit; give the model actionable text.
  1389. logger.warning("[%s] Daily upload limit exceeded for %s (%s)", self._log_tag, exc.file_name, exc.file_size_human)
  1390. return SendResult(
  1391. success=False, retryable=False,
  1392. error=f"QQ daily upload limit exceeded for {exc.file_name!r} ({exc.file_size_human}). Retry tomorrow.")
  1393. except UploadFileTooLargeError as exc:
  1394. logger.warning(
  1395. "[%s] File too large: %s (%s, platform limit %s)",
  1396. self._log_tag, exc.file_name, exc.file_size_human, exc.limit_human)
  1397. return SendResult(
  1398. success=False, retryable=False,
  1399. error=f"{exc.file_name!r} ({exc.file_size_human}) exceeds the QQ per-file upload limit ({exc.limit_human}).")
  1400. except Exception as exc:
  1401. logger.error("[%s] Media send failed: %s", self._log_tag, exc)
  1402. return SendResult(success=False, error=str(exc) or type(exc).__name__)
  1403. async def _upload_local_file(
  1404. self, chat_type: str, chat_id: str, media_source: str, file_type: int, file_name: Optional[str],
  1405. ) -> dict[str, Any]:
  1406. """Chunked-upload a local file; returns the complete response whose ``file_info`` goes
  1407. into the RichMedia body. Raises UploadDailyLimitExceededError / UploadFileTooLargeError
  1408. from the uploader, ValueError for placeholder paths like ``<path>``, FileNotFoundError."""
  1409. client = self._require_http_client()
  1410. local_path = Path(media_source).expanduser()
  1411. if not local_path.is_absolute():
  1412. local_path = (Path.cwd() / local_path).resolve()
  1413. if not local_path.exists() or not local_path.is_file():
  1414. if media_source.startswith("<") or len(media_source) < 3:
  1415. raise ValueError(f"Invalid media source (looks like a placeholder): {media_source!r}")
  1416. raise FileNotFoundError(f"Media file not found: {local_path}")
  1417. uploader = ChunkedUploader(api_request=self._api_request, http_put=client.put, log_tag=self._log_tag)
  1418. return await uploader.upload(
  1419. chat_type=chat_type, target_id=chat_id, file_path=str(local_path), file_type=file_type,
  1420. file_name=file_name or local_path.name)
  1421. # ── Typing indicator ──
  1422. async def send_typing(self, chat_id: str, metadata=None) -> None:
  1423. """C2C-only input notify, debounced to ~50s (API shows a 60s indicator);
  1424. needs the last inbound msg_id from ``_last_msg_id``."""
  1425. msg_id = self._last_msg_id.get(chat_id)
  1426. now = time.time()
  1427. if (
  1428. not self.is_connected or self._guess_chat_type(chat_id) != "c2c" or not msg_id
  1429. or now - self._typing_sent_at.get(chat_id, 0.0) < self._TYPING_DEBOUNCE_SECONDS
  1430. ):
  1431. return
  1432. try:
  1433. body = {
  1434. "msg_type": MSG_TYPE_INPUT_NOTIFY,
  1435. "msg_id": msg_id,
  1436. "input_notify": {"input_type": 1, "input_second": self._TYPING_INPUT_SECONDS},
  1437. "msg_seq": self._next_msg_seq(chat_id)}
  1438. await self._api_request("POST", f"/v2/users/{chat_id}/messages", body)
  1439. self._typing_sent_at[chat_id] = now
  1440. except Exception as exc:
  1441. logger.debug("[%s] send_typing failed: %s", self._log_tag, exc)
  1442. # ── Format / chat info / helpers ──
  1443. def format_message(self, content: str) -> str:
  1444. """Pass markdown through when supported, else strip it (as BlueBubbles/SMS do)."""
  1445. return content if self._markdown_support else strip_markdown(content)
  1446. async def get_chat_info(self, chat_id: str) -> dict[str, Any]:
  1447. chat_type = self._guess_chat_type(chat_id)
  1448. return {"name": chat_id, "type": "group" if chat_type in {"group", "guild"} else "dm"}
  1449. @staticmethod
  1450. def _is_url(source: str) -> bool:
  1451. return urlparse(str(source)).scheme in {"http", "https"}
  1452. def _guess_chat_type(self, chat_id: str) -> str:
  1453. """Determine chat type from stored inbound metadata, fallback to 'c2c'."""
  1454. return self._chat_type_map.get(chat_id, "c2c")
  1455. @staticmethod
  1456. def _strip_at_mention(content: str) -> str:
  1457. return re.sub(r"^@\S+\s*", "", content.strip())
  1458. def _entry_matches(self, entries: list[str], target: str) -> bool:
  1459. normalized_target = str(target).strip().lower()
  1460. return any(str(e).strip().lower() in ("*", normalized_target) for e in entries)
  1461. def _parse_qq_timestamp(self, raw: str) -> datetime:
  1462. """Parse a QQ timestamp — ISO 8601 string (current) or integer ms (legacy)."""
  1463. if raw:
  1464. with contextlib.suppress(ValueError, TypeError):
  1465. return datetime.fromisoformat(raw)
  1466. with contextlib.suppress(ValueError, TypeError):
  1467. return datetime.fromtimestamp(int(raw) / 1000, tz=UTC)
  1468. return datetime.now(tz=UTC)