message_gate.py 12.6 KB
"""MessageGate 服务 - API 层和 AgentHub 之间的意图门控层。

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

import asyncio
import logging
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  # actionable | casual | incomplete | ignore
    rewritten_query: Optional[str] = None
    reply: Optional[str] = None
    cancel: bool = False  # 暂未使用,Phase 2 启用


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),
                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)
        lock = self._get_lock(session_id)

        async with lock:
            # 步骤 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)

            # 步骤 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(
                session_id=session_id,
                pending=pending,
                agent_codes=list(bot_id_mapping.keys()),
            )

            # 步骤 8:根据 intent 分支
            if decision.intent == "ignore":
                # 按 msg_id 移除本批次
                ids = [m["msg_id"] for m in pending if "msg_id" in m]
                buffer.remove_by_msg_ids(ids)
                return

            if decision.intent == "casual":
                await self._handle_casual(
                    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()
                return

            # actionable 或 incomplete(Phase 1 临时走 actionable 路径)
            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,
        session_id: str,
        pending: List[Dict[str, Any]],
        agent_codes: Optional[List[str]] = None,
    ) -> "GateDecision":
        """调 LLM 进行意图分类 + query 重写。"""
        # 合并文本
        merged_text = "\n".join(
            m.get("msg_content", "")
            for m in pending
            if m.get("msg_type") in ("text", "other", "file")
        )

        # 加载最近 5 轮历史
        from app.infrastructure.session_store import SessionStore
        store = SessionStore()
        history_data = store.get(session_id) or {}
        history = (history_data.get("conversation_history") or [])[-10:]

        # 构造 prompt
        system_prompt = self._build_classify_prompt(
            agent_codes=agent_codes or [],
            history=history,
        )
        user_prompt = f"## 当前用户消息\n{merged_text}\n\n请按 system 指令输出 JSON。"

        # 调用 LLM
        response = await self.model(
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_prompt},
            ],
        )

        # 解析 JSON
        text = self._extract_text(response)
        return self._parse_decision_json(text)

    def _build_classify_prompt(
        self,
        agent_codes: List[str],
        history: List[Dict[str, Any]],
    ) -> str:
        """构造分类 + 重写的 system prompt。"""
        history_lines = []
        for m in history:
            role = m.get("role", "user")
            content = (m.get("content") or "")[:200]
            history_lines.append(f"{role}: {content}")
        history_text = "\n".join(history_lines) if history_lines else "(无)"

        agent_text = ", ".join(agent_codes) if agent_codes else "(未指定)"

        return f"""你是 MessageGate 助手,负责:
1. 识别用户消息的意图(actionable / casual / incomplete / ignore)
2. 将用户消息重写为完整、明确的指令

## 风格指南
- 保持自然、说人话,不官方
- 简洁,不超过 50 字
- emoji 适度

## 意图分类
- actionable: 有明确任务意图 + 信息充足
- casual: 打招呼、感谢、确认、闲聊
- incomplete: 有资源(文件/URL)但无意图说明,或有意图但缺少关键信息
- ignore: 纯表情、无意义字符、系统通知

## 当前会话可用的 Agent
{agent_text}

## 最近 5 轮对话历史
{history_text}

## 输出格式(严格 JSON)
{{
  "intent": "actionable|casual|incomplete|ignore",
  "rewritten_query": "完整指令(actionable 时必填)",
  "reply": "回复文本(casual/incomplete 时必填)"
}}
"""

    @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 _parse_decision_json(text: str) -> "GateDecision":
        """解析 LLM 返回的 JSON 字符串为 GateDecision。"""
        import json
        import re

        # 尝试提取 JSON 块(可能包在 ```json 中)
        match = re.search(r"\{.*\}", text, re.DOTALL)
        if not match:
            logger.warning("MessageGate LLM 输出无 JSON: %s", text[:200])
            return GateDecision(intent="ignore")
        try:
            data = json.loads(match.group(0))
            return GateDecision(
                intent=data.get("intent", "ignore"),
                rewritten_query=data.get("rewritten_query"),
                reply=data.get("reply"),
            )
        except json.JSONDecodeError:
            logger.warning("MessageGate LLM 输出 JSON 解析失败: %s", text[:200])
            return GateDecision(intent="ignore")

    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") in ("text", "other", "file")
        )
        mem = SessionMemory(session_id, store)
        mem.add("user", merged_text)
        mem.add("assistant", decision.reply, agent_code=self.main_agent_key)
        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:
        """actionable 分支:分发到 AgentHub。"""
        query = decision.rewritten_query or ""
        if not query:
            logger.warning("[MessageGate] session=%s actionable 但无 query,跳过", session_id)
            return

        # 提取 file_url(兼容 image 类型)
        file_url = None
        for m in pending:
            if m.get("msg_type") == "image" and m.get("msg_content"):
                file_url = m["msg_content"]
                break

        async def _run():
            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,
                )

        task = asyncio.create_task(_run())
        self._running_tasks[session_id] = task
        task.add_done_callback(lambda t: self._running_tasks.pop(session_id, None))

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