diff --git a/src/agenthub/channels/__init__.py b/src/agenthub/channels/__init__.py new file mode 100644 index 0000000..adf3249 --- /dev/null +++ b/src/agenthub/channels/__init__.py @@ -0,0 +1,15 @@ +"""IM channel implementations (peer front-ends to the NATS channel).""" + +from .base import IMChannel, InboundMessage +from .wecom import WecomAibotChannel +from .wecom_app import WecomAppChannel +from .weixin import WeixinApiError, WeixinChannel + +__all__ = [ + "IMChannel", + "InboundMessage", + "WecomAibotChannel", + "WecomAppChannel", + "WeixinChannel", + "WeixinApiError", +] diff --git a/src/agenthub/channels/base.py b/src/agenthub/channels/base.py new file mode 100644 index 0000000..852425e --- /dev/null +++ b/src/agenthub/channels/base.py @@ -0,0 +1,115 @@ +"""Channel abstraction: every inbound/outbound front-end implements this. + +A channel is identified by (channel, chat_id). All hub logic (session +binding, agent routing, permissions) is channel-agnostic. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Callable, Protocol + +# --------------------------------------------------------------------------- +# inbound message +# --------------------------------------------------------------------------- + +@dataclass +class InboundMessage: + channel: str # "wecom" | "wecom-app" | "weixin" | "nats" + chat_id: str # chat/user identifier within the channel + user_id: str # sender identity (for ACL) + text: str = "" + images: list[bytes] = field(default_factory=list) # raw bytes + image_mime: str = "image/png" + raw: dict[str, Any] = field(default_factory=dict) + + +@dataclass +class ChannelUserRef: + channel: str + chat_id: str + user_id: str = "" + + +# --------------------------------------------------------------------------- +# outbound event sink — channels decide how to present progress +# --------------------------------------------------------------------------- + +EventSink = Callable[[str, str, dict[str, Any]], None] +"""sink(chat_id, kind, payload); kind in: + "delta" - text chunk (streaming append) + "replace" - full replacement of current bubble text + "status" - transient status line (tool running, thinking...) + "final" - terminal text for the turn + "permission" - permission request payload (needs user decision) +""" + + +class IMChannel(Protocol): + """Lifecycle + IO contract for all IM front-ends.""" + + name: str + + def start(self) -> None: ... + def stop(self) -> None: ... + + def on_message(self, cb: Callable[[InboundMessage], None]) -> None: ... + def set_event_sink(self, sink: EventSink) -> None: ... + + def reply(self, chat_id: str, text: str) -> None: ... + def push_event(self, chat_id: str, kind: str, payload: dict[str, Any]) -> None: ... + + +# --------------------------------------------------------------------------- +# helpers shared by channels +# --------------------------------------------------------------------------- + +def split_message_text(value: str, limit: int) -> list[str]: + """Split text into chunks <= limit chars, preferring \\n then space breaks. + + Mirrors dsh-im shared/editable-message-stream.splitMessageText. + """ + text = (value or "").strip() + if not text: + return [] + chunks: list[str] = [] + remaining = text + while len(remaining.encode("utf-8")) > limit: + # operate on utf-8 byte budget like WeCom requires + cut = _byte_safe_cut(remaining, limit) + chunks.append(remaining[:cut].strip()) + remaining = remaining[cut:].lstrip() + if remaining: + chunks.append(remaining) + return chunks + + +def _byte_safe_cut(text: str, byte_limit: int) -> int: + """Largest char index whose utf-8 prefix fits byte_limit, cut at \\n/space if reasonable.""" + cut = len(text) + acc = 0 + for i, ch in enumerate(text): + w = 1 if ord(ch) < 0x80 else (2 if ord(ch) < 0x800 else (3 if ord(ch) < 0x10000 else 4)) + if acc + w > byte_limit: + cut = i + break + acc += w + window = text[:cut] + nl = window.rfind("\n") + if nl >= int(cut * 0.55): + return nl + sp = window.rfind(" ") + if sp >= int(cut * 0.55): + return sp + return cut + + +def clean_control_chars(value: str, max_len: int = 80) -> str: + """Strip Cc/Cf (zero-width etc.) — WeCom/ZWSP hygiene.""" + out = [] + for ch in (value or "")[: max_len * 4]: + o = ord(ch) + if o in (0x200B, 0x200C, 0x200D, 0xFEFF) or (o < 0x20 and ch not in "\n\t"): + continue # drop, don't substitute + out.append(ch) + return "".join(out).strip()[:max_len] diff --git a/src/agenthub/channels/editable_stream.py b/src/agenthub/channels/editable_stream.py new file mode 100644 index 0000000..2a81ab7 --- /dev/null +++ b/src/agenthub/channels/editable_stream.py @@ -0,0 +1,114 @@ +"""Editable-message stream: create one bubble, edit it periodically, flush remainder. + +Generic pattern for platforms with an "edit message" API (WeCom template +card update / aibot replyStream / any edit endpoint). Mirrors dsh-im's +shared/editable-message-stream. + +Usage: + stream = EditableMessageStream( + create=lambda text: api.send(chat_id, text), # -> msg_id + edit=lambda msg_id, text: api.edit(msg_id, text), + send_remainder=lambda text: api.send(chat_id, text), + limit=4000, update_interval_ms=800, + ) + stream.append("chunk...") # call from event thread + stream.close() # final flush +""" + +from __future__ import annotations + +import threading +import time +from typing import Any, Callable + +from .base import split_message_text + + +class EditableMessageStream: + def __init__( + self, + create: Callable[[str], Any], + edit: Callable[[Any, str], Any], + send_remainder: Callable[[str], Any] | None = None, + limit: int = 4000, + update_interval_s: float = 0.8, + initial_text: str = "正在处理…", + on_error: Callable[[Exception], None] | None = None, + ): + self._create = create + self._edit = edit + self._send_remainder = send_remainder + self._limit = limit + self._interval = update_interval_s + self._on_error = on_error + self._msg_id: Any = None + self._buffer: list[str] = [] + self._sent_text = "" + self._lock = threading.Lock() + self._last_edit = 0.0 + self._closed = False + self._started = False + + def _safe(self, fn, *args): + try: + return fn(*args) + except Exception as e: # noqa: BLE001 - delivery errors must not kill the turn + if self._on_error: + try: + self._on_error(e) + except Exception: + pass + + def append(self, text: str) -> None: + if self._closed or not text: + return + with self._lock: + self._buffer.append(text) + pending = self._sent_text + "".join(self._buffer) + now = time.monotonic() + if self._msg_id is None: + if not self._started: + self._started = True + self._msg_id = self._safe(self._create, initial_bubble(pending)) + self._last_edit = now + return + if now - self._last_edit >= self._interval: + self._flush_locked(pending, now) + + def _flush_locked(self, pending: str, now: float) -> None: + shown = pending[: self._limit * 4] + if len(shown.encode("utf-8")) > self._limit: + shown = shown[: max(1, self._limit // 4) * 4] + # re-trim to a char count whose utf-8 fits + while len(shown.encode("utf-8")) > self._limit and shown: + shown = shown[:-1] + self._safe(self._edit, self._msg_id, shown) + self._sent_text = pending + self._buffer.clear() + self._last_edit = now + + def close(self, final_text: str | None = None) -> None: + with self._lock: + if self._closed: + return + self._closed = True + pending = self._sent_text + "".join(self._buffer) + self._buffer.clear() + text = final_text if final_text is not None else pending + if not text: + return + # if too long for one bubble: edit remainder into follow-up messages + chunks = split_message_text(text, self._limit) + if self._msg_id is None: + for c in chunks: + self._safe(self._create, c) + return + first, rest = (chunks[0], chunks[1:]) if chunks else ("", []) + self._safe(self._edit, self._msg_id, first) + send = self._send_remainder or self._create + for c in rest: + self._safe(send, c) + + +def initial_bubble(pending: str) -> str: + return (pending[:120] + "…") if pending else "正在处理…" diff --git a/src/agenthub/channels/wecom.py b/src/agenthub/channels/wecom.py new file mode 100644 index 0000000..aa62dd6 --- /dev/null +++ b/src/agenthub/channels/wecom.py @@ -0,0 +1,244 @@ +"""WeCom aibot channel: official WebSocket long-connection via @wecom aibot API. + +Python port of dsh-im src/channels/wecom (runtime/bridge patterns), speaking +the aibot WebSocket protocol directly: +- wss long connection, auth handshake with bot token/secret +- client.replyStream(frame, reqId, chunk, finished) for streaming replies +- client.sendMessage(chatId, {msgtype}) for active sends +- reconnect with backoff; auth-failure is terminal + +Config (dict): + bot_id: str + secret: str + domain: str = "https://open.weixin.qq.com" # aibot gateway + connect_timeout_s: float = 20 + max_reconnect_attempts: int = 10 + reply_timeout_s: float = 600 + allowed_users: list[str] = [] # empty = allow all + +Note: requires `websockets` (or aiohttp) at runtime; M1.5 ships with a +mockable transport so tests run without the real gateway. +""" + +from __future__ import annotations + +import json +import threading +import time +import uuid +from typing import Any, Callable + +from .base import IMChannel, InboundMessage, clean_control_chars, split_message_text + +# aibot protocol message types (subset used here) +MT_REPLY_STREAM = "reply_stream" +MT_SEND_MESSAGE = "send_message" + + +class WecomAibotChannel: + name = "wecom" + + def __init__( + self, + config: dict[str, Any], + ws_factory: Callable[[dict[str, Any]], Any] | None = None, + logger: Any = None, + ): + self.bot_id = config["bot_id"] + self.secret = config["secret"] + self.domain = config.get("domain", "https://open.weixin.qq.com") + self.connect_timeout_s = float(config.get("connect_timeout_s", 20)) + self.max_reconnect = int(config.get("max_reconnect_attempts", 10)) + self.reply_timeout_s = float(config.get("reply_timeout_s", 600)) + self.allowed_users = set(config.get("allowed_users") or []) + self._ws_factory = ws_factory # returns object with send/recv/close + self._logger = logger or _default_logger() + self._msg_cb: Callable[[InboundMessage], None] | None = None + self._sink: Callable[[str, str, dict], None] | None = None + self._stop = threading.Event() + self._thread: threading.Thread | None = None + self._ws = None # current socket (set by _connect_and_serve) + # frame -> stream state for streaming replies + self._streams: dict[str, dict] = {} + self._stream_lock = threading.Lock() + + # -- IMChannel --------------------------------------------------------- + def start(self) -> None: + self._stop.clear() + self._thread = threading.Thread(target=self._run, name="wecom-aibot", daemon=True) + self._thread.start() + + def stop(self) -> None: + self._stop.set() + + def on_message(self, cb: Callable[[InboundMessage], None]) -> None: + self._msg_cb = cb + + def set_event_sink(self, sink: Callable[[str, str, dict], None]) -> None: + self._sink = sink + + # -- connection loop --------------------------------------------------- + def _run(self) -> None: + attempt = 0 + while not self._stop.is_set(): + try: + self._connect_and_serve() + attempt = 0 + except _AuthFailure as e: + self._logger.error(f"[wecom] auth failed, giving up: {e}") + return + except Exception as e: # noqa: BLE001 + attempt += 1 + if attempt > self.max_reconnect: + self._logger.error(f"[wecom] reconnect exhausted ({attempt}): {e}") + return + delay = min(2**attempt, 30) + self._logger.warning(f"[wecom] disconnected ({e}); retry {attempt}/{self.max_reconnect} in {delay}s") + self._stop.wait(delay) + + def _connect_and_serve(self) -> None: + if self._ws_factory is None: + raise RuntimeError("wecom channel requires a ws_factory (real or mock transport)") + ws = self._ws_factory( + { + "bot_id": self.bot_id, + "secret": self.secret, + "domain": self.domain, + "timeout_s": self.connect_timeout_s, + } + ) + ws.connect() + self._ws = ws + self._logger.info("[wecom] WebSocket authenticated") + try: + while not self._stop.is_set(): + raw = ws.recv(timeout=1.0) + if raw is None: + continue + msg = json.loads(raw) + self._dispatch(msg, ws) + finally: + try: + ws.close() + except Exception: # noqa: BLE001 + pass + + # -- inbound ----------------------------------------------------------- + def _dispatch(self, msg: dict[str, Any], ws: Any) -> None: + # aibot frames carry a callback payload; adapt per real protocol fields + frame_id = msg.get("frame_id") or msg.get("msgid") or uuid.uuid4().hex + body = msg.get("body") or msg + sender = (body.get("from") or {}).get("userid") or body.get("sender") or "" + chat_id = body.get("chatid") or body.get("chat_id") or sender + if self.allowed_users and sender and sender not in self.allowed_users: + self._logger.warning(f"[wecom] user {sender} not allowed, dropped") + return + text = "" + images: list[bytes] = [] + msgtype = body.get("msgtype", "text") + if msgtype == "text": + text = (body.get("text") or {}).get("content", "") + elif msgtype == "image": + b64 = (body.get("image") or {}).get("base64", "") + if b64: + import base64 + + images.append(base64.b64decode(b64)) + elif msgtype == "markdown": + text = (body.get("markdown") or {}).get("content", "") + text = clean_control_chars(text, max_len=100000).strip() if text else "" + if not text and not images: + return + if self._msg_cb: + self._msg_cb( + InboundMessage( + channel=self.name, + chat_id=str(chat_id), + user_id=str(sender), + text=text, + images=images, + raw={"frame_id": frame_id, "msg": msg}, + ) + ) + + # -- outbound ---------------------------------------------------------- + def reply(self, chat_id: str, text: str) -> None: + for chunk in split_message_text(text, 4000): + self._send({"type": MT_SEND_MESSAGE, "chatid": chat_id, "msgtype": "markdown", "markdown": {"content": chunk}}) + + def push_event(self, chat_id: str, kind: str, payload: dict[str, Any]) -> None: + if kind == "delta": + self._stream_append(chat_id, str(payload.get("text", ""))) + elif kind == "status": + # transient status → only reflected in the bubble text when no deltas yet + self._stream_ensure(chat_id, str(payload.get("text", ""))) + elif kind == "final": + self._stream_close(chat_id, str(payload.get("text", ""))) + elif kind == "permission": + self.reply(chat_id, _permission_text(payload)) + # "replace" treated as delta reset for now + + # -- streaming state --------------------------------------------------- + def _stream_key_states(self, chat_id: str) -> dict: + with self._stream_lock: + return self._streams.setdefault(chat_id, {"req_id": uuid.uuid4().hex, "buf": "", "sent": False}) + + def _stream_ensure(self, chat_id: str, text: str) -> None: + st = self._stream_key_states(chat_id) + if not st["sent"]: + self._reply_stream(chat_id, st, text or "正在处理…", finished=False) + + def _stream_append(self, chat_id: str, text: str) -> None: + st = self._stream_key_states(chat_id) + st["buf"] += text + # rate: push edits at most every 0.8s (like dsh-im update_interval) + now = time.monotonic() + if now - st.get("last", 0) >= 0.8: + st["last"] = now + self._reply_stream(chat_id, st, st["buf"][-4000:], finished=False) + + def _stream_close(self, chat_id: str, final_text: str) -> None: + st = self._stream_key_states(chat_id) + text = final_text or st["buf"] + self._reply_stream(chat_id, st, text, finished=True) + with self._stream_lock: + self._streams.pop(chat_id, None) + + def _reply_stream(self, chat_id: str, st: dict, text: str, finished: bool) -> None: + self._send( + { + "type": MT_REPLY_STREAM, + "chatid": chat_id, + "req_id": st["req_id"], + "content": text, + "finished": finished, + } + ) + if finished: + st["sent"] = True + + def _send(self, obj: dict) -> None: + ws = getattr(self, "_ws", None) + if ws is None: + self._logger.warning("[wecom] send skipped, not connected") + return + ws.send(json.dumps(obj, ensure_ascii=False)) + + +class _AuthFailure(Exception): + pass + + +def _permission_text(payload: dict[str, Any]) -> str: + title = payload.get("title") or payload.get("tool", "operation") + return ( + f"⚠️ 权限请求:{title}\n" + f"回复「允许」执行;其他回复视为拒绝。\n" + f"请求 ID:{payload.get('request_id', '')}" + ) + + +def _default_logger(): + import logging + + return logging.getLogger("agenthub.wecom") diff --git a/src/agenthub/channels/wecom_app.py b/src/agenthub/channels/wecom_app.py new file mode 100644 index 0000000..a635660 --- /dev/null +++ b/src/agenthub/channels/wecom_app.py @@ -0,0 +1,317 @@ +"""WeCom 自建应用 channel: HTTP callback + qyapi.weixin.qq.com APIs. + +Port of dsh-im src/channels/wecom-app. Works in BOTH WeCom client and +WeChat (via 企业微信后台的「微信插件」) — same conversation, both ends. + +Protocol facts (from dsh-im docs/企业微信自建应用接入.md): +- callback: GET verify (echostr decrypt) + POST encrypted XML/JSON messages +- APIs: access_token (2h TTL, corp_id+secret), send message, upload media +- errors: 60020 = trusted-IP missing, 41004 = bad secret +- streaming: WeChat side has NO edit API -> always whole-message delivery; + WeCom client side also whole-message for self-built apps (aibot has + replyStream, self-built does not) +- http server runs in-thread (stdlib), no external web framework needed + +Config (dict): + corp_id, agent_id, secret, token, encoding_aes_key + callback_listen_host: str = "127.0.0.1" + callback_listen_port: int = 30987 + callback_base_url: str = "" # public base (IP:port or domain) + api_proxy: str = "" # optional reverse proxy for qyapi + allowed_users: list[str] = [] +""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import socket +import threading +import time +import urllib.parse +import urllib.request +import xml.etree.ElementTree as ET +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any, Callable + +from .base import IMChannel, InboundMessage, clean_control_chars, split_message_text + +QYAPI = "https://qyapi.weixin.qq.com" + + +# --------------------------------------------------------------------------- +# WXBizMsgCrypt equivalent (stdlib) — SHA1 sig + AES-CBC msg encryption +# --------------------------------------------------------------------------- + +class WxBizError(Exception): + pass + + +class WxMsgCrypt: + """企业微信消息加解密(sha1 签名 + AES-256-CBC,PKCS7,base64).""" + + def __init__(self, token: str, encoding_aes_key: str, corp_id: str): + self.token = token + self.corp_id = corp_id + key = base64.b64decode(encoding_aes_key + "=") + if len(key) != 32: + raise WxBizError("EncodingAESKey invalid") + self.key = key + + def _sign(self, timestamp: str, nonce: str, encrypt: str) -> str: + raw = "".join(sorted([self.token, timestamp, nonce, encrypt])) + return hashlib.sha1(raw.encode()).hexdigest() + + def verify_url(self, msg_signature: str, timestamp: str, nonce: str, echostr: str) -> str: + """Decrypt echostr for URL verification; raises WxBizError on mismatch.""" + if self._sign(timestamp, nonce, echostr) != msg_signature: + raise WxBizError("signature mismatch (verify URL)") + plain = self._decrypt(echostr) + return plain + + def decrypt_msg(self, msg_signature: str, timestamp: str, nonce: str, encrypt: str) -> str: + if self._sign(timestamp, nonce, encrypt) != msg_signature: + raise WxBizError("signature mismatch (msg)") + return self._decrypt(encrypt) + + def encrypt_msg(self, plain: str, nonce: str, timestamp: str | None = None) -> str: + import os + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + + ts = timestamp or str(int(time.time())) + rnd = os.urandom(16) + msg_bytes = plain.encode() + # 16B rnd + 4B network-order len + msg + corp_id + PKCS7 to 32-block + raw = ( + rnd + + len(msg_bytes).to_bytes(4, "big") + + msg_bytes + + self.corp_id.encode() + ) + pad = 32 - (len(raw) % 32) + raw += bytes([pad]) * pad + cipher = Cipher(algorithms.AES(self.key), modes.CBC(self.key[:16])) + enc = cipher.encryptor() + encrypted = enc.update(raw) + enc.finalize() + b64 = base64.b64encode(encrypted).decode() + sig = self._sign(ts, nonce, b64) + return json.dumps({"encrypt": b64, "msgsignature": sig, "timestamp": ts, "nonce": nonce}) + + def _decrypt(self, b64: str) -> str: + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + + data = base64.b64decode(b64) + if len(data) % 16 or len(data) < 32: + raise WxBizError("bad encrypted payload length") + cipher = Cipher(algorithms.AES(self.key), modes.CBC(self.key[:16])) + dec = cipher.decryptor() + raw = dec.update(data) + dec.finalize() + pad = raw[-1] + if not 1 <= pad <= 32: + raise WxBizError("bad PKCS7 padding") + raw = raw[:-pad] + msg_len = int.from_bytes(raw[16:20], "big") + corp = raw[20 + msg_len :].decode() + if corp != self.corp_id: + raise WxBizError(f"corp_id mismatch: {corp}") + return raw[20 : 20 + msg_len].decode() + + +# --------------------------------------------------------------------------- +# channel +# --------------------------------------------------------------------------- + +class WecomAppChannel: + name = "wecom-app" + + def __init__(self, config: dict[str, Any], logger: Any = None): + self.corp_id = config["corp_id"] + self.agent_id = str(config["agent_id"]) + self.secret = config["secret"] + self.token = config["token"] + self.aes_key = config["encoding_aes_key"] + self.host = config.get("callback_listen_host", "127.0.0.1") + self.port = int(config.get("callback_listen_port", 30987)) + self.api_base = (config.get("api_proxy") or QYAPI).rstrip("/") + self.allowed_users = set(config.get("allowed_users") or []) + + self.crypt = WxMsgCrypt(self.token, self.aes_key, self.corp_id) + self._msg_cb: Callable[[InboundMessage], None] | None = None + self._logger = logger or _log() + self._server: ThreadingHTTPServer | None = None + self._thread: threading.Thread | None = None + self._stop = threading.Event() + self._access_token: str = "" + self._token_exp: float = 0 + self._token_lock = threading.Lock() + self._external = self # for handler closure + + # -- IMChannel --------------------------------------------------------- + def start(self) -> None: + outer = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, format, *args): # noqa: A002 - stdlib signature + pass + + def do_GET(self): + q = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query) + ms, ts, nc = q.get("msg_signature", [""])[0], q.get("timestamp", [""])[0], q.get("nonce", [""])[0] + echo = q.get("echostr", [""])[0] + try: + plain = outer.crypt.verify_url(ms, ts, nc, echo) + self._respond(200, plain.encode()) + except WxBizError as e: + outer._logger.warning(f"[wecom-app] URL verify failed: {e}") + self._respond(403, b"verify failed") + + def do_POST(self): + length = int(self.headers.get("Content-Length", 0)) + body = self.rfile.read(length) + q = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query) + ms = q.get("msg_signature", [""])[0] + ts = q.get("timestamp", [""])[0] + nc = q.get("nonce", [""])[0] + self._respond(200, b"success") # ack fast, process async + try: + encrypt = _extract_encrypt(body) + plain_xml = outer.crypt.decrypt_msg(ms, ts, nc, encrypt) + outer._on_plain_xml(plain_xml) + except Exception as e: # noqa: BLE001 + outer._logger.error(f"[wecom-app] msg processing failed: {e}") + + def _respond(self, code: int, data: bytes): + self.send_response(code) + self.send_header("Content-Type", "text/plain; charset=utf-8") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + self._server = ThreadingHTTPServer((self.host, self.port), Handler) + self._thread = threading.Thread(target=self._server.serve_forever, name="wecom-app-callback", daemon=True) + self._thread.start() + self._logger.info(f"[wecom-app] callback server on {self.host}:{self.port}") + + def stop(self) -> None: + self._stop.set() + if self._server: + self._server.shutdown() + + def on_message(self, cb: Callable[[InboundMessage], None]) -> None: + self._msg_cb = cb + + def set_event_sink(self, sink: Callable[[str, str, dict], None]) -> None: + self._sink = sink + + # -- inbound ----------------------------------------------------------- + def _on_plain_xml(self, xml_text: str) -> None: + root = ET.fromstring(xml_text) + get = lambda tag: (root.findtext(tag) or "").strip() # noqa: E731 + sender = get("FromUserName") + if self.allowed_users and sender not in self.allowed_users: + return + msgtype = get("MsgType") + text, images = "", [] + if msgtype == "text": + text = get("Content") + elif msgtype == "image": + data = self._download_media(get("PicUrl")) + if data: + images.append(data) + elif msgtype in ("voice", "video", "location"): + text = f"[{msgtype} message omitted]" # M1.5 scope: text/image only + text = clean_control_chars(text, max_len=100000).strip() + if not text and not images: + return + if self._msg_cb: + self._msg_cb( + InboundMessage( + channel=self.name, + chat_id=sender, # self-built app: 1:1 by user + user_id=sender, + text=text, + images=images, + raw={"msg_id": get("MsgID"), "msg_type": msgtype}, + ) + ) + + # -- outbound ---------------------------------------------------------- + def get_access_token(self) -> str: + with self._token_lock: + if self._access_token and time.monotonic() < self._token_exp: + return self._access_token + url = ( + f"{self.api_base}/cgi-bin/gettoken" + f"?corpid={urllib.parse.quote(self.corp_id)}&corpsecret={urllib.parse.quote(self.secret)}" + ) + with urllib.request.urlopen(url, timeout=10) as resp: + d = json.loads(resp.read()) + if d.get("errcode"): + raise RuntimeError(f"gettoken failed: {d}") + self._access_token = d["access_token"] + self._token_exp = time.monotonic() + int(d.get("expires_in", 7200)) - 120 + return self._access_token + + def reply(self, chat_id: str, text: str) -> None: + for chunk in split_message_text(text, 2000): # self-built markdown limit + self._api( + "/cgi-bin/message/send", + { + "touser": chat_id, + "msgtype": "markdown", + "agentid": self.agent_id, + "markdown": {"content": chunk}, + }, + ) + + def push_event(self, chat_id: str, kind: str, payload: dict[str, Any]) -> None: + # Self-built apps have no edit API: coalesce deltas, deliver on final. + if kind == "delta": + return # accumulate in session layer; final carries full text + if kind == "final": + self.reply(chat_id, str(payload.get("text", ""))) + elif kind == "status": + pass # no transient surface on this channel + elif kind == "permission": + self.reply(chat_id, _permission_text(payload)) + + # -- helpers ----------------------------------------------------------- + def _api(self, path: str, payload: dict) -> dict: + url = f"{self.api_base}{path}?access_token={self.get_access_token()}" + req = urllib.request.Request( + url, data=json.dumps(payload, ensure_ascii=False).encode(), headers={"Content-Type": "application/json"} + ) + with urllib.request.urlopen(req, timeout=15) as resp: + d = json.loads(resp.read()) + if d.get("errcode") not in (0, None): + raise RuntimeError(f"{path} -> {d}") + return d + + def _download_media(self, url: str) -> bytes | None: + try: + with urllib.request.urlopen(url, timeout=15) as resp: + return resp.read() + except Exception as e: # noqa: BLE001 + self._logger.warning(f"[wecom-app] media download failed: {e}") + return None + + +def _extract_encrypt(body: bytes) -> str: + """Callback body may be XML () or JSON ({"encrypt": ...}).""" + text = body.decode("utf-8", "replace").lstrip() + if text.startswith("<"): + root = ET.fromstring(text) + return (root.findtext("Encrypt") or "").strip() + return (json.loads(text)).get("encrypt", "") + + +def _permission_text(payload: dict[str, Any]) -> str: + title = payload.get("title") or payload.get("tool", "operation") + return f"⚠️ 权限请求:{title}\n回复「允许」执行;其他回复视为拒绝。" + + +def _log(): + import logging + + return logging.getLogger("agenthub.wecom-app") diff --git a/src/agenthub/channels/weixin.py b/src/agenthub/channels/weixin.py new file mode 100644 index 0000000..0b05e3b --- /dev/null +++ b/src/agenthub/channels/weixin.py @@ -0,0 +1,208 @@ +"""WeChat 智能机器人 channel: QR-scan login + getupdates long-polling. + +Port of dsh-im src/channels/weixin (API surface only, no protocol hacks): +- login: POST /ilink/bot/get_bot_qrcode?bot_type=... -> {qrcode,...} + GET /ilink/bot/get_qrcode_status?qrcode=... (long poll, optional verify_code) + -> token on success +- receive: POST /ilink/bot/getupdates {get_updates_buf} (long poll; timeout + returns empty msgs, NOT an error) +- send: POST /ilink/bot/sendmessage (whole-text only, no edit API) +- base: https://ilinkai.weixin.qq.com/ + +Config (dict): + token: str = "" # existing login token (skip QR if set) + bot_type: str = "" # passed to get_bot_qrcode + base_url: str = default + poll_timeout_ms: int = 35000 + allowed_users: list[str] = [] + +Login flow: call start_login() to get a QR for the user to scan with +WeChat; poll_login() yields status; on success the token is stored via +token_provider (persist it — scanning is manual). +""" + +from __future__ import annotations + +import json +import threading +import time +import urllib.error +import urllib.parse +import urllib.request +from typing import Any, Callable + +from .base import IMChannel, InboundMessage, clean_control_chars, split_message_text + +DEFAULT_BASE = "https://ilinkai.weixin.qq.com/" +DEFAULT_POLL_TIMEOUT_MS = 35_000 + + +class WeixinApiError(Exception): + def __init__(self, code: str, message: str, provider: Any = None): + super().__init__(f"{code}: {message}") + self.code = code + self.provider = provider + + +class WeixinChannel: + name = "weixin" + + def __init__( + self, + config: dict[str, Any], + http_post: Callable[[str, dict, str | None, int], dict] | None = None, + http_get: Callable[[str, int], dict] | None = None, + token_persist: Callable[[str], None] | None = None, + logger: Any = None, + ): + self.base_url = (config.get("base_url") or DEFAULT_BASE).rstrip("/") + "/" + self.bot_type = config.get("bot_type", "") + self.poll_timeout_ms = int(config.get("poll_timeout_ms", DEFAULT_POLL_TIMEOUT_MS)) + self.allowed_users = set(config.get("allowed_users") or []) + self._token: str = config.get("token", "") + self._get_updates_buf = "" + self._http_post = http_post or self._default_post + self._http_get = http_get or self._default_get + self._token_persist = token_persist + self._logger = logger or _log() + self._msg_cb: Callable[[InboundMessage], None] | None = None + self._stop = threading.Event() + self._thread: threading.Thread | None = None + self._poll_thread: threading.Thread | None = None + + # -- IMChannel --------------------------------------------------------- + def start(self) -> None: + if not self._token: + raise WeixinApiError("no-token", "call start_login()/finish QR scan first, or set config token") + self._stop.clear() + self._poll_thread = threading.Thread(target=self._poll_loop, name="weixin-poll", daemon=True) + self._poll_thread.start() + + def stop(self) -> None: + self._stop.set() + + def on_message(self, cb: Callable[[InboundMessage], None]) -> None: + self._msg_cb = cb + + def set_event_sink(self, sink: Callable[[str, str, dict], None]) -> None: + self._sink = sink + + # -- login ------------------------------------------------------------- + def start_login(self, local_tokens: list[str] | None = None) -> dict[str, str]: + """Request a login QR; returns {qrcode, qrcode_url}. User must scan.""" + body: dict[str, Any] = {"local_token_list": local_tokens or []} + if self.bot_type: + resp = self._http_post(f"ilink/bot/get_bot_qrcode?bot_type={urllib.parse.quote(self.bot_type)}", body, None, 10_000) + else: + resp = self._http_post("ilink/bot/get_bot_qrcode", body, None, 10_000) + qrcode = resp.get("qrcode") + if not qrcode: + raise WeixinApiError("invalid-qr", "微信服务没有返回二维码令牌", resp) + return {"qrcode": qrcode, "qrcode_url": resp.get("qrcode_img_content", "")} + + def poll_login(self, qrcode: str, verify_code: str = "", timeout_s: float = 120) -> str: + """Long-poll QR status until confirmed; returns the bot token.""" + deadline = time.monotonic() + timeout_s + endpoint = f"ilink/bot/get_qrcode_status?qrcode={urllib.parse.quote(qrcode)}" + if verify_code: + endpoint += f"&verify_code={urllib.parse.quote(verify_code)}" + while time.monotonic() < deadline and not self._stop.is_set(): + resp = self._http_get(endpoint, 40_000) + status = resp.get("status") + if status == "confirmed" or resp.get("token"): + self._token = resp["token"] + if self._token_persist: + self._token_persist(self._token) + self._logger.info("[weixin] login confirmed") + return self._token + if status in ("expired", "rejected"): + raise WeixinApiError(f"login-{status}", f"扫码登录{ '过期' if status=='expired' else '被拒绝' }") + time.sleep(1.0) + raise WeixinApiError("login-timeout", "扫码登录超时") + + # -- receive ----------------------------------------------------------- + def _poll_loop(self) -> None: + self._logger.info("[weixin] long-poll started") + while not self._stop.is_set(): + try: + resp = self._http_post( + "ilink/bot/getupdates", + {"get_updates_buf": self._get_updates_buf, "base_info": {}}, + self._token, + self.poll_timeout_ms, + ) + msgs = resp.get("msgs") or [] + self._get_updates_buf = resp.get("get_updates_buf", self._get_updates_buf) + for m in msgs: + self._handle(m) + except Exception as e: # noqa: BLE001 - keep polling on transient errors + self._logger.warning(f"[weixin] poll error: {e}; backoff 3s") + self._stop.wait(3) + + def _handle(self, msg: dict[str, Any]) -> None: + sender = str(msg.get("from_user_id") or msg.get("sender") or "") + chat_id = sender # 1:1 DM: peer = sender + if self.allowed_users and sender not in self.allowed_users: + return + text = "" + msgtype = msg.get("msg_type", "") + if msgtype in ("text", 1, "1"): + text = msg.get("text", {}).get("content", "") if isinstance(msg.get("text"), dict) else str(msg.get("content", "")) + text = clean_control_chars(text, max_len=100000).strip() + if not text: + return + if self._msg_cb: + self._msg_cb(InboundMessage(channel=self.name, chat_id=chat_id, user_id=sender, text=text, raw={"msg": msg})) + + # -- outbound ---------------------------------------------------------- + def reply(self, chat_id: str, text: str) -> None: + for chunk in split_message_text(text, 2000): + self._http_post( + "ilink/bot/sendmessage", + {"to_user_id": chat_id, "msg_type": "text", "text": {"content": chunk}}, + self._token, + 15_000, + ) + + def push_event(self, chat_id: str, kind: str, payload: dict[str, Any]) -> None: + # No edit API: deltas coalesce away, only final text is delivered. + if kind == "final": + self.reply(chat_id, str(payload.get("text", ""))) + elif kind == "permission": + self.reply(chat_id, _permission_text(payload)) + + # -- transport defaults ------------------------------------------------ + def _default_post(self, endpoint: str, body: dict, token: str | None, timeout_ms: int) -> dict: + url = self.base_url + endpoint + headers = {"Content-Type": "application/json"} + if token: + headers["Authorization"] = f"Bearer {token}" + req = urllib.request.Request(url, data=json.dumps(body).encode(), headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout_ms / 1000 + 5) as resp: + return json.loads(resp.read()) + except urllib.error.HTTPError as e: + raise WeixinApiError("http-error", f"{e.code} on {endpoint}", e.read()[:200]) from e + except urllib.error.URLError as e: + if "timed out" in str(e.reason): + return {} # long-poll timeout: empty tick + raise WeixinApiError("network", str(e)) from e + + def _default_get(self, endpoint: str, timeout_ms: int) -> dict: + url = self.base_url + endpoint + try: + with urllib.request.urlopen(url, timeout=timeout_ms / 1000 + 5) as resp: + return json.loads(resp.read()) + except urllib.error.HTTPError as e: + raise WeixinApiError("http-error", f"{e.code} on {endpoint}") from e + + +def _permission_text(payload: dict[str, Any]) -> str: + title = payload.get("title") or payload.get("tool", "operation") + return f"⚠️ 权限请求:{title}\n回复「允许」执行;其他回复视为拒绝。" + + +def _log(): + import logging + + return logging.getLogger("agenthub.weixin") diff --git a/tests/test_channels.py b/tests/test_channels.py new file mode 100644 index 0000000..6f03992 --- /dev/null +++ b/tests/test_channels.py @@ -0,0 +1,171 @@ +"""Tests for the three IM channels (mock transports, no network).""" + +from __future__ import annotations + +import base64 +import json +import os +import sys +import urllib.request +import xml.etree.ElementTree as ET + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) + +from agenthub.channels.base import clean_control_chars, split_message_text # noqa: E402 +from agenthub.channels.wecom import WecomAibotChannel # noqa: E402 +from agenthub.channels.wecom_app import WxMsgCrypt # noqa: E402 +from agenthub.channels.weixin import WeixinChannel # noqa: E402 + + +# --------------------------------------------------------------------------- +# base helpers +# --------------------------------------------------------------------------- + +def test_split_prefers_newline(): + assert split_message_text("ab\ncd", 4) == ["ab", "cd"] + + +def test_split_hard_cut_utf8_safe(): + parts = split_message_text("你好世界", 4) # 4 bytes = 1 chinese char + part + assert all(p.encode("utf-8") for p in parts) + assert "".join(parts) == "你好世界" + + +def test_clean_control_chars(): + assert clean_control_chars("a\u200bb\u0000c", 100) == "abc" + + +# --------------------------------------------------------------------------- +# wecom aibot +# --------------------------------------------------------------------------- + +class MockWS: + def __init__(self): + self.sent = [] + self.incoming = [] + + def connect(self): + pass + + def recv(self, timeout=1.0): + if self.incoming: + return self.incoming.pop(0) + return None + + def send(self, raw): + self.sent.append(json.loads(raw)) + + def close(self): + pass + + +def _make_wecom(): + ws = MockWS() + ch = WecomAibotChannel( + {"bot_id": "b", "secret": "s", "allowed_users": ["u1"]}, + ws_factory=lambda cfg: ws, + ) + return ch, ws + + +def test_wecom_dispatch_text_and_permission(): + ch, ws = _make_wecom() + got = [] + ch.on_message(got.append) + ws.incoming.append( + json.dumps({"frame_id": "f1", "body": {"msgtype": "text", "from": {"userid": "u1"}, "chatid": "c1", "text": {"content": "hello\u200b"}}}) + ) + ch._dispatch(json.loads(ws.incoming[0]), ws) + assert len(got) == 1 and got[0].text == "hello" and got[0].chat_id == "c1" + + +def test_wecom_allowed_users_drops_others(): + ch, ws = _make_wecom() + got = [] + ch.on_message(got.append) + ch._dispatch({"frame_id": "f2", "body": {"msgtype": "text", "from": {"userid": "u2"}, "chatid": "c", "text": {"content": "x"}}}, ws) + assert got == [] + + +def test_wecom_streaming_delta_coalesce_and_final(): + ch, ws = _make_wecom() + ch._ws = ws # pretend connected (stream sends go through the socket) + ch.push_event("c1", "delta", {"text": "hello "}) + ch.push_event("c1", "delta", {"text": "world"}) + # force-time independent: final flushes buffer + ch.push_event("c1", "final", {"text": "hello world"}) + replies = [m for m in ws.sent if m["type"] == "reply_stream"] + assert replies and replies[-1]["finished"] is True + assert replies[-1]["content"] == "hello world" + assert len({m["req_id"] for m in replies}) == 1 # same bubble + + +# --------------------------------------------------------------------------- +# wecom-app crypto round-trip +# --------------------------------------------------------------------------- + +def test_wxbiz_crypt_roundtrip(): + import os + + key = base64.b64encode(os.urandom(32)).decode().rstrip("=") + crypt = WxMsgCrypt("tok", key, "corp123") + nonce, ts = "n1", "1700000000" + enc = crypt.encrypt_msg("hi", nonce, ts) + payload = json.loads(enc) + assert crypt._sign(ts, nonce, payload["encrypt"]) == payload["msgsignature"] + plain = crypt._decrypt(payload["encrypt"]) + assert plain == "hi" + + +# --------------------------------------------------------------------------- +# weixin +# --------------------------------------------------------------------------- + +class MockHTTP: + def __init__(self, responses): + self.responses = responses + self.posts = [] + + def post(self, endpoint, body, token, timeout_ms): + self.posts.append((endpoint, body, token)) + return self.responses.get(endpoint, {}) + + def get(self, endpoint, timeout_ms): + return self.responses.get(endpoint, {}) + + +def test_weixin_login_flow(): + http = MockHTTP( + { + "ilink/bot/get_bot_qrcode": {"qrcode": "qr1"}, + "ilink/bot/get_qrcode_status?qrcode=qr1": {"status": "confirmed", "token": "tk"}, + } + ) + ch = WeixinChannel({}, http_post=http.post, http_get=http.get) + qr = ch.start_login() + assert qr["qrcode"] == "qr1" + token = ch.poll_login("qr1", timeout_s=3) + assert token == "tk" and ch._token == "tk" + + +def test_weixin_receive_and_reply(): + http = MockHTTP({"ilink/bot/getupdates": {"msgs": [], "get_updates_buf": ""}}) + ch = WeixinChannel({"token": "tk"}, http_post=http.post, http_get=http.get) + got = [] + ch.on_message(got.append) + ch._handle({"from_user_id": "wxid_1", "to_user_id": "bot", "msg_type": "text", "text": {"content": " hi\u200b "}}) + assert got[0].text == "hi" and got[0].chat_id == "wxid_1" + + ch.reply("wxid_1", "answer") + ep, body, token = http.posts[-1] + assert ep == "ilink/bot/sendmessage" and token == "tk" + assert body["text"]["content"] == "answer" + + +def test_weixin_no_edit_deltas_dropped_final_sent(): + http = MockHTTP({}) + ch = WeixinChannel({"token": "tk"}, http_post=http.post, http_get=http.get) + ch.push_event("u", "delta", {"text": "partial"}) + assert not http.posts + ch.push_event("u", "final", {"text": "full text"}) + assert http.posts[-1][1]["text"]["content"] == "full text"