message_gate.py 13.3 KB
"""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


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)

        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)

            # 步骤 6:检查 running task(Phase 1 简化版:发现 running 直接跳过)
            running_task = self._running_tasks.get(session_id)
            if running_task and not running_task.done():
                logger.info(
                    "[MessageGate] session=%s 已有 running task,跳过",
                    session_id,
                )
                buffer.clear_pending()
                return

            # 步骤 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()

    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_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()