message_gate.py 15.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
"""MessageGate 服务 - API 层和 AgentHub 之间的意图门控层。

详见设计文档: docs/superpowers/specs/2026-06-01-message-gate-design.md
"""
from __future__ import annotations

import asyncio
import logging
import re
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional

from app.config.loader import ConfigLoader
from app.hooks.post_reply import PostReplyHook
from app.service.active_session_service import ActiveSessionService

logger = logging.getLogger(__name__)


@dataclass
class GateDecision:
    """MessageGate 评估后输出的决策结果。"""
    intent: str  # chat | pass


BUSY_REPLY = "你的消息我记下了!手上还有件事没处理完,稍等片刻就来聊~"


class MessageGate:
    """消息门控层 - 等待/分类/重写/调度。"""

    def __init__(
        self,
        config_loader: ConfigLoader,
        session_service: ActiveSessionService,
        post_reply_hook: PostReplyHook,
        agent_hub: Any,  # AgentHub 实例,避免循环 import
        main_agent_key: str,
        model: Any = None,
    ) -> None:
        self.config_loader = config_loader
        self.session_service = session_service
        self.post_reply_hook = post_reply_hook
        self.agent_hub = agent_hub
        self.main_agent_key = main_agent_key

        # 运行时状态
        self._session_locks: Dict[str, asyncio.Lock] = {}
        self._running_tasks: Dict[str, asyncio.Task] = {}

        # 模型:优先使用注入的(测试场景),否则从配置加载
        if model is not None:
            self.model = model
        else:
            from agentscope.model import OpenAIChatModel
            import os
            models = config_loader.load_models()
            gate_cfg = models.get("message_gate")
            if gate_cfg is None:
                raise RuntimeError("models.json 缺少 message_gate 配置")
            self.model = OpenAIChatModel(
                model_name=gate_cfg.model_name,
                api_key=os.path.expandvars(gate_cfg.api_key),
                stream=False,
                client_kwargs={"base_url": gate_cfg.api_base},
            )

    def _get_lock(self, session_id: str) -> asyncio.Lock:
        if session_id not in self._session_locks:
            self._session_locks[session_id] = asyncio.Lock()
        return self._session_locks[session_id]

    async def evaluate(
        self,
        session_id: str,
        room_id: str,
        user_id: str,
        bot_id_mapping: Dict[str, str],
        wait_seconds: float = 6.0,
    ) -> None:
        """评估入口:等待、分类、重写、分发。

        Args:
            session_id: 会话 ID
            room_id: 房间 ID
            user_id: 用户 ID
            bot_id_mapping: 由 endpoint 注入的 agent_key → bot_id 映射
            wait_seconds: 等待窗口(默认 6 秒,测试时可缩短)
        """
        from app.service.session_buffer import SessionBuffer
        from app.infrastructure.session_store import SessionStore

        store = SessionStore()
        buffer = SessionBuffer(store, session_id, session_service=self.session_service)
        lock = self._get_lock(session_id)

        # 检查在途任务:已有任务则保存消息 + 发 busy 回复,不排队等待
        existing = self._running_tasks.get(session_id)
        if existing and not existing.done():
            logger.info(
                "[MessageGate] session=%s 有在途任务,保存消息并发送 busy 回复",
                session_id,
            )
            pending = buffer.get_pending()
            if pending:
                await self._handle_busy(
                    session_id=session_id,
                    room_id=room_id,
                    user_id=user_id,
                    pending=pending,
                    bot_id_mapping=bot_id_mapping,
                )
            buffer.clear_pending()
            return
        elif existing and existing.done():
            del self._running_tasks[session_id]

        # 标记在途任务
        self._running_tasks[session_id] = asyncio.current_task()

        try:
            async with lock:
                # 调试:记录锁获取时的 KV 状态
                _kv_data = store.get(session_id) or {}
                _kv_history = _kv_data.get("conversation_history") or []
                _kv_pending = _kv_data.get("pending_messages") or []
                logger.info(
                    "[MessageGate] session=%s 获取锁,conversation_history 长度=%d,pending_messages 长度=%d",
                    session_id, len(_kv_history), len(_kv_pending),
                )

                # 步骤 4:检查 buffer 是否全是 file/image/other 无 text
                if not buffer.has_text_message() and buffer.get_pending():
                    logger.info(
                        "[MessageGate] session=%s 无 text 消息,等待 %.1fs",
                        session_id, wait_seconds,
                    )
                    await asyncio.sleep(wait_seconds)
                    # 等待后重新读取 buffer
                    buffer = SessionBuffer(store, session_id, session_service=self.session_service)

                # 步骤 7:调 LLM 做激活识别(无历史上下文)
                pending = buffer.get_pending()
                if not pending:
                    logger.warning("[MessageGate] session=%s buffer 为空,跳过", session_id)
                    return

                decision = await self._classify_and_rewrite(pending=pending)

                # 步骤 8:根据 intent 分支
                if decision.intent == "chat":
                    await self._handle_chat(
                        session_id=session_id,
                        pending=pending,
                    )
                    buffer.clear_pending()
                    return

                # pass
                await self._handle_actionable(
                    session_id=session_id,
                    room_id=room_id,
                    user_id=user_id,
                    decision=decision,
                    pending=pending,
                    bot_id_mapping=bot_id_mapping,
                )
                buffer.clear_pending()
        finally:
            self._running_tasks.pop(session_id, None)

    async def _classify_and_rewrite(
        self,
        pending: List[Dict[str, Any]],
    ) -> "GateDecision":
        """调 LLM 判断当前消息是否需要激活助手。无历史上下文,只看当前消息。

        Returns:
            GateDecision with intent="chat" or "pass"
        """
        merged_text = self._merge_text_from_pending(pending)
        if not merged_text:
            return GateDecision(intent="chat")

        prompt = (
            "你是助手激活识别器。判断当前消息是否需要AI助手响应。\n"
            "- chat:打招呼、道谢、确认收到、纯社交寒暄、群友间对话 —— 助手沉默\n"
            "- pass:提问、命令、文件处理、提到某Agent名称、需要协助 —— 激活助手\n"
            "\n只输出 \"chat\" 或 \"pass\"。\n"
            "\n当前消息:\n" + merged_text
        )
        messages = [{"role": "user", "content": prompt}]

        response = await self.model(messages=messages)
        text = self._extract_text(response).strip().lower()
        logger.debug("[MessageGate] activation response: %s", text)

        if text == "pass":
            return GateDecision(intent="pass")
        return GateDecision(intent="chat")  # 兜底默认:chat

    async def _handle_chat(
        self,
        session_id: str,
        pending: List[Dict[str, Any]],
    ) -> None:
        """chat 分支:追加用户消息到 conversation_history,不触发 AgentHub,不发 IM。"""
        from app.service.memory import SessionMemory
        from app.infrastructure.session_store import SessionStore

        store = SessionStore()
        mem = SessionMemory(session_id, store)
        for m in pending:
            if m.get("msg_type") == "text" and m.get("msg_content"):
                mem.add("user", m["msg_content"])
        self.session_service.save_to_db(session_id)

    @staticmethod
    def _extract_text(response: Any) -> str:
        """从 OpenAI 兼容响应中提取文本。"""
        if hasattr(response, "content"):
            content = response.content
            if isinstance(content, list):
                for block in content:
                    if isinstance(block, dict) and block.get("type") == "text":
                        return block.get("text", "")
            return str(content)
        return str(response)

    @staticmethod
    def _merge_text_from_pending(pending: List[Dict[str, Any]]) -> str:
        """从 pending 列表中提取文本,与 _classify_and_rewrite 拼 merged_text 逻辑一致。"""
        parts = []
        for m in pending:
            mt = m.get("msg_type", "")
            mc = m.get("msg_content", "")
            if mt == "text" and mc:
                parts.append(mc)
            elif mc:
                parts.append(f"[文件: {mc}]")
        return "\n".join(parts) if parts else ""

    async def _handle_casual(
        self,
        session_id: str,
        room_id: str,
        user_id: str,
        decision: "GateDecision",
        pending: List[Dict[str, Any]],
        bot_id_mapping: Dict[str, str],
    ) -> None:
        """casual 分支:直接发 IM 回复,并记录 user + assistant 到 history。"""
        if not decision.reply:
            return
        from app.service.memory import SessionMemory
        from app.infrastructure.session_store import SessionStore
        store = SessionStore()
        merged_text = "\n".join(
            m.get("msg_content", "") for m in pending
            if m.get("msg_type") == "text"
        )
        mem = SessionMemory(session_id, store)
        mem.add("user", merged_text)
        mem.add("assistant", decision.reply, agent_code=self.main_agent_key)

        # 清空 intent_session
        data = store.get(session_id) or {}
        data["intent_session"] = ""
        store.set(session_id, data)

        self.session_service.save_to_db(session_id)
        await self.post_reply_hook.execute({
            "agent_name": self.main_agent_key,
            "response_content": decision.reply,
            "room_id": room_id,
            "mentioned_list": [user_id],
            "bot_id_mapping": bot_id_mapping,
        })

    async def _handle_busy(
        self,
        session_id: str,
        room_id: str,
        user_id: str,
        pending: List[Dict[str, Any]],
        bot_id_mapping: Dict[str, str],
    ) -> None:
        """在途任务忙碌分支:保存用户消息到 history,发固定告知回复。"""
        from app.service.memory import SessionMemory
        from app.infrastructure.session_store import SessionStore
        store = SessionStore()
        text_msgs = [
            m["msg_content"] for m in pending
            if m.get("msg_type") == "text" and m.get("msg_content")
        ]
        if text_msgs:
            merged_text = "\n".join(text_msgs)
            mem = SessionMemory(session_id, store)
            mem.add("user", merged_text)
            self.session_service.save_to_db(session_id)
        await self.post_reply_hook.execute({
            "agent_name": self.main_agent_key,
            "response_content": BUSY_REPLY,
            "room_id": room_id,
            "mentioned_list": [user_id],
            "bot_id_mapping": bot_id_mapping,
        })

    async def _handle_incomplete(
        self,
        session_id: str,
        room_id: str,
        user_id: str,
        decision: "GateDecision",
        pending: List[Dict[str, Any]],
        bot_id_mapping: Dict[str, str],
    ) -> None:
        """incomplete 分支:追问用户意图,保留 pending_messages 等待补充。"""
        if not decision.reply:
            return
        from app.infrastructure.session_store import SessionStore
        store = SessionStore()
        merged_text = "\n".join(
            m.get("msg_content", "") for m in pending
            if m.get("msg_type") == "text"
        )
        # 将追问交换追加到 intent_session(分类上下文),不污染 conversation_history
        data = store.get(session_id) or {}
        intent_msgs = data.get("intent_session")
        if isinstance(intent_msgs, list):
            intent_msgs.append({"role": "user", "content": merged_text})
            intent_msgs.append({"role": "assistant", "content": decision.reply})
        else:
            intent_msgs = [
                {"role": "user", "content": merged_text},
                {"role": "assistant", "content": decision.reply},
            ]
        data["intent_session"] = intent_msgs
        store.set(session_id, data)
        self.session_service.save_to_db(session_id)
        await self.post_reply_hook.execute({
            "agent_name": self.main_agent_key,
            "response_content": decision.reply,
            "room_id": room_id,
            "mentioned_list": [user_id],
            "bot_id_mapping": bot_id_mapping,
        })

    async def _handle_actionable(
        self,
        session_id: str,
        room_id: str,
        user_id: str,
        decision: "GateDecision",
        pending: List[Dict[str, Any]],
        bot_id_mapping: Dict[str, str],
    ) -> None:
        """pass 分支:分发到 AgentHub。"""
        query = self._merge_text_from_pending(pending)

        if not query:
            logger.warning("[MessageGate] session=%s actionable 但无 query,跳过", session_id)
            return

        # 安全网:从 text 消息中提取 URL,补齐 rewritten_query 可能丢弃的链接
        # 只补 text 类型(用户主动写的 URL),不补 file/image 类型的历史残留链接
        URL_RE = re.compile(r'https?://[^\s<>"{}|\\^`\[\]]+')
        for m in pending:
            if m.get("msg_type") != "text":
                continue
            mc = m.get("msg_content", "")
            for url in URL_RE.findall(mc):
                if url not in query:
                    query = f"{query}\n{url}"

        # 提取 file_url(取第一个非 text 消息的 URL)
        file_url = None
        for m in pending:
            if m.get("msg_type") != "text" and m.get("msg_content"):
                file_url = m["msg_content"]
                break

        try:
            await self.agent_hub.process_message(
                session_id=session_id,
                room_id=room_id,
                user_id=user_id,
                user_query=query,
                file_url=file_url,
                allowed_agent_codes=None,  # Phase 1 简化:不传
                bot_id_mapping=bot_id_mapping,
            )
        except asyncio.CancelledError:
            logger.info(
                "[MessageGate] session=%s 任务被取消",
                session_id,
            )
            raise
        except Exception:
            logger.exception(
                "[MessageGate] session=%s AgentHub.process_message 失败",
                session_id,
            )

    async def close(self) -> None:
        """清理资源:取消运行中的任务并清空状态。"""
        for task in list(self._running_tasks.values()):
            task.cancel()
        self._running_tasks.clear()
        self._session_locks.clear()