Skip to content

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_Zhou51fde798874e
diff --git a/docs/en/Channels.md b/docs/en/Channels.md
index c3d2157ada..d7e95636db 100644
--- a/docs/en/Channels.md
+++ b/docs/en/Channels.md
@@ -221,10 +221,12 @@ permissions:
deny_guidance_message: "This tool is not authorized in digital avatar mode."
``````
-6. The Feishu robot needs to be granted the following permissions:
- im:message.group_msg - Retrieve all messages in the group (with sensitive permissions)
- contact:contact.base:readonly - Retrieve basic information of the contact list
- contact:user.base:readonly - Retrieve basic information of the user
+6\. The Feishu robot needs to be granted the following permissions:
+
+ - `im:message.group_msg` - Retrieve all messages in the group (with sensitive permissions)
+ - `contact:contact.base:readonly` - Retrieve basic information of the contact list
+ - `contact:user.base:readonly` - Retrieve basic information of the user
+ - `im:message.p2p_msg:readonly` - Retrieve private messages sent to the bot
### Fields
diff --git "a/docs/zh/\351\242\221\351\201\223.md" "b/docs/zh/\351\242\221\351\201\223.md"
index 9bcec7265c..81d3329d27 100644
--- "a/docs/zh/\351\242\221\351\201\223.md"
+++ "b/docs/zh/\351\242\221\351\201\223.md"
@@ -235,13 +235,15 @@ permissions:
write:
"*": "deny"
deny_guidance_message: "该工具未被授权在数字分身模式下使用。"
-
-6. 飞书机器人需要新增以下权限:
- im:message.group_msg - 获取群组中所有消息(敏感权限)
- contact:contact.base:readonly - 获取通讯录基本信息
- contact:user.base:readonly - 获取用户基本信息
``````
+6\. 飞书机器人需要新增以下权限:
+
+ - `im:message.group_msg` - 获取群组中所有消息(敏感权限)
+ - `contact:contact.base:readonly` - 获取通讯录基本信息
+ - `contact:user.base:readonly` - 获取用户基本信息
+ - `im:message.p2p_msg:readonly` - 获取用户发给机器人的单聊消息
+
### 配置项说明
| 配置项 | 说明 |
diff --git a/jiuwenclaw/agentserver/deep_agent/rails/avatar_rail.py b/jiuwenclaw/agentserver/deep_agent/rails/avatar_rail.py
index d282da766d..723a0693e9 100644
--- a/jiuwenclaw/agentserver/deep_agent/rails/avatar_rail.py
+++ b/jiuwenclaw/agentserver/deep_agent/rails/avatar_rail.py
@@ -124,6 +124,16 @@ class AvatarPromptRail(DeepAgentRail):
except Exception as e:
logger.debug("[AvatarRail] 加载 forbidden_memory 失败: %s", e)
+ if is_group_digital_avatar:
+ interaction_content = _build_interaction_prompt(language)
+ section = PromptSection(
+ name="interaction_guidance",
+ content={language: interaction_content},
+ priority=_AVATAR_PROMPT_PRIORITY + 4,
+ )
+ builder.add_section(section)
+ self._injected_sections.add("interaction_guidance")
+
async def before_tool_call(self, ctx: AgentCallbackContext) -> None:
"""拦截记忆工具调用。
@@ -282,3 +292,73 @@ def _build_memory_fully_disabled_prompt(language: str) -> str:
__all__ = [
"AvatarPromptRail",
]
+
+
+def _build_interaction_prompt(language: str) -> str:
+ if language == "cn":
+ return """## 多轮交互指引
+
+在以下情况,你必须通过追问来明确需求,不要自行假设或跳过:
+
+### 何时必须追问
+1. **缺少关键参数**:任务需要具体参数但用户未提供(如订会议室但没说楼层、时间)
+2. **需求模糊或宽泛**:用户请求范围太大或方向不明确,直接执行可能偏离意图(如"帮我写个报告""做个调研""整理一下")
+3. **存在多种理解**:请求可以有多种解读方式,不同理解会导致完全不同的执行结果
+4. **需要确认授权**:需要 principal(你代替的人)确认或授权才能执行
+
+### 群聊追问
+如果缺少的信息可以由群聊中的某位用户提供,在回复开头加上 `[群聊追问@用户名]`:
+- 例:`[群聊追问@张三] 请问需要预约哪个楼层的会议室?`
+- 系统会自动在群聊中 @张三 并追踪回复
+
+如果缺少的信息由发送请求的人自己补充即可,在回复开头加上 `[群聊追问]`(不带@):
+- 例:`[群聊追问] 请问会议主题是什么?`
+- 例:`[群聊追问] 你说的调研报告是关于哪个方向的?需要覆盖哪些内容?`
+- 系统会自动追踪发送者的回复
+
+### 私聊追问
+如果需要 principal(你代替的人)确认或授权,在回复开头加上 `[私聊追问]`:
+- 例:`[私聊追问] 张三要订会议室,你确认吗?`
+- 系统会自动私聊 principal 并在群聊中发送简短确认
+
+### 注意事项
+- 需求模糊时**必须追问**,不要自行猜测用户意图后直接执行,否则很可能白做
+- 追问时给出具体选项或方向提示,帮助用户快速回复(如"是A方向还是B方向?"而非"你要什么?")
+- 追问前缀必须放在回复的最开头
+- 收到追问的回答后,继续完成任务即可,不需要再加前缀
+- 收到追问回答后,只针对当前追问的任务继续处理,不要与之前的其他任务混淆
+- 如果群聊历史中存在多个不同的任务,务必根据追问上下文区分,只处理当前任务
+"""
+ return """## Multi-turn Interaction Guidance
+
+You MUST follow up to clarify requirements in these situations — do NOT assume or skip:
+
+### When You Must Follow Up
+1. **Missing key parameters**: The task requires specific parameters the user hasn't provided (e.g., booking a room without specifying floor or time)
+2. **Vague or broad requests**: The request is too broad or unclear — executing directly may miss the user's intent (e.g., "write a report", "do some research", "organize this")
+3. **Ambiguous interpretation**: The request could be understood in multiple ways, leading to very different outcomes
+4. **Need confirmation**: You need the principal (the person you represent) to confirm or authorize
+
+### Group Follow-up
+If the missing information can be provided by someone in the group chat, prefix your reply with `[群聊追问@Username]`:
+- Example: `[群聊追问@张三] Which floor meeting room do you need?`
+- The system will automatically @mention the user and track their reply
+
+If the sender can provide the missing information themselves, prefix your reply with `[群聊追问]` (without @):
+- Example: `[群聊追问] What is the meeting topic?`
+- Example: `[群聊追问] What direction should the research report cover? What topics should it include?`
+- The system will automatically track the sender's reply
+
+### DM Follow-up
+If you need the principal (the person you represent) to confirm or authorize, prefix your reply with `[私聊追问]`:
+- Example: `[私聊追问] 张三 wants to book a meeting room, do you confirm?`
+- The system will automatically DM the principal and send a brief acknowledgment in the group
+
+### Notes
+- When the request is vague, you **MUST follow up** — do NOT guess the user's intent and execute, or you'll likely waste effort
+- When following up, provide specific options or directional hints to help the user reply quickly (e.g., "Direction A or Direction B?" rather than "What do you want?")
+- The follow-up prefix must be at the very beginning of your reply
+- After receiving the answer, continue completing the task without any prefix
+- After receiving the answer, only process the current task from the follow-up, do not mix with previous tasks
+- If the group chat history contains multiple different tasks, distinguish them based on the follow-up context and only handle the current one
+"""
diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.py
index 0f1a088243..d0496e2b9b 100644
--- a/jiuwenclaw/agentserver/interface.py
+++ b/jiuwenclaw/agentserver/interface.py
@@ -76,24 +76,42 @@ _SKILL_ROUTES: dict[ReqMethod, str] = {
}
-def build_user_prompt(
- content: str, files: dict, channel: str,
- language: str, trusted_dirs: list[str] | None = None
- ) -> str:
+def build_user_prompt(content: str, files: dict, channel: str, language: str, *,
+ trusted_dirs: list[str] | None = None, metadata: dict[str, Any] | None = None) -> str:
"""Build user prompt for the agent."""
+ interaction_prefix = ""
+ if metadata:
+ interaction_ctx = str(metadata.get("interaction_context") or "").strip()
+ if interaction_ctx:
+ interaction_prefix = f"\n{interaction_ctx}\n\n"
+
if language == "zh":
prompt = "你收到一条消息:\n"
else:
prompt = "You receive a new message:\n"
+ msg_data: dict[str, Any] = {
+ "source": channel,
+ "preferred_response_language": language,
+ "content": content,
+ "type": "user input",
+ }
if channel in ["cron", "heartbeat"]:
- return prompt + json.dumps(
- {
- "source": "system",
- "preferred_response_language": language,
- "content": content,
- "type": channel,
- },
- ensure_ascii=False,
+ msg_data["source"] = "system"
+ msg_data["type"] = channel
+ if metadata:
+ chat_type = str(metadata.get("chat_type") or metadata.get("im_chat_type") or "").strip()
+ if chat_type:
+ msg_data["chat_type"] = chat_type
+ sender_name = str(metadata.get("sender_name") or "").strip()
+ if sender_name:
+ msg_data["sender"] = sender_name
+ if channel not in ["cron", "heartbeat"]:
+ msg_data["files_updated_by_user"] = json.dumps(files, ensure_ascii=False)
+ final_prompt = interaction_prefix + prompt + json.dumps(msg_data, ensure_ascii=False)
+ if interaction_prefix:
+ logger.info(
+ "[build_user_prompt][DEBUG] interaction_context 存在,最终 prompt=\n%s",
+ final_prompt,
)
now = datetime.now(timezone(timedelta(hours=8)))
@@ -109,7 +127,7 @@ def build_user_prompt(
}
if trusted_dirs:
user_message_context["trusted_dirs"] = json.dumps(trusted_dirs, ensure_ascii=False)
- return prompt + json.dumps(user_message_context, ensure_ascii=False)
+ return interaction_prefix + prompt + json.dumps(user_message_context, ensure_ascii=False)
class JiuWenClaw:
@@ -218,6 +236,11 @@ class JiuWenClaw:
for d in raw_trusted_dirs:
if isinstance(d, str) and d.strip():
trusted_dirs.append(d.strip())
+ if request.metadata and request.metadata.get("interaction_context"):
+ logger.info(
+ "[_build_inputs][DEBUG] request.params.query=\n%s",
+ query[:2000] if isinstance(query, str) else str(query)[:2000],
+ )
if isinstance(query, InteractiveInput):
final_query = query
@@ -232,6 +255,7 @@ class JiuWenClaw:
channel=channel,
language=language,
trusted_dirs=trusted_dirs,
+ metadata=request.metadata,
)
else:
final_query = build_user_prompt(
@@ -240,6 +264,7 @@ class JiuWenClaw:
channel=channel,
language=language,
trusted_dirs=trusted_dirs,
+ metadata=request.metadata,
)
inputs: dict[str, Any] = {
diff --git a/jiuwenclaw/channel/feishu.py b/jiuwenclaw/channel/feishu.py
index c3a89afb03..dd556d0a7d 100644
--- a/jiuwenclaw/channel/feishu.py
+++ b/jiuwenclaw/channel/feishu.py
@@ -229,7 +229,8 @@ class FeishuChannel(BaseChannel):
Args:
inbound: Feishu 入站消息
"""
- # Message 的 id 必须全局唯一;多 bot 同群时飞书消息 message_id 相同,需加上 channel_id 防止冲突。
+ from jiuwenclaw.gateway.interaction_context import PendingInteraction
+
msg_id = f"{self.channel_id}:{inbound.message_id}"
params = {"content": inbound.content, "query": inbound.content} if inbound.params is None else inbound.params
_meta = inbound.metadata or {}
@@ -244,6 +245,43 @@ class FeishuChannel(BaseChannel):
_meta["avatar_mode"] = True
_meta["principal_user_id"] = self._get_target_user_open_id()
_meta["triggering_user_id"] = str(inbound.user_id or "")
+
+ if not _is_group and self.config.group_digital_avatar:
+ sender_open_id = str(inbound.user_id or "").strip()
+ principal_id = self._get_target_user_open_id()
+ if sender_open_id and sender_open_id == principal_id:
+ pi = PendingInteraction.find_pending(self.channel_id, principal_id)
+ if pi is not None:
+ _meta = dict(_meta)
+ _meta["avatar_mode"] = True
+ _meta["is_resume_message"] = True
+ _meta["principal_user_id"] = principal_id
+ _meta["dm_pending_interaction_id"] = pi.interaction_id
+
+ resume_msg = Message(
+ id=f"{self.channel_id}:resume:{inbound.message_id}",
+ type="req",
+ channel_id=self.channel_id,
+ session_id=pi.origin_session_id,
+ params={"content": inbound.content or "", "query": inbound.content or ""},
+ timestamp=time.time(), ok=True,
+ provider=self.name,
+ chat_id=pi.origin_session_id,
+ user_id=principal_id,
+ bot_id=str(inbound.bot_id or self.config.app_id or ""),
+ req_method=ReqMethod.CHAT_SEND,
+ is_stream=False,
+ metadata=_meta,
+ group_digital_avatar=True,
+ enable_memory=self.config.enable_memory,
+ enable_streaming=False,
+ )
+ if self._message_callback:
+ self._message_callback(resume_msg)
+ else:
+ await self.bus.route_user_message(resume_msg)
+ return
+
_effective_group_digital_avatar = self.config.group_digital_avatar and _is_group
msg = Message(
id=msg_id,
@@ -652,7 +690,6 @@ class FeishuChannel(BaseChannel):
@staticmethod
def _should_send_group_ack(metadata: dict[str, Any]) -> bool:
"""仅在待办/提醒类私发场景下,才补发群内短确认。"""
- # 定时任务消息不发送群确认
if bool(metadata.get("is_cron_job")):
return False
if str(metadata.get("reply_scope") or "").strip().lower() != "dm":
@@ -666,6 +703,39 @@ class FeishuChannel(BaseChannel):
return False
return bool(metadata.get("reply_personal_action"))
+ @staticmethod
+ def _should_send_interaction_ack(metadata: dict[str, Any]) -> bool:
+ """追问场景下,群内补发简短确认。"""
+ if bool(metadata.get("is_cron_job")):
+ return False
+ has_interaction = bool(metadata.get("interaction_mention_user")) or bool(
+ metadata.get("interaction_question")
+ )
+ if not has_interaction:
+ return False
+ if not str(metadata.get("feishu_chat_id") or "").strip():
+ return False
+ return True
+
+ async def _send_interaction_ack(self, metadata: dict[str, Any], content: str) -> None:
+ """追问场景下在群内补发简短确认。"""
+ try:
+ group_chat_id = str(metadata.get("feishu_chat_id") or "").strip()
+ if not group_chat_id:
+ return
+
+ mention_name = str(metadata.get("interaction_mention_user") or "").strip()
+ if mention_name:
+ ack_text = f"已向 {mention_name} 追问,等回复后继续处理。"
+ else:
+ ack_text = "已私聊确认,等回复后继续处理。"
+
+ card = self._build_card_content(ack_text)
+ await self._send_feishu_message(group_chat_id, "chat_id", card, "interaction_ack")
+ logger.info("[FeishuChannel] 追问确认已发送: chat_id=%s", group_chat_id)
+ except Exception as e:
+ logger.warning("[FeishuChannel] 追问确认发送失败: %s", e)
+
@staticmethod
def _fallback_group_ack() -> str:
"""群内短回复兜底文案,保持第一人称口吻。"""
@@ -1419,19 +1489,24 @@ class FeishuChannel(BaseChannel):
# 群聊数字分身回复到群聊时,@发送人
if msg.group_digital_avatar and id_type == "chat_id":
+ mention_user_id = str(
+ meta.get("interaction_mention_user_id") or ""
+ ).strip()
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}"
+ at_user_id = mention_user_id or sender_open_id
+ if at_user_id and not at_user_id.startswith("bot"):
+ content_str = f"<at id={at_user_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)
- # 用LLM在群内补发简短回复
- if msg.group_digital_avatar and self._should_send_group_ack(meta):
+ if msg.group_digital_avatar and self._should_send_interaction_ack(meta):
+ asyncio.create_task(self._send_interaction_ack(meta, content_str))
+ elif msg.group_digital_avatar and self._should_send_group_ack(meta):
group_chat_id = str(meta.get("feishu_chat_id") or "").strip()
if group_chat_id and group_chat_id != receive_id:
asyncio.create_task(self._send_group_ack(meta, content_str))
diff --git a/jiuwenclaw/channel/platform_adapter/feishu_im_adapter.py b/jiuwenclaw/channel/platform_adapter/feishu_im_adapter.py
index e882ceea05..57b920a102 100644
--- a/jiuwenclaw/channel/platform_adapter/feishu_im_adapter.py
+++ b/jiuwenclaw/channel/platform_adapter/feishu_im_adapter.py
@@ -171,4 +171,28 @@ class FeishuIMPlatformAdapter:
@staticmethod
def get_candidate_user_id(metadata: dict[str, Any]) -> str:
- return str(metadata.get("reply_candidate_feishu_open_id") or "").strip()
\ No newline at end of file
+ return str(metadata.get("reply_candidate_feishu_open_id") or "").strip()
+
+ def resolve_user_id_by_name(self, name: str) -> str:
+ """根据用户名在群聊历史中查找对应的 open_id。"""
+ if not name or not self._api_client:
+ return ""
+ try:
+ from jiuwenclaw.utils import get_agent_workspace_dir
+ import json
+ from pathlib import Path
+
+ interactions_dir = Path.home() / ".jiuwenclaw" / "workspace" / "agent" / "interactions"
+ for fp in interactions_dir.glob("*.json"):
+ try:
+ data = json.loads(fp.read_text(encoding="utf-8"))
+ if data.get("target_user_name") == name:
+ uid = str(data.get("target_user_id") or "").strip()
+ if uid:
+ return uid
+ except Exception as e:
+ logger.debug("[FeishuIMAdapter] 解析交互文件 %s 失败: %s", fp, e)
+ continue
+ except Exception as e:
+ logger.warning("[FeishuIMAdapter] resolve_user_id_by_name 失败: %s", e)
+ return ""
\ No newline at end of file
diff --git a/jiuwenclaw/channel/platform_adapter/wecom_im_adapter.py b/jiuwenclaw/channel/platform_adapter/wecom_im_adapter.py
index c6500987e1..95331dc2ef 100644
--- a/jiuwenclaw/channel/platform_adapter/wecom_im_adapter.py
+++ b/jiuwenclaw/channel/platform_adapter/wecom_im_adapter.py
@@ -146,3 +146,27 @@ class WecomIMPlatformAdapter:
if candidate:
metadata.update(patch)
return candidate
+
+ @staticmethod
+ def resolve_user_id_by_name(name: str) -> str:
+ """根据用户名在群聊历史中查找对应的 user_id。"""
+ if not name:
+ return ""
+ try:
+ import json
+ from pathlib import Path
+
+ interactions_dir = Path.home() / ".jiuwenclaw" / "workspace" / "agent" / "interactions"
+ for fp in interactions_dir.glob("*.json"):
+ try:
+ data = json.loads(fp.read_text(encoding="utf-8"))
+ if data.get("target_user_name") == name:
+ uid = str(data.get("target_user_id") or "").strip()
+ if uid:
+ return uid
+ except Exception as e:
+ logger.debug("[WecomIMAdapter] 解析交互文件 %s 失败: %s", fp, e)
+ continue
+ except Exception as e:
+ logger.warning("[WecomIMAdapter] resolve_user_id_by_name 失败: %s", e)
+ return ""
diff --git a/jiuwenclaw/channel/wecom_channel.py b/jiuwenclaw/channel/wecom_channel.py
index f653966488..6e11e1fb0e 100644
--- a/jiuwenclaw/channel/wecom_channel.py
+++ b/jiuwenclaw/channel/wecom_channel.py
@@ -204,7 +204,6 @@ class WecomChannel(BaseChannel):
@staticmethod
def _should_send_group_ack(metadata: dict[str, Any]) -> bool:
"""仅在待办/提醒类私发场景下,才补发群内短确认。"""
- # 定时任务消息不发送群确认
if bool(metadata.get("is_cron_job")):
return False
@@ -214,8 +213,8 @@ class WecomChannel(BaseChannel):
reply_personal_action = bool(metadata.get("reply_personal_action"))
logger.info(
- "[WecomChannel] _should_send_group_ack: reply_scope=%s \
- reply_reason=%s wecom_chat_id=%s reply_personal_action=%s",
+ "[WecomChannel] _should_send_group_ack: reply_scope=%s "
+ "reply_reason=%s wecom_chat_id=%s reply_personal_action=%s",
reply_scope, reply_reason, wecom_chat_id, reply_personal_action
)
@@ -238,6 +237,39 @@ class WecomChannel(BaseChannel):
logger.info("[WecomChannel] _should_send_group_ack: 返回True")
return True
+ @staticmethod
+ def _should_send_interaction_ack(metadata: dict[str, Any]) -> bool:
+ """追问场景下,群内补发简短确认。"""
+ if bool(metadata.get("is_cron_job")):
+ return False
+ has_interaction = bool(metadata.get("interaction_mention_user")) or bool(
+ metadata.get("interaction_question")
+ )
+ if not has_interaction:
+ return False
+ if not str(metadata.get("wecom_chat_id") or "").strip():
+ return False
+ return True
+
+ async def _send_interaction_ack(self, metadata: dict[str, Any]) -> None:
+ """追问场景下在群内补发简短确认。"""
+ try:
+ group_chat_id = str(metadata.get("wecom_chat_id") or "").strip()
+ if not group_chat_id or not self._ws_client:
+ return
+
+ mention_name = str(metadata.get("interaction_mention_user") or "").strip()
+ if mention_name:
+ ack_text = f"已向 {mention_name} 追问,等回复后继续处理。"
+ else:
+ ack_text = "已私聊确认,等回复后继续处理。"
+
+ body = {"msgtype": "markdown", "markdown": {"content": ack_text}}
+ await self._ws_client.send_message(group_chat_id, body)
+ logger.info("[WecomChannel] 追问确认已发送: chat_id=%s", group_chat_id)
+ except Exception as e:
+ logger.warning("[WecomChannel] 追问确认发送失败: %s", e)
+
@staticmethod
def _fallback_group_ack() -> str:
"""群内短回复兜底文案。"""
@@ -742,6 +774,8 @@ class WecomChannel(BaseChannel):
metadata: dict[str, Any],
) -> None:
"""内部消息处理入口。"""
+ from jiuwenclaw.gateway.interaction_context import PendingInteraction
+
chat_type = metadata.get("chat_type", "")
is_group_chat = chat_type == "group"
msg_enable_streaming = self.config.enable_streaming
@@ -749,12 +783,43 @@ class WecomChannel(BaseChannel):
if self.config.group_digital_avatar and is_group_chat:
msg_enable_streaming = False
is_stream = False
- # 源头注入基础 avatar 标记,即使 inbound pipeline 异常 Agent 也能感知数字分身场景
metadata = dict(metadata)
metadata["avatar_mode"] = True
- # 权限方案:统一注入 principal/triggering
metadata["principal_user_id"] = self._get_target_user_id()
metadata["triggering_user_id"] = user_id
+
+ if not is_group_chat and self.config.group_digital_avatar:
+ principal_id = self._get_target_user_id()
+ if user_id and user_id == principal_id:
+ pi = PendingInteraction.find_pending(self.name, principal_id)
+ if pi is not None:
+ metadata = dict(metadata)
+ metadata["avatar_mode"] = True
+ metadata["is_resume_message"] = True
+ metadata["principal_user_id"] = principal_id
+ metadata["dm_pending_interaction_id"] = pi.interaction_id
+
+ resume_msg = Message(
+ id=f"{self.name}:resume:{int(time.time() * 1000)}",
+ type="req",
+ channel_id=self.name,
+ session_id=pi.origin_session_id,
+ params={"content": content, "query": content},
+ timestamp=time.time(),
+ ok=True,
+ req_method=ReqMethod.CHAT_SEND,
+ is_stream=False,
+ metadata=metadata,
+ group_digital_avatar=True,
+ enable_memory=self.config.enable_memory,
+ enable_streaming=False,
+ )
+ if self._message_callback:
+ self._message_callback(resume_msg)
+ else:
+ await self.bus.route_user_message(resume_msg)
+ return
+
effective_group_digital_avatar = self.config.group_digital_avatar and is_group_chat
msg = Message(
id=metadata.get("message_id") or f"wecom_{int(time.time() * 1000)}",
@@ -1217,13 +1282,16 @@ class WecomChannel(BaseChannel):
try:
is_dm = str(meta.get("reply_scope") or "").strip().lower() == "dm"
- # 群聊数字分身回复到群聊时,@发送人
if msg.group_digital_avatar and not is_dm:
+ mention_user_id = str(
+ meta.get("interaction_mention_user_id") or ""
+ ).strip()
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}"
+ at_user_id = mention_user_id or sender_user_id
+ if at_user_id and not at_user_id.startswith("bot"):
+ content = f"<@{at_user_id}>\n{content}"
body = {"msgtype": "markdown", "markdown": {"content": content}}
await self._ws_client.send_message(chatid, body)
@@ -1234,7 +1302,9 @@ class WecomChannel(BaseChannel):
else:
logger.info("[WecomChannel] 发送消息: chatid=%s len=%d", chatid, len(content))
- if msg.group_digital_avatar and self._should_send_group_ack(meta):
+ if msg.group_digital_avatar and self._should_send_interaction_ack(meta):
+ asyncio.create_task(self._send_interaction_ack(meta))
+ elif msg.group_digital_avatar and self._should_send_group_ack(meta):
group_chat_id = str(meta.get("wecom_chat_id") or "").strip()
if group_chat_id and group_chat_id != chatid:
asyncio.create_task(self._send_group_ack(meta, content))
diff --git a/jiuwenclaw/gateway/im_pipeline/im_inbound.py b/jiuwenclaw/gateway/im_pipeline/im_inbound.py
index 3a0a8c78d8..3d72ad75c1 100644
--- a/jiuwenclaw/gateway/im_pipeline/im_inbound.py
+++ b/jiuwenclaw/gateway/im_pipeline/im_inbound.py
@@ -14,6 +14,7 @@ from openjiuwen.core.foundation.llm import Model
from openjiuwen.core.foundation.llm.schema.config import ModelClientConfig, ModelRequestConfig
from jiuwenclaw.config import _parse_custom_headers
+from jiuwenclaw.gateway.interaction_context import PendingInteraction
from jiuwenclaw.schema.message import Message, ReqMethod
from jiuwenclaw.gateway.slash_command import CONTROL_MESSAGE_TEXTS
from jiuwenclaw.utils import get_root_dir, logger
@@ -171,6 +172,8 @@ class IMConversationProcessor:
self,
msg: Message,
adapter: IMPlatformAdapter,
+ *,
+ pending_context: str | None = None,
) -> InboundProcessResult:
if msg.req_method != ReqMethod.CHAT_SEND:
return InboundProcessResult(reason="non-chat-send")
@@ -230,6 +233,7 @@ class IMConversationProcessor:
timestamp_ms=self._resolve_timestamp_ms(msg.timestamp, metadata),
principal_name=principal_name,
adapter=adapter,
+ pending_context=pending_context,
)
rewritten_content = await self._rewrite_query(prompt, principal_name, adapter)
if not rewritten_content:
@@ -329,6 +333,7 @@ class IMConversationProcessor:
timestamp_ms: int,
principal_name: str,
adapter: IMPlatformAdapter,
+ pending_context: str | None = None,
) -> str:
prompt_parts: list[str] = []
prompt_parts.append("=== 群聊历史消息 ===")
@@ -350,6 +355,11 @@ class IMConversationProcessor:
prompt_parts.append(user_profile if user_profile else "暂无用户画像信息")
prompt_parts.append("")
+ if pending_context:
+ prompt_parts.append("=== 待回答的追问 ===")
+ prompt_parts.append(pending_context)
+ prompt_parts.append("")
+
prompt_parts.append("=== 当前消息 ===")
sender_name = adapter.resolve_user_display_name(sender_user_id) or "未知用户"
dt = datetime.fromtimestamp(int(timestamp_ms) / 1000)
@@ -465,6 +475,44 @@ class IMInboundPipeline:
if adapter is None:
return True
+ metadata = dict(msg.metadata or {})
+ if bool(metadata.get("is_resume_message")):
+ dm_pending_id = str(metadata.get("dm_pending_interaction_id") or "").strip()
+ if dm_pending_id:
+ pi = PendingInteraction.load(dm_pending_id)
+ if pi is not None:
+ answer = ""
+ if isinstance(msg.params, dict):
+ answer = str(
+ msg.params.get("query") or msg.params.get("content") or ""
+ ).strip()
+ resume_content = pi.build_resume_content(answer)
+ logger.info(
+ "[IMInboundPipeline][DEBUG] dm_resume: id=%s answer=%s",
+ dm_pending_id,
+ answer[:80],
+ )
+ logger.info(
+ "[IMInboundPipeline][DEBUG] resume_content=\n%s",
+ resume_content,
+ )
+ if not isinstance(msg.params, dict):
+ msg.params = {}
+ msg.params["query"] = resume_content
+ if "content" in msg.params:
+ msg.params["content"] = resume_content
+ merged = dict(msg.metadata or {})
+ merged["interaction_context"] = resume_content
+ msg.metadata = merged
+ pi.status = "completed"
+ pi.save()
+ pi.remove()
+ logger.info(
+ "[IMInboundPipeline] resume 消息直接放行: channel=%s id=%s",
+ msg.channel_id, msg.id,
+ )
+ return True
+
original_query = ""
if isinstance(msg.params, dict):
query = msg.params.get("query")
@@ -474,7 +522,14 @@ class IMInboundPipeline:
elif isinstance(content, str):
original_query = content
- result = await self._processor.process(msg, adapter)
+ pending_context = self._peek_pending(msg)
+ if pending_context:
+ logger.info(
+ "[IMInboundPipeline][DEBUG] pending_context=\n%s",
+ pending_context,
+ )
+
+ result = await self._processor.process(msg, adapter, pending_context=pending_context)
if result.metadata_patch:
merged_metadata = dict(msg.metadata or {})
@@ -487,15 +542,45 @@ class IMInboundPipeline:
msg.params["query"] = result.rewritten_content
if "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 详情字段
+ if pending_context and result.should_forward:
+ merged = dict(msg.metadata or {})
+ merged["interaction_context"] = pending_context
+ sender_user_id = str(
+ metadata.get("im_sender_user_id")
+ or metadata.get("open_id")
+ or metadata.get("sender_id")
+ or ""
+ ).strip()
+ if sender_user_id:
+ merged["interaction_answered_user_id"] = sender_user_id
+ msg.metadata = merged
+
+ session_id = str(msg.session_id or "").strip()
+ if session_id and sender_user_id:
+ pi = PendingInteraction.find_group_pending(session_id, sender_user_id)
+ logger.info(
+ "[IMInboundPipeline][DEBUG] find_group_pending=%s",
+ pi,
+ )
+ if pi is not None:
+ answer = result.rewritten_content or original_query
+ resume_content = pi.build_resume_content(answer)
+ logger.info(
+ "[IMInboundPipeline][DEBUG] resume_content=\n%s",
+ resume_content,
+ )
+ if not isinstance(msg.params, dict):
+ msg.params = {}
+ msg.params["query"] = resume_content
+ if "content" in msg.params:
+ msg.params["content"] = resume_content
+
if result.should_forward and result.reason != "non-group-chat":
principal_name = adapter.get_principal_display_name().strip()
avatar_detail: dict[str, Any] = {
@@ -506,7 +591,6 @@ class IMInboundPipeline:
avatar_detail["avatar_principal_name"] = principal_name
principal_id = adapter.get_principal_user_id().strip()
if principal_id:
- # 统一用 principal_user_id,供权限方案和 prompt 方案共享
avatar_detail["principal_user_id"] = principal_id
merged = dict(msg.metadata or {})
merged.update(avatar_detail)
@@ -518,7 +602,7 @@ class IMInboundPipeline:
logger.info(
"[IMInboundPipeline] channel=%s request=%s should_forward=%s reason=%s rewritten=%s "
- "original_preview=%r rewritten_preview=%r metadata_keys=%s",
+ "original_preview=%r rewritten_preview=%r metadata_keys=%s pending=%s",
msg.channel_id,
msg.id,
result.should_forward,
@@ -527,5 +611,30 @@ class IMInboundPipeline:
original_preview,
rewritten_preview,
metadata_keys,
+ bool(pending_context),
)
- return result.should_forward
\ No newline at end of file
+ return result.should_forward
+
+ @staticmethod
+ def _peek_pending(msg: Message) -> str | None:
+ metadata = dict(msg.metadata or {})
+ session_id = str(msg.session_id or "").strip()
+ sender_user_id = str(
+ metadata.get("im_sender_user_id")
+ or metadata.get("open_id")
+ or metadata.get("sender_id")
+ or ""
+ ).strip()
+ if not session_id or not sender_user_id:
+ return None
+ pi = PendingInteraction.find_group_pending(session_id, sender_user_id)
+ if pi is None:
+ return None
+ return (
+ f"【追问上下文】你之前在处理以下任务时向 {pi.target_user_name or '用户'} 追问了信息:\n"
+ f"- 原始请求:{pi.origin_content}\n"
+ f"- 你的追问:{pi.question}\n"
+ f"现在 {pi.target_user_name or '用户'} 已回复,请综合「原始请求」和「用户回复」中的所有信息继续完成任务,"
+ f"原始请求中已明确提供的信息(如时间、地点等)直接使用即可,不要再次追问。"
+ f"不要与群聊历史中的其他任务混淆。"
+ )
\ No newline at end of file
diff --git a/jiuwenclaw/gateway/im_pipeline/im_outbound.py b/jiuwenclaw/gateway/im_pipeline/im_outbound.py
index f4304d5160..f27352be1e 100644
--- a/jiuwenclaw/gateway/im_pipeline/im_outbound.py
+++ b/jiuwenclaw/gateway/im_pipeline/im_outbound.py
@@ -1,9 +1,13 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
-"""IMOutboundPipeline — 出站预处理管线:路由决策(群发 vs 私发)。
+"""IMOutboundPipeline — 出站预处理管线:路由决策(群发 vs 私发)+ 追问前缀解析。
在 MessageHandler.publish_robot_messages() 入队前拦截,根据 LLM 分类和关键词匹配
决定是否将回复私发给目标用户。Channel.send() 仅读取 metadata 执行实际发送。
+
+追问前缀约定:
+ [群聊追问@张三] → 群聊中 @张三 追问
+ [私聊追问] → 私聊 principal 追问
"""
from __future__ import annotations
@@ -11,9 +15,11 @@ from __future__ import annotations
import logging
import os
import re
+import secrets
from typing import TYPE_CHECKING, Any
from jiuwenclaw.config import _parse_custom_headers
+from jiuwenclaw.gateway.interaction_context import PendingInteraction
if TYPE_CHECKING:
from jiuwenclaw.gateway.im_pipeline.im_inbound import IMPlatformAdapter
@@ -40,6 +46,9 @@ _GROUP_ACK_KEYWORDS: tuple[str, ...] = (
"记住了",
)
+_RE_GROUP_FOLLOWUP = re.compile(r"^\[群聊追问(?:@(.+?))?\]\s*")
+_RE_DM_FOLLOWUP = re.compile(r"^\[私聊追问\]\s*")
+
class IMOutboundPipeline:
"""出站预处理管线:根据回复内容决定是否私发给目标用户。"""
@@ -123,24 +132,16 @@ class IMOutboundPipeline:
msg.channel_id, msg.id, msg.group_digital_avatar
)
- # 检查是否需要数字分身路由决策
- # 优先使用 msg.group_digital_avatar,其次检查 metadata 中的 avatar_mode
meta = dict(msg.metadata or {})
is_digital_avatar = msg.group_digital_avatar or bool(meta.get("avatar_mode"))
if not is_digital_avatar:
return
- # 幂等:已经有 reply_scope 则跳过
- if str(meta.get("reply_scope") or "").strip():
- return
-
- # 跳过不需要路由决策的中间事件
payload = msg.payload if isinstance(msg.payload, dict) else {}
event_type = str(payload.get("event_type") or "")
if event_type in _SKIP_EVENT_TYPES:
return
- # 仅群聊需要路由决策
chat_type = str(meta.get("chat_type") or "").strip()
if chat_type != "group":
return
@@ -149,20 +150,48 @@ class IMOutboundPipeline:
if adapter is None:
return
- candidate_user_id = adapter.get_candidate_user_id(meta)
- if not candidate_user_id:
- return
-
content = self._extract_content(msg)
if not content:
return
+ # ---- 群聊追问的 pending 清除逻辑(必须在追问前缀解析之前) ----
+ answered_user_id = str(meta.get("interaction_answered_user_id") or "").strip()
+ if answered_user_id:
+ session_id = str(msg.session_id or "").strip()
+ if session_id:
+ existing = PendingInteraction.find_group_pending(session_id, answered_user_id)
+ if existing:
+ existing.remove()
+ logger.info(
+ "[IMOutboundPipeline] clear_pending: session=%s user=%s",
+ session_id, answered_user_id,
+ )
+
+ # ---- 追问前缀解析(优先于原有路由逻辑) ----
+ group_match = _RE_GROUP_FOLLOWUP.match(content)
+ dm_match = _RE_DM_FOLLOWUP.match(content)
+
+ if group_match:
+ await self._handle_group_followup(msg, meta, adapter, content, group_match)
+ return
+
+ if dm_match:
+ await self._handle_dm_followup(msg, meta, adapter, content)
+ return
+
+ # ---- 原有路由逻辑 ----
+ if str(meta.get("reply_scope") or "").strip():
+ return
+
+ candidate_user_id = adapter.get_candidate_user_id(meta)
+ if not candidate_user_id:
+ return
+
logger.info(
"[IMOutboundPipeline] 继续处理: channel=%s candidate=%s content_len=%d",
msg.channel_id, candidate_user_id, len(content)
)
- # 先进行关键词判断,只有包含个人行动关键词时才需要进一步判断
keyword_hit = _is_personal_action_reply(content)
is_personal, llm_raw = await self._classify_personal_action(
@@ -205,12 +234,146 @@ class IMOutboundPipeline:
msg.channel_id, msg.id, adapter.reply_user_id_key,
)
+ # ---- 追问处理 ----
+
+ async def _handle_group_followup(
+ self,
+ msg: "Message",
+ meta: dict[str, Any],
+ adapter: "IMPlatformAdapter",
+ content: str,
+ match: re.Match,
+ ) -> None:
+ target_name = (match.group(1) or "").strip()
+ stripped = _RE_GROUP_FOLLOWUP.sub("", content).strip()
+
+ target_user_id = ""
+ if target_name and hasattr(adapter, "resolve_user_id_by_name"):
+ target_user_id = adapter.resolve_user_id_by_name(target_name)
+
+ if not target_user_id:
+ sender_user_id = str(
+ meta.get("im_sender_user_id")
+ or meta.get("open_id")
+ or meta.get("sender_id")
+ or ""
+ ).strip()
+ if sender_user_id:
+ target_user_id = sender_user_id
+ if not target_name and hasattr(adapter, "resolve_user_display_name"):
+ target_name = adapter.resolve_user_display_name(sender_user_id)
+ else:
+ candidate_user_id = adapter.get_candidate_user_id(meta)
+ if candidate_user_id:
+ target_user_id = candidate_user_id
+ if not target_name:
+ target_name = str(meta.get("reply_target_name") or "").strip()
+
+ meta["interaction_mention_user"] = target_name
+ meta["interaction_mention_user_id"] = target_user_id
+ meta["interaction_question"] = True
+
+ payload = msg.payload if isinstance(msg.payload, dict) else {}
+ payload["content"] = content
+ msg.payload = payload
+
+ session_id = str(msg.session_id or "").strip()
+ origin_content = str(meta.get("avatar_original_query") or "").strip()
+ origin_sender_id = str(
+ meta.get("im_sender_user_id")
+ or meta.get("open_id")
+ or meta.get("sender_id")
+ or ""
+ ).strip()
+ origin_sender_name = target_name
+
+ pi = PendingInteraction(
+ interaction_id=f"gpq_{session_id}_{target_user_id}",
+ mode="group",
+ origin_channel_id=msg.channel_id,
+ origin_session_id=session_id,
+ origin_content=origin_content,
+ origin_sender_name=origin_sender_name,
+ origin_sender_id=origin_sender_id,
+ question=stripped,
+ target_user_id=target_user_id,
+ target_user_name=target_name,
+ origin_metadata=dict(meta),
+ )
+ pi.save()
+
+ msg.metadata = meta
+ logger.info(
+ "[IMOutboundPipeline] 群聊追问: session=%s target=%s(%s) question=%s",
+ session_id, target_name, target_user_id, stripped[:80],
+ )
+
+ async def _handle_dm_followup(
+ self,
+ msg: "Message",
+ meta: dict[str, Any],
+ adapter: "IMPlatformAdapter",
+ content: str,
+ ) -> None:
+ stripped = _RE_DM_FOLLOWUP.sub("", content).strip()
+
+ meta["reply_scope"] = "dm"
+ meta["interaction_question"] = True
+
+ candidate_user_id = adapter.get_candidate_user_id(meta)
+ if candidate_user_id:
+ meta[adapter.reply_user_id_key] = candidate_user_id
+
+ payload = msg.payload if isinstance(msg.payload, dict) else {}
+ payload["content"] = content
+ msg.payload = payload
+
+ session_id = str(msg.session_id or "").strip()
+ origin_content = str(meta.get("avatar_original_query") or "").strip()
+ origin_sender_name = str(meta.get("reply_target_name") or "").strip()
+ origin_sender_id = str(
+ meta.get("im_sender_user_id")
+ or meta.get("open_id")
+ or meta.get("sender_id")
+ or ""
+ ).strip()
+ target_user_id = candidate_user_id or ""
+
+ hex_suffix = secrets.token_hex(4)
+ pi = PendingInteraction(
+ interaction_id=f"iact_{msg.channel_id}_{hex_suffix}",
+ mode="dm",
+ origin_channel_id=msg.channel_id,
+ origin_session_id=session_id,
+ origin_content=origin_content,
+ origin_sender_name=origin_sender_name,
+ origin_sender_id=origin_sender_id,
+ question=stripped,
+ target_user_id=target_user_id,
+ origin_metadata=dict(meta),
+ )
+ pi.save()
+
+ msg.metadata = meta
+ logger.info(
+ "[IMOutboundPipeline] DM 追问: session=%s target=%s question=%s",
+ session_id, target_user_id, stripped[:80],
+ )
+
# ---- helpers ----
@staticmethod
def _extract_content(msg: "Message") -> str:
payload = msg.payload if isinstance(msg.payload, dict) else {}
- return str(payload.get("content") or "").strip()
+ content = payload.get("content")
+ if isinstance(content, str):
+ return content.strip()
+ if isinstance(content, dict):
+ for key in ("output", "text", "message"):
+ val = content.get(key)
+ if isinstance(val, str) and val.strip():
+ return val.strip()
+ return str(content or "").strip()
async def _classify_personal_action(
self,
diff --git a/jiuwenclaw/gateway/interaction_context.py b/jiuwenclaw/gateway/interaction_context.py
new file mode 100644
index 0000000000..a2de678304
--- /dev/null
+++ b/jiuwenclaw/gateway/interaction_context.py
@@ -0,0 +1,189 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""PendingInteraction — 统一的追问上下文,支持群聊追问和 DM 追问两种模式。
+
+存储路径: ~/.jiuwenclaw/workspace/agent/interactions/{interaction_id}.json
+文件名前缀: gpq_* 群聊追问, iact_* DM 追问
+TTL: 24 小时
+"""
+
+from __future__ import annotations
+
+import glob
+import json
+import logging
+import os
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+_SENSITIVE_KEYS = frozenset({"api_key", "token", "authorization"})
+_DEFAULT_TTL = 86400
+
+
+def _get_interactions_dir() -> Path:
+ home = os.path.expanduser("~/.jiuwenclaw")
+ d = Path(home) / "workspace" / "agent" / "interactions"
+ d.mkdir(parents=True, exist_ok=True)
+ return d
+
+
+def _filter_sensitive(metadata: dict[str, Any]) -> dict[str, Any]:
+ return {k: v for k, v in metadata.items() if k.lower() not in _SENSITIVE_KEYS}
+
+
+@dataclass
+class PendingInteraction:
+ interaction_id: str
+ mode: str
+ origin_channel_id: str
+ origin_session_id: str
+ origin_content: str
+ origin_sender_name: str
+ origin_sender_id: str
+ question: str
+ target_user_id: str
+ target_user_name: str = ""
+ origin_metadata: dict[str, Any] = field(default_factory=dict)
+ principal_id: str = ""
+ status: str = "pending"
+ created_at: float = field(default_factory=time.time)
+ updated_at: float = field(default_factory=time.time)
+
+ def _path(self) -> Path:
+ return _get_interactions_dir() / f"{self.interaction_id}.json"
+
+ def save(self) -> None:
+ self.updated_at = time.time()
+ data = {
+ "interaction_id": self.interaction_id,
+ "mode": self.mode,
+ "origin_channel_id": self.origin_channel_id,
+ "origin_session_id": self.origin_session_id,
+ "origin_content": self.origin_content,
+ "origin_sender_name": self.origin_sender_name,
+ "origin_sender_id": self.origin_sender_id,
+ "question": self.question,
+ "target_user_id": self.target_user_id,
+ "target_user_name": self.target_user_name,
+ "origin_metadata": _filter_sensitive(self.origin_metadata),
+ "principal_id": self.principal_id,
+ "status": self.status,
+ "created_at": self.created_at,
+ "updated_at": self.updated_at,
+ }
+ try:
+ self._path().write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
+ logger.info("[PendingInteraction] save: id=%s mode=%s", self.interaction_id, self.mode)
+ except Exception as exc:
+ logger.warning("[PendingInteraction] save 失败: %s", exc)
+
+ def remove(self) -> None:
+ try:
+ p = self._path()
+ if p.exists():
+ p.unlink()
+ logger.info("[PendingInteraction] remove: id=%s", self.interaction_id)
+ except Exception as exc:
+ logger.warning("[PendingInteraction] remove 失败: %s", exc)
+
+ @classmethod
+ def load(cls, interaction_id: str) -> "PendingInteraction | None":
+ p = _get_interactions_dir() / f"{interaction_id}.json"
+ if not p.exists():
+ return None
+ try:
+ data = json.loads(p.read_text(encoding="utf-8"))
+ return cls(**{k: data[k] for k in data if k in cls.__dataclass_fields__})
+ except Exception as exc:
+ logger.warning("[PendingInteraction] load 失败: id=%s %s", interaction_id, exc)
+ return None
+
+ @classmethod
+ def find_pending(cls, channel_id: str, principal_id: str) -> "PendingInteraction | None":
+ d = _get_interactions_dir()
+ oldest: "PendingInteraction | None" = None
+ for prefix in (f"iact_{channel_id}_", "gpq_"):
+ pattern = str(d / f"{prefix}*.json")
+ for fp in glob.glob(pattern):
+ try:
+ data = json.loads(Path(fp).read_text(encoding="utf-8"))
+ pi = cls(**{k: data[k] for k in data if k in cls.__dataclass_fields__})
+ if pi.status != "pending":
+ continue
+ if time.time() - pi.created_at > _DEFAULT_TTL:
+ pi.remove()
+ continue
+ if pi.principal_id and pi.principal_id != principal_id:
+ continue
+ if pi.target_user_id and pi.target_user_id != principal_id:
+ continue
+ if oldest is None or pi.created_at < oldest.created_at:
+ oldest = pi
+ except Exception as e:
+ logger.debug("[PendingInteraction] 解析交互文件 %s 失败: %s", fp, e)
+ continue
+ cls.cleanup_expired()
+ return oldest
+
+ @classmethod
+ def find_all_group_pending(cls) -> list["PendingInteraction"]:
+ d = _get_interactions_dir()
+ pattern = str(d / "gpq_*.json")
+ result: list[PendingInteraction] = []
+ for fp in glob.glob(pattern):
+ try:
+ data = json.loads(Path(fp).read_text(encoding="utf-8"))
+ pi = cls(**{k: data[k] for k in data if k in cls.__dataclass_fields__})
+ if pi.status == "pending" and time.time() - pi.created_at <= _DEFAULT_TTL:
+ result.append(pi)
+ except Exception as e:
+ logger.debug("[PendingInteraction] 解析交互文件 %s 失败: %s", fp, e)
+ continue
+ return result
+
+ @classmethod
+ def find_group_pending(cls, session_id: str, user_id: str) -> "PendingInteraction | None":
+ interaction_id = f"gpq_{session_id}_{user_id}"
+ return cls.load(interaction_id)
+
+ @classmethod
+ def cleanup_expired(cls, ttl: int = _DEFAULT_TTL) -> int:
+ d = _get_interactions_dir()
+ count = 0
+ now = time.time()
+ for fp in glob.glob(str(d / "*.json")):
+ try:
+ data = json.loads(Path(fp).read_text(encoding="utf-8"))
+ created = float(data.get("created_at", 0))
+ if now - created > ttl:
+ Path(fp).unlink()
+ count += 1
+ except Exception as e:
+ logger.debug("[PendingInteraction] 清理交互文件 %s 失败: %s", fp, e)
+ continue
+ if count:
+ logger.info("[PendingInteraction] cleanup_expired: removed %d files", count)
+ return count
+
+ def build_resume_content(self, answer: str) -> str:
+ if self.mode == "dm":
+ return (
+ f"[任务恢复] 之前的群聊请求:{self.origin_content}(来自 {self.origin_sender_name})\n"
+ f"你之前的追问:{self.question}\n"
+ f"principal 的回答:{answer}\n"
+ f"请综合「原始请求」和「principal 的回答」中的所有信息继续完成任务,"
+ f"原始请求中已明确提供的信息直接使用即可,不要再次追问。"
+ f"并将结果回复到群聊。"
+ )
+ return (
+ f"[任务恢复] 你正在处理的群聊请求:{self.origin_content}(来自 {self.origin_sender_name})\n"
+ f"你之前追问了 {self.target_user_name or '用户'}:{self.question}\n"
+ f"{self.target_user_name or '用户'} 的回答:{answer}\n"
+ f"请综合「原始请求」和「用户的回答」中的所有信息来完成任务。"
+ f"原始请求中已明确提供的信息(如时间、地点等)直接使用即可,不要再次追问或要求补充。"
+ f"现在请立即执行任务(如设置提醒、创建日程等),不要只是确认或记录信息,并将执行结果回复到群聊。"
+ )