yuanbao_proto.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. """yuanbao_proto.py - Yuanbao WebSocket 协议编解码(手写 protobuf wire-format,不依赖 google.protobuf)
  2. 每个 WebSocket frame = 一条 ConnMsg protobuf(标准 protobuf;conn.proto 注释里的 magic+len 二进制格式只用于 quic/tcp):
  3. ConnMsg { Head head=1 (cmd_type, cmd, seq_no, msg_id, module, ...); bytes data=2 }
  4. data = 业务 payload(InboundMessagePush / SendC2CMessageReq / ...,包 trpc.yuanbao.yuanbao_conn.yuanbao_openclaw_proxy.*)
  5. """
  6. from __future__ import annotations
  7. import threading
  8. import time
  9. from typing import Optional
  10. # conn 层消息类型(ConnMsg.Head.cmd_type)
  11. PB_MSG_TYPES = {
  12. n: f"trpc.yuanbao.conn_common.{n}"
  13. for n in ("ConnMsg", "AuthBindReq", "AuthBindRsp", "PingReq", "PingRsp", "KickoutMsg", "DirectedPush", "PushMsg")
  14. }
  15. # cmd_type: 上行请求 / 请求回包 / 下行推送 / 推送 ACK
  16. CMD_TYPE = {"Request": 0, "Response": 1, "Push": 2, "PushAck": 3}
  17. CMD = {"AuthBind": "auth-bind", "Ping": "ping", "Kickout": "kickout", "UpdateMeta": "update-meta"}
  18. MODULE = {"ConnAccess": "conn_access"}
  19. # biz 层服务/方法映射。TS client 使用短名 'yuanbao_openclaw_proxy'(非完整包路径)。
  20. _BIZ_PKG = "yuanbao_openclaw_proxy"
  21. BIZ_SERVICES = {
  22. n: f"{_BIZ_PKG}.{n}"
  23. for n in ("InboundMessagePush",) + tuple(
  24. f"{m}{k}" for m in ("SendC2CMessage", "SendGroupMessage", "QueryGroupInfo", "GetGroupMemberList",
  25. "SendPrivateHeartbeat", "SendGroupHeartbeat") for k in ("Req", "Rsp")
  26. )
  27. }
  28. HERMES_INSTANCE_ID = 17 # openclaw instance_id(固定值)
  29. WS_HEARTBEAT_RUNNING = 1
  30. WS_HEARTBEAT_FINISH = 2
  31. _seq_lock = threading.Lock()
  32. _seq_counter = 0
  33. _SEQ_MAX = 2 ** 32 - 1 # uint32 上限
  34. def next_seq_no() -> int:
  35. """生成递增序列号(线程安全,溢出时归零)"""
  36. global _seq_counter
  37. with _seq_lock:
  38. val = _seq_counter
  39. _seq_counter = (_seq_counter + 1) & _SEQ_MAX
  40. return val
  41. # ---- Protobuf wire-format 基础工具
  42. WT_VARINT = 0
  43. WT_64BIT = 1
  44. WT_LEN = 2
  45. WT_32BIT = 5
  46. _FIXED_SIZE = {WT_64BIT: 8, WT_32BIT: 4}
  47. def _encode_varint(value: int) -> bytes:
  48. """protobuf varint(负数按 64-bit two's complement)"""
  49. if value < 0:
  50. value &= 0xFFFFFFFFFFFFFFFF
  51. out = []
  52. while True:
  53. bits = value & 0x7F
  54. value >>= 7
  55. if not value:
  56. out.append(bits)
  57. return bytes(out)
  58. out.append(bits | 0x80)
  59. def _decode_varint(data: bytes, pos: int) -> tuple[int, int]:
  60. """从 data[pos:] 解码 varint,返回 (value, new_pos)"""
  61. result = 0
  62. shift = 0
  63. while pos < len(data):
  64. b = data[pos]
  65. pos += 1
  66. result |= (b & 0x7F) << shift
  67. shift += 7
  68. if not (b & 0x80):
  69. break
  70. if shift >= 64:
  71. raise ValueError("varint too long")
  72. return result, pos
  73. def _encode_field(field_number: int, wire_type: int, value: bytes) -> bytes:
  74. return _encode_varint((field_number << 3) | wire_type) + value
  75. def _encode_message(b: bytes) -> bytes:
  76. """length-prefixed bytes / 嵌套 message value"""
  77. return _encode_varint(len(b)) + b
  78. def _encode_string(s: str) -> bytes:
  79. return _encode_message(s.encode("utf-8"))
  80. # 完整 field 编码快捷方式:string / varint / 嵌套 message
  81. def _s(fn: int, s: str) -> bytes:
  82. return _encode_field(fn, WT_LEN, _encode_string(s))
  83. def _v(fn: int, n: int) -> bytes:
  84. return _encode_field(fn, WT_VARINT, _encode_varint(n))
  85. def _m(fn: int, b: bytes) -> bytes:
  86. return _encode_field(fn, WT_LEN, _encode_message(b))
  87. def _parse_fields(data: bytes) -> list[tuple[int, int, bytes | int]]:
  88. """→ [(field_number, wire_type, raw_value)];raw_value 为 int(VARINT)或 bytes(LEN / 64BIT / 32BIT)"""
  89. fields = []
  90. pos = 0
  91. while pos < len(data):
  92. tag, pos = _decode_varint(data, pos)
  93. wire_type = tag & 0x07
  94. if wire_type == WT_VARINT:
  95. val, pos = _decode_varint(data, pos)
  96. else:
  97. if wire_type == WT_LEN:
  98. length, pos = _decode_varint(data, pos)
  99. elif wire_type in _FIXED_SIZE:
  100. length = _FIXED_SIZE[wire_type]
  101. else:
  102. raise ValueError(f"unknown wire type {wire_type} at pos {pos - 1}")
  103. val = data[pos: pos + length]
  104. pos += length
  105. fields.append((tag >> 3, wire_type, val))
  106. return fields
  107. def _fields_to_dict(fields: list) -> dict[int, list]:
  108. """→ {field_number: [(wire_type, value), ...]}(repeated 字段有多个)"""
  109. d: dict[int, list] = {}
  110. for fn, wt, val in fields:
  111. d.setdefault(fn, []).append((wt, val))
  112. return d
  113. def _parse_dict(data: bytes) -> dict[int, list]:
  114. return _fields_to_dict(_parse_fields(data))
  115. def _first(fdict: dict, fn: int, wt: int):
  116. """第一个字段值(仅当其 wire type 匹配),无则 None"""
  117. entries = fdict.get(fn)
  118. return entries[0][1] if entries and entries[0][0] == wt else None
  119. def _get_string(fdict: dict, fn: int, default: str = "") -> str:
  120. val = _first(fdict, fn, WT_LEN)
  121. return val.decode("utf-8", errors="replace") if isinstance(val, (bytes, bytearray)) else default
  122. def _get_varint(fdict: dict, fn: int, default: int = 0) -> int:
  123. val = _first(fdict, fn, WT_VARINT)
  124. return val if isinstance(val, int) else default
  125. def _get_bytes(fdict: dict, fn: int, default: bytes = b"") -> bytes:
  126. val = _first(fdict, fn, WT_LEN)
  127. return bytes(val) if isinstance(val, (bytes, bytearray)) else default
  128. def _get_repeated_bytes(fdict: dict, fn: int) -> list[bytes]:
  129. return [bytes(val) for wt, val in fdict.get(fn, []) if wt == WT_LEN]
  130. def _parse_repeated(fdict: dict, fn: int) -> list[dict]:
  131. return [_parse_dict(b) for b in _get_repeated_bytes(fdict, fn)]
  132. # 字段表编码:parts = [(field_number, kind, value)];kind:
  133. # "S" string 总是编码 "s" string 非空才编码 "v" varint 非零才编码 "n" varint 非 None 才编码 "m" 嵌套 bytes 非空才编码
  134. # "b" repeated MsgBodyElement "t" LogInfoExt{1 trace_id} 非空才编码
  135. _PART_ENCODERS = {
  136. "S": _s, "s": _s, "v": _v, "n": _v, "m": _m,
  137. "b": lambda fn, body: b"".join(_m(fn, _encode_msg_body_element(el)) for el in body),
  138. "t": lambda fn, trace_id: _m(fn, _s(1, trace_id)),
  139. }
  140. def _encode_parts(parts: list) -> bytes:
  141. buf = b""
  142. for fn, kind, val in parts:
  143. if kind == "S" or (val is not None if kind == "n" else val):
  144. buf += _PART_ENCODERS[kind](fn, val)
  145. return buf
  146. # 字段表驱动编解码:spec = [(field_number, key, kind)],kind:
  147. # "s" string(编码时 str(v)) "r" string(原值) "i" varint(编码时 int(v))
  148. # 编码跳过 falsy 值;解码只保留 truthy 值。spec 顺序即 wire 顺序和 dict 插入顺序。
  149. _STR_KINDS = ("s", "r")
  150. def _encode_spec(obj: dict, spec: list) -> bytes:
  151. buf = b""
  152. for fn, key, kind in spec:
  153. v = obj.get(key, "" if kind in _STR_KINDS else 0)
  154. if v:
  155. buf += _s(fn, str(v) if kind == "s" else v) if kind in _STR_KINDS else _v(fn, int(v))
  156. return buf
  157. def _decode_spec(fdict: dict, spec: list) -> dict:
  158. out: dict = {}
  159. for fn, key, kind in spec:
  160. v = _get_string(fdict, fn) if kind in _STR_KINDS else _get_varint(fdict, fn)
  161. if v:
  162. out[key] = v
  163. return out
  164. # ---- ConnMsg 层编解码
  165. # message Head { uint32 cmd_type=1; string cmd=2; uint32 seq_no=3; string msg_id=4;
  166. # string module=5; bool need_ack=6; ... int32 status=10; }
  167. # message ConnMsg { Head head=1; bytes data=2; }
  168. def _encode_head(
  169. cmd_type: int, cmd: str, seq_no: int, msg_id: str, module: str, need_ack: bool = False, status: int = 0,
  170. ) -> bytes:
  171. return _encode_parts([
  172. (1, "v", cmd_type), (2, "s", cmd), (3, "v", seq_no), (4, "s", msg_id), (5, "s", module),
  173. (6, "v", 1 if need_ack else 0), (10, "v", status & 0xFFFFFFFFFFFFFFFF),
  174. ])
  175. def _decode_head(data: bytes) -> dict:
  176. fd = _parse_dict(data)
  177. return {
  178. "cmd_type": _get_varint(fd, 1), "cmd": _get_string(fd, 2), "seq_no": _get_varint(fd, 3), "msg_id": _get_string(fd, 4),
  179. "module": _get_string(fd, 5), "need_ack": bool(_get_varint(fd, 6)), "status": _get_varint(fd, 10),
  180. }
  181. def encode_conn_msg_full(
  182. cmd_type: int, cmd: str, seq_no: int, msg_id: str, module: str, data: bytes, need_ack: bool = False,
  183. ) -> bytes:
  184. """编码完整的 ConnMsg(含 cmd/msg_id/module 等 head 字段)"""
  185. buf = _m(1, _encode_head(cmd_type, cmd, seq_no, msg_id, module, need_ack))
  186. return buf + _m(2, data) if data else buf
  187. def encode_conn_msg(msg_type: int, seq_no: int, data: bytes) -> bytes:
  188. """编码 ConnMsg(简化接口:仅 cmd_type + seq_no + payload)"""
  189. return encode_conn_msg_full(msg_type, "", seq_no, "", "", data)
  190. def decode_conn_msg(data: bytes) -> dict:
  191. """解码 ConnMsg → {msg_type, seq_no, data, head}(head 为完整 Head dict)"""
  192. fdict = _parse_dict(data)
  193. head = _decode_head(_get_bytes(fdict, 1))
  194. return {"msg_type": head["cmd_type"], "seq_no": head["seq_no"], "data": _get_bytes(fdict, 2), "head": head}
  195. def _conn_request(cmd_type: int, cmd: str, msg_id: str, module: str, data: bytes = b"") -> bytes:
  196. return encode_conn_msg_full(cmd_type, cmd, next_seq_no(), msg_id, module, data)
  197. # ---- BizMsg 层:业务 body 包装成 ConnMsg(head.cmd = method, head.module = service)
  198. # 与 conn-codec.ts buildBusinessConnMsg(cmd, module, bizData, msgId) 行为一致。
  199. def encode_biz_msg(service: str, method: str, req_id: str, body: bytes) -> bytes:
  200. """将已编码的业务 protobuf 包装为可直接发送的 ConnMsg bytes"""
  201. return _conn_request(CMD_TYPE["Request"], method, req_id, service, body)
  202. def decode_biz_msg(data: bytes) -> dict:
  203. """解码 ConnMsg → {service, method, req_id, body, is_response, head}"""
  204. result = decode_conn_msg(data)
  205. head = result["head"]
  206. return {
  207. "service": head["module"], "method": head["cmd"], "req_id": head["msg_id"], "body": result["data"],
  208. "is_response": head["cmd_type"] == CMD_TYPE["Response"], "head": head,
  209. }
  210. def _biz_request(method: str, prefix: str, body: bytes, msg_id: str = "") -> bytes:
  211. """biz 请求 ConnMsg;req_id 为 msg_id,空则 '<prefix>_<seq>'(seq 在 conn seq_no 之前分配)"""
  212. return encode_biz_msg(_BIZ_PKG, method, msg_id or f"{prefix}_{next_seq_no()}", body)
  213. # ---- 业务 protobuf 消息编解码(biz payload)
  214. # MsgContent:1 text, 2 uuid, 3 image_format, 4 data, 5 desc, 6 ext, 7 sound,
  215. # 8 image_info_array (repeated), 9 index, 10 url, 11 file_size, 12 file_name,
  216. # 999 ext_map (map<string,string>: repeated entry{1 key, 2 value})
  217. # ext_map key 格式 wexin_forward_msg_[forward_msg_id]_[userid],value 为
  218. # base64(ForwardMsgData protobuf)(不是 JSON),用 decode_forward_msg_data() 解析。
  219. _MSG_CONTENT_SPEC = [
  220. (1, "text", "s"), (2, "uuid", "s"), (4, "data", "s"), (5, "desc", "s"),
  221. (6, "ext", "s"), (7, "sound", "s"), (10, "url", "s"), (12, "file_name", "s"),
  222. (3, "image_format", "i"), (9, "index", "i"), (11, "file_size", "i"),
  223. ]
  224. _IMAGE_INFO_SPEC = [(1, "type", "i"), (2, "size", "i"), (3, "width", "i"), (4, "height", "i"), (5, "url", "r")]
  225. _MAP_ENTRY_SPEC = [(1, "key", "s"), (2, "value", "s")]
  226. def _encode_msg_content(content: dict) -> bytes:
  227. buf = _encode_spec(content, _MSG_CONTENT_SPEC)
  228. for img in content.get("image_info_array") or []:
  229. buf += _m(8, _encode_spec(img, _IMAGE_INFO_SPEC))
  230. ext_map = content.get("ext_map")
  231. if isinstance(ext_map, dict):
  232. for k, v in ext_map.items():
  233. buf += _m(999, _encode_spec({"key": str(k), "value": str(v)}, _MAP_ENTRY_SPEC))
  234. return buf
  235. def _decode_msg_content(data: bytes) -> dict:
  236. fdict = _parse_dict(data)
  237. content = _decode_spec(fdict, _MSG_CONTENT_SPEC)
  238. imgs = [img for img in (_decode_spec(d, _IMAGE_INFO_SPEC) for d in _parse_repeated(fdict, 8)) if img]
  239. ext_map = {_get_string(e, 1): _get_string(e, 2) for e in _parse_repeated(fdict, 999) if _get_string(e, 1)}
  240. content.update({k: v for k, v in (("image_info_array", imgs), ("ext_map", ext_map)) if v})
  241. return content
  242. # MsgBodyElement:1 msg_type (string, e.g. "TIMTextElem"), 2 msg_content (MsgContent)
  243. def _encode_msg_body_element(element: dict) -> bytes:
  244. content = element.get("msg_content", {})
  245. return _encode_parts([(1, "s", element.get("msg_type", "")), (2, "m", _encode_msg_content(content) if content else b"")])
  246. def _decode_msg_body_element(data: bytes) -> dict:
  247. fdict = _parse_dict(data)
  248. content_bytes = _get_bytes(fdict, 2)
  249. return {"msg_type": _get_string(fdict, 1), "msg_content": _decode_msg_content(content_bytes) if content_bytes else {}}
  250. # ---- 入站消息解析
  251. # InboundMessagePush 字段表 [(field_number, key, getter)];getter 为 _get_string / _get_varint 或自定义 (fdict, fn) -> value
  252. _INBOUND_PUSH_SPEC = [
  253. (1, "callback_command", _get_string), (2, "from_account", _get_string), (3, "to_account", _get_string),
  254. (4, "sender_nickname", _get_string), (5, "group_id", _get_string), (6, "group_code", _get_string),
  255. (7, "group_name", _get_string), (8, "msg_seq", _get_varint), (9, "msg_random", _get_varint),
  256. (10, "msg_time", _get_varint), (11, "msg_key", _get_string), (12, "msg_id", _get_string),
  257. (13, "msg_body", lambda fd, fn: [_decode_msg_body_element(b) for b in _get_repeated_bytes(fd, fn)]),
  258. (14, "cloud_custom_data", _get_string), (15, "event_time", _get_varint), (16, "bot_owner_id", _get_string),
  259. (17, "recall_msg_seq_list", lambda fd, fn: [ # repeated ImMsgSeq{1 msg_seq, 2 msg_id}
  260. {"msg_seq": _get_varint(d, 1), "msg_id": _get_string(d, 2)} for d in _parse_repeated(fd, fn)] or None),
  261. (18, "claw_msg_type", _get_varint), (19, "private_from_group_code", _get_string),
  262. (20, "trace_id", lambda fd, fn: _get_string(_parse_dict(_get_bytes(fd, fn)), 1) if _get_bytes(fd, fn) else ""), # LogInfoExt
  263. ]
  264. def decode_inbound_push(data: bytes) -> Optional[dict]:
  265. """解析 InboundMessagePush biz payload;空值已过滤(msg_body / msg_seq 始终保留),解析失败返回 None。"""
  266. try:
  267. fdict = _parse_dict(data)
  268. result = {key: get(fdict, fn) for fn, key, get in _INBOUND_PUSH_SPEC}
  269. return {k: v for k, v in result.items() if v or k in {"msg_body", "msg_seq"}}
  270. except Exception:
  271. return None
  272. # ---- WeChat forwarded chat-history parsing (ForwardMsgData)
  273. # ext_map["wexin_forward_msg_<id>_<userid>"] = base64(ForwardMsgData) — protobuf, NOT JSON.
  274. # Verified against live captures:
  275. # ForwardMsgData { uint32 sub_type=1 (1 = WeChat chat-history forward); uint32 begin_time=2;
  276. # uint32 end_time=3; string nick_name=4 (forwarder); repeated ForwardMsg msg=5 }
  277. # ForwardMsg { string sender=1; uint32 time=2; string plainText=3; repeated MsgContent msgContent=4 }
  278. # MsgContent { uint32 type=1 (1=TEXT, 2=MULTIMEDIA, 3=nested forward); string text=2;
  279. # repeated Multimedia multimedia=3 }
  280. # Multimedia { string type=1 (image/file/document/url/video); string url=2; string file_name=4;
  281. # uint32 file_size=5; uint32 width=6; uint32 height=7;
  282. # string media_id=15 (usable directly as a ybres RID); string res_type=24 }
  283. _FORWARD_MULTIMEDIA_SPEC = [(1, "type", "s"), (2, "url", "s"), (4, "file_name", "s"), (5, "file_size", "i"), (15, "media_id", "s")]
  284. def _decode_forward_msg_content(data: bytes) -> dict:
  285. """MsgContent → {type, text?, multimedia?}(shape 与 _format_multimedia 对齐)"""
  286. fdict = _parse_dict(data)
  287. content: dict = {"type": _get_varint(fdict, 1)}
  288. if _get_string(fdict, 2):
  289. content["text"] = _get_string(fdict, 2)
  290. if _get_repeated_bytes(fdict, 3):
  291. content["multimedia"] = [_decode_spec(d, _FORWARD_MULTIMEDIA_SPEC) for d in _parse_repeated(fdict, 3)]
  292. return content
  293. def _decode_forward_msg(fd: dict) -> dict:
  294. return {"sender": _get_string(fd, 1), "time": _get_varint(fd, 2), "plainText": _get_string(fd, 3),
  295. "msgContent": [_decode_forward_msg_content(b) for b in _get_repeated_bytes(fd, 4)]}
  296. def decode_forward_msg_data(data: bytes) -> Optional[dict]:
  297. """Parse ForwardMsgData bytes (base64-decoded ext_map value) into the {sub_type, nick_name, msg, ...}
  298. structure consumed by ForwardedRecordsParseMiddleware.build_forward_text; None on parse failure."""
  299. try:
  300. fd = _parse_dict(data)
  301. return {
  302. "sub_type": _get_varint(fd, 1), "begin_time": _get_varint(fd, 2), "end_time": _get_varint(fd, 3),
  303. "nick_name": _get_string(fd, 4), "msg": [_decode_forward_msg(d) for d in _parse_repeated(fd, 5)],
  304. }
  305. except Exception:
  306. return None
  307. # ---- Outbound message encoding
  308. def encode_send_c2c_message(
  309. to_account: str, msg_body: list, from_account: str, msg_id: str = "", msg_random: int = 0,
  310. msg_seq: Optional[int] = None, group_code: str = "", trace_id: str = "",
  311. ) -> bytes:
  312. """SendC2CMessageReq → 完整 ConnMsg bytes(可直接发送)。
  313. msg_body items are {"msg_type": str, "msg_content": dict}; msg_id doubles as req_id when set;
  314. group_code is filled for the "private chat originating from a group" case.
  315. """
  316. return _biz_request("send_c2c_message", "c2c", _encode_parts([
  317. (1, "s", msg_id), (2, "S", to_account), (3, "s", from_account), (4, "v", msg_random),
  318. (5, "b", msg_body), (6, "s", group_code), (7, "n", msg_seq), (8, "t", trace_id),
  319. ]), msg_id)
  320. def encode_send_group_message(
  321. group_code: str, msg_body: list, from_account: str, msg_id: str = "", to_account: str = "", random: str = "",
  322. msg_seq: Optional[int] = None, ref_msg_id: str = "", trace_id: str = "",
  323. ) -> bytes:
  324. """SendGroupMessageReq → 完整 ConnMsg bytes。to_account usually empty; ref_msg_id = quoted message."""
  325. return _biz_request("send_group_message", "grp", _encode_parts([
  326. (1, "s", msg_id), (2, "S", group_code), (3, "s", from_account), (4, "s", to_account), (5, "s", random),
  327. (6, "b", msg_body), (7, "s", ref_msg_id), (8, "n", msg_seq), (9, "t", trace_id),
  328. ]), msg_id)
  329. # ---- AuthBind / Ping / PushAck
  330. def encode_auth_bind(
  331. biz_id: str, uid: str, source: str, token: str, msg_id: str, app_version: str = "", operation_system: str = "",
  332. bot_version: str = "", route_env: str = "",
  333. ) -> bytes:
  334. """auth-bind 请求 ConnMsg bytes。
  335. AuthBindReq: 1 biz_id, 2 auth_info (AuthInfo{1 uid, 2 source, 3 token}),
  336. 3 device_info (DeviceInfo{1 app_version, 2 app_operation_system, 10 instance_id, 24 bot_version}),
  337. 5 env_name
  338. """
  339. dev_buf = _encode_parts([
  340. (1, "s", app_version), (2, "s", operation_system), (10, "S", str(HERMES_INSTANCE_ID)), (24, "s", bot_version),
  341. ])
  342. req_buf = _encode_parts([
  343. (1, "S", biz_id), (2, "m", _s(1, uid) + _s(2, source) + _s(3, token)), (3, "m", dev_buf), (5, "s", route_env),
  344. ])
  345. return _conn_request(CMD_TYPE["Request"], CMD["AuthBind"], msg_id, MODULE["ConnAccess"], req_buf)
  346. def encode_ping(msg_id: str) -> bytes:
  347. """ping 请求 ConnMsg bytes(PingReq 为空消息)"""
  348. return _conn_request(CMD_TYPE["Request"], CMD["Ping"], msg_id, MODULE["ConnAccess"])
  349. def encode_push_ack(original_head: dict) -> bytes:
  350. """push ACK 回包(回显原 head 的 cmd / msg_id / module)"""
  351. return _conn_request(
  352. CMD_TYPE["PushAck"], original_head.get("cmd", ""), original_head.get("msg_id", ""), original_head.get("module", ""),
  353. )
  354. # ---- Heartbeat / 群信息 / 群成员列表
  355. def encode_send_private_heartbeat(from_account: str, to_account: str, heartbeat: int = WS_HEARTBEAT_RUNNING) -> bytes:
  356. """SendPrivateHeartbeatReq{1 from_account, 2 to_account, 3 heartbeat (RUNNING=1, FINISH=2)} → ConnMsg bytes"""
  357. return _biz_request("send_private_heartbeat", "hb_priv", _s(1, from_account) + _s(2, to_account) + _v(3, heartbeat))
  358. def encode_send_group_heartbeat(
  359. from_account: str, group_code: str, heartbeat: int = WS_HEARTBEAT_RUNNING, send_time: int = 0,
  360. ) -> bytes:
  361. """SendGroupHeartbeatReq{1 from_account, 2 to_account (群场景留空), 3 group_code,
  362. 4 send_time (ms; 0 → now), 5 heartbeat} → ConnMsg bytes"""
  363. ts = send_time or int(time.time() * 1000)
  364. buf = _s(1, from_account) + _s(2, "") + _s(3, group_code) + _v(4, ts) + _v(5, heartbeat)
  365. return _biz_request("send_group_heartbeat", "hb_grp", buf)
  366. def encode_query_group_info(group_code: str) -> bytes:
  367. """QueryGroupInfoReq{1 group_code} → ConnMsg bytes"""
  368. return _biz_request("query_group_info", "qgi", _s(1, group_code))
  369. def decode_query_group_info_rsp(data: bytes) -> Optional[dict]:
  370. """QueryGroupInfoRsp{1 code, 2 message, 3 GroupInfo{1 group_name, 2 group_owner_user_id,
  371. 3 group_owner_nickname, 4 group_size}} → {code, message?, group_name, owner_id, owner_nickname,
  372. member_count}(对齐 TS member.ts queryGroupInfo);解析失败返回 None。"""
  373. try:
  374. fdict = _parse_dict(data)
  375. result: dict = {"code": _get_varint(fdict, 1)}
  376. if _get_string(fdict, 2):
  377. result["message"] = _get_string(fdict, 2)
  378. # field 3 taken regardless of wire type; non-bytes payloads fall back to defaults
  379. gi_entries = fdict.get(3, [])
  380. gi_bytes = gi_entries[0][1] if gi_entries else b""
  381. gi = _parse_dict(gi_bytes) if gi_bytes and isinstance(gi_bytes, (bytes, bytearray)) else {}
  382. result.update(
  383. group_name=_get_string(gi, 1), owner_id=_get_string(gi, 2), owner_nickname=_get_string(gi, 3),
  384. member_count=_get_varint(gi, 4),
  385. )
  386. return result
  387. except Exception:
  388. return None
  389. def encode_get_group_member_list(group_code: str, offset: int = 0, limit: int = 200) -> bytes:
  390. """GetGroupMemberListReq{1 group_code, 2 offset, 3 limit} → ConnMsg bytes"""
  391. return _biz_request("get_group_member_list", "gml", _s(1, group_code) + (_v(2, offset) if offset else b"") + _v(3, limit))
  392. def decode_get_group_member_list_rsp(data: bytes) -> Optional[dict]:
  393. """GetGroupMemberListRsp{1 code, 2 message, 3 members (repeated MemberInfo), 4 next_offset, 5 is_complete};
  394. MemberInfo{1 user_id, 2 nickname, 3 role (0=member,1=admin,2=owner), 4 join_time, 5 name_card (群昵称)}。
  395. member dict 过滤空值但保留 role;解析失败返回 None。"""
  396. try:
  397. fdict = _parse_dict(data)
  398. members = [
  399. {"user_id": _get_string(m, 1), "nickname": _get_string(m, 2), "role": _get_varint(m, 3),
  400. "join_time": _get_varint(m, 4), "name_card": _get_string(m, 5)}
  401. for m in _parse_repeated(fdict, 3)
  402. ]
  403. return {
  404. "code": _get_varint(fdict, 1), "message": _get_string(fdict, 2),
  405. "members": [{k: v for k, v in mem.items() if v or k == "role"} for mem in members],
  406. "next_offset": _get_varint(fdict, 4), "is_complete": bool(_get_varint(fdict, 5)),
  407. }
  408. except Exception:
  409. return None