JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat: 修改群聊消息助手消息出站&入站逻辑
Ziliang_Zhou5cb6e495bd47
diff --git a/jiuwenclaw/agentserver/tools/user_todo_tool.py b/jiuwenclaw/agentserver/tools/user_todo_tool.pyindex eb19ec7de7..30f0c5636a 100644--- a/jiuwenclaw/agentserver/tools/user_todo_tool.py+++ b/jiuwenclaw/agentserver/tools/user_todo_tool.py@@ -216,6 +216,8 @@ async def user_todos(params: UserTodosParams) -> Dict[str, Any]:Returns:操作结果字典"""+ if isinstance(params, dict):+ params = UserTodosParams(**{k: v for k, v in params.items() if k in UserTodosParams.__dataclass_fields__})return await _handle_user_todos(params)diff --git a/jiuwenclaw/channel/feishu.py b/jiuwenclaw/channel/feishu.pyindex e1b55a577d..0cf765ceb3 100644--- a/jiuwenclaw/channel/feishu.py+++ b/jiuwenclaw/channel/feishu.py@@ -1414,6 +1414,16 @@ class FeishuChannel(BaseChannel):await self._send_file_card(receive_id, id_type, fp, os.path.basename(fp))except Exception as file_err:logger.error("飞书兜底文件发送失败: %s %s", fp, file_err)++ # 群聊数字分身回复到群聊时,@发送人+ if msg.group_digital_avatar and id_type == "chat_id":+ sender_open_id = str(+ meta.get("im_sender_user_id")+ or meta.get("open_id")+ or ""+ ).strip()+ if sender_open_id and not sender_open_id.startswith("bot"):+ content_str = f"<at id={sender_open_id}></at>\n{content_str}"card_content = self._build_card_content(content_str)await self._send_feishu_message(receive_id, id_type, card_content, msg.id)@@ -1438,11 +1448,11 @@ class FeishuChannel(BaseChannel):else:chat_id = meta.get("feishu_chat_id") or ""- # 记录机器人回复消息到群聊历史中去- if chat_id:+ # 记录机器人回复消息到群聊历史中去(仅数字分身模式)+ if chat_id and self.config.group_digital_avatar:self._message_storage.add_message_to_memory(- chat_id=chat_id,- message={+ chat_id=chat_id,+ message={"message_id": f"bot_{int(time.time() * 1000)}_{msg.id}","content": content_str,"timestamp": int(time.time() * 1000),@@ -2077,36 +2087,46 @@ class FeishuChannel(BaseChannel):**({"file_info": file_info} if file_info else {}),}- # 记录消息到本地存储(支持数字分身记忆功能)- try:- self._message_storage.add_message_to_memory(+ # 记录消息到本地存储(仅数字分身模式)+ if self.config.group_digital_avatar:+ try:+ self._message_storage.add_message_to_memory(+ chat_id=message.chat_id,+ message={+ "message_id": message.message_id,+ "content": content,+ "timestamp": getattr(message, "create_time", int(time.time() * 1000)),+ "msg_type": message.message_type,+ "open_id": open_id,+ "chat_type": message.chat_type,+ }+ )+ except Exception as e:+ logger.warning(f"记录消息到本地存储失败: {e}")++ # 数字分身模式:走消息批次合并;否则直接处理+ _ts = int(getattr(message, "create_time", int(time.time() * 1000)))+ _meta = self._build_reply_metadata(+ message=message,+ sender_open_id=open_id,+ base_metadata=base_metadata,+ )+ if self.config.group_digital_avatar:+ await self._enqueue_message_batch(chat_id=message.chat_id,- message={- "message_id": message.message_id,- "content": content,- "timestamp": getattr(message, "create_time", int(time.time() * 1000)),- "msg_type": message.message_type,- "open_id": open_id,- "chat_type": message.chat_type,- }+ open_id=open_id or "",+ content=content,+ timestamp_ms=_ts,+ metadata=_meta,+ )+ else:+ await self._process_batched_message(+ chat_id=message.chat_id,+ open_id=open_id or "",+ merged_content=content,+ timestamp_ms=_ts,+ metadata=_meta,)- except Exception as e:- logger.warning(f"记录消息到本地存储失败: {e}")-- # 使用消息批次处理(支持数字分身功能)- await self._enqueue_message_batch(- chat_id=message.chat_id,- open_id=open_id or "",- content=content,- timestamp_ms=int(- getattr(message, "create_time", int(time.time() * 1000))- ),- metadata=self._build_reply_metadata(- message=message,- sender_open_id=open_id,- base_metadata=base_metadata,- ),- )except Exception as e:logger.error(f"处理飞书消息时发生异常: {e}")diff --git a/jiuwenclaw/channel/wecom_channel.py b/jiuwenclaw/channel/wecom_channel.pyindex 2871dea934..02f640dbf2 100644--- a/jiuwenclaw/channel/wecom_channel.py+++ b/jiuwenclaw/channel/wecom_channel.py@@ -849,19 +849,20 @@ class WecomChannel(BaseChannel):},)- try:- self._message_storage.add_message_to_memory(- chat_id=chatid,- message={- "message_id": req_id,- "content": content,- "timestamp": int(time.time() * 1000),- "user_id": sender_user_id,- "chat_type": chat_type,- }- )- except Exception as e:- logger.warning(f"[WecomChannel] 记录消息到本地存储失败: {e}")+ if self.config.group_digital_avatar:+ try:+ self._message_storage.add_message_to_memory(+ chat_id=chatid,+ message={+ "message_id": req_id,+ "content": content,+ "timestamp": int(time.time() * 1000),+ "user_id": sender_user_id,+ "chat_type": chat_type,+ }+ )+ except Exception as e:+ logger.warning(f"[WecomChannel] 记录消息到本地存储失败: {e}")_effective_streaming = self.config.enable_streamingif self.config.group_digital_avatar and chat_type == "group":_effective_streaming = False@@ -897,13 +898,24 @@ class WecomChannel(BaseChannel):else:await self._send_stream_placeholder(req_id_final)- await self._enqueue_message_batch(- chat_id=chatid,- user_id=sender_user_id,- content=content,- timestamp_ms=int(time.time() * 1000),- metadata=metadata,- )+ # 数字分身模式:走消息批次合并;否则直接处理+ _ts = int(time.time() * 1000)+ if self.config.group_digital_avatar:+ await self._enqueue_message_batch(+ chat_id=chatid,+ user_id=sender_user_id,+ content=content,+ timestamp_ms=_ts,+ metadata=metadata,+ )+ else:+ await self._process_batched_message(+ chat_id=chatid,+ user_id=sender_user_id,+ merged_content=content,+ timestamp_ms=_ts,+ metadata=metadata,+ )def _extract_chatid(self, msg: Message) -> str | None:"""从出站消息提取 chatid;私发模式优先使用 reply_wecom_user_id。"""@@ -1203,6 +1215,15 @@ class WecomChannel(BaseChannel):self._clear_group_progress_state(request_id)try:+ is_dm = str(meta.get("reply_scope") or "").strip().lower() == "dm"+ # 群聊数字分身回复到群聊时,@发送人+ if msg.group_digital_avatar and not is_dm:+ sender_user_id = str(+ meta.get("im_sender_user_id") or ""+ ).strip()+ if sender_user_id and not sender_user_id.startswith("bot"):+ content = f"<@{sender_user_id}>\n{content}"+body = {"msgtype": "markdown", "markdown": {"content": content}}await self._ws_client.send_message(chatid, body)@@ -1217,19 +1238,20 @@ class WecomChannel(BaseChannel):if group_chat_id and group_chat_id != chatid:asyncio.create_task(self._send_group_ack(meta, content))- try:- self._message_storage.add_message_to_memory(- chat_id=chatid,- message={- "message_id": f"bot_{int(time.time() * 1000)}_{msg.id}",- "content": content,- "timestamp": int(time.time() * 1000),- "user_id": f"bot_{self.config.bot_id}",- "chat_type": "bot_reply",- }- )- except Exception as e:- logger.warning(f"[WecomChannel] 记录机器人回复消息失败: {e}")+ if self.config.group_digital_avatar:+ try:+ self._message_storage.add_message_to_memory(+ chat_id=chatid,+ message={+ "message_id": f"bot_{int(time.time() * 1000)}_{msg.id}",+ "content": content,+ "timestamp": int(time.time() * 1000),+ "user_id": f"bot_{self.config.bot_id}",+ "chat_type": "bot_reply",+ }+ )+ except Exception as e:+ logger.warning(f"[WecomChannel] 记录机器人回复消息失败: {e}")except Exception as e:logger.error("WecomChannel 发送失败: %s", e)diff --git a/jiuwenclaw/gateway/im_pipeline/im_inbound.py b/jiuwenclaw/gateway/im_pipeline/im_inbound.pyindex f9c6606ea0..8e9b6f2de7 100644--- a/jiuwenclaw/gateway/im_pipeline/im_inbound.py+++ b/jiuwenclaw/gateway/im_pipeline/im_inbound.py@@ -430,6 +430,7 @@ class IMConversationProcessor:)if response and isinstance(response.content, str):return response.content.strip() or None+except Exception as exc:logger.warning("[IMConversationProcessor] 调用 LLM 改写失败,将回退原始消息: %s",@@ -484,6 +485,12 @@ class IMInboundPipeline:msg.params["query"] = result.rewritten_contentif "content" in msg.params:msg.params["content"] = result.rewritten_content++ # 将原始 query 存入 metadata,供 outbound pipeline 路由决策使用+ if original_query:+ merged = dict(msg.metadata or {})+ merged["avatar_original_query"] = original_query+ msg.metadata = merged# 补全 avatar 详情字段(avatar_mode 已在 channel 层源头注入)# 只在群聊模式下补全 avatar 详情字段diff --git a/jiuwenclaw/gateway/im_pipeline/im_outbound.py b/jiuwenclaw/gateway/im_pipeline/im_outbound.pyindex bbbcd00d28..1105afb014 100644--- a/jiuwenclaw/gateway/im_pipeline/im_outbound.py+++ b/jiuwenclaw/gateway/im_pipeline/im_outbound.py@@ -1,4 +1,4 @@- # Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved."""IMOutboundPipeline — 出站预处理管线:路由决策(群发 vs 私发)。@@ -224,15 +224,27 @@ class IMOutboundPipeline:return None, ""target_name = str(metadata.get("reply_target_name") or "").strip() or "目标用户"+ original_query = str(metadata.get("avatar_original_query") or "").strip()++ query_section = ""+ if original_query:+ query_section = f"群聊中的原始提问:\n{original_query[:300]}\n\n"+prompt = ("请判断下面这条{platform}机器人回复,是否应该私发给特定用户,而不是直接回到群里。\n\n""判断标准:\n""- 如果内容是在为该用户记录待办、设置提醒、安排日程、私下跟进、单独通知,输出 DM\n""- 如果内容是在公开回复群讨论、解释问题、同步信息、继续群聊协作,输出 CHAT\n""- 只输出 DM 或 CHAT,不要输出其他内容\n\n"+ "{query_section}""目标用户:{name}\n""机器人回复:\n{content}"- ).format(platform=platform_name, name=target_name, content=content[:500])+ ).format(+ platform=platform_name,+ query_section=query_section,+ name=target_name,+ content=content[:500],+ )logger.info("[IMOutboundPipeline] LLM 请求: model=%r target=%s content_len=%d prompt:\n%s",