message_gate.py 16.6 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 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
"""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),
                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(
                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)

                # 清空 intent_session 并持久化
                data = store.get(session_id) or {}
                data["intent_session"] = ""
                store.set(session_id, data)
                self.session_service.save_to_db(session_id)
                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

            if decision.intent == "incomplete":
                await self._handle_incomplete(
                    session_id=session_id,
                    room_id=room_id,
                    user_id=user_id,
                    decision=decision,
                    pending=pending,
                    bot_id_mapping=bot_id_mapping,
                )
                # 不清空 buffer:用户后续补充的消息需要合并
                return

            # 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 重写。"""
        from app.infrastructure.session_store import SessionStore
        store = SessionStore()

        # 合并 pending 消息文本(逻辑不变)
        parts = []
        for m in pending:
            mt = m.get("msg_type", "")
            mc = m.get("msg_content", "")
            if mt in ("text", "other", "file") and mc:
                if mt == "file":
                    parts.append(f"[文件: {mc}]")
                elif mt == "other":
                    parts.append(f"[其他: {mc}]")
                else:
                    parts.append(mc)
        merged_text = "\n".join(parts) if parts else "(空消息)"

        # 加载 KV data
        data = store.get(session_id) or {}
        history = (data.get("conversation_history") or [])[-10:]

        # 取 base_messages(intent_session フィールド,冷恢复或上次写入)
        base_messages = data.get("intent_session")
        if not isinstance(base_messages, list) or not base_messages:
            base_messages = self._build_default_classify_messages(agent_codes or [])

        # 抽 system(不含 history)
        system_msg = next(
            (m for m in base_messages if m.get("role") == "system"),
            None,
        )
        if not system_msg:
            system_msg = {
                "role": "system",
                "content": self._build_classify_prompt(agent_codes=agent_codes or []),
            }

        # 拼 history 成多轮 messages 对
        messages = [system_msg]
        for h in history:
            if h.get("role") in ("user", "assistant"):
                messages.append({"role": h["role"], "content": h.get("content", "")})

        # 加 user current
        user_prompt = f"## 当前用户消息\n{merged_text}\n\n请按 system 指令输出 JSON。"
        messages.append({"role": "user", "content": user_prompt})

        # 调 LLM
        response = await self.model(messages=messages)

        # 解析 JSON
        text = self._extract_text(response)
        logger.debug(
            "[MessageGate] LLM raw response type=%s, extracted text=%s",
            type(response).__name__, text[:300],
        )

        # 写回 intent_session(不含 history,下次再拼)
        # 注意:SessionStore.get() 返回反序列化后新 dict,必须显式 set() 写回 KV
        data["intent_session"] = [system_msg, {"role": "user", "content": user_prompt}]
        store.set(session_id, data)
        self.session_service.save_to_db(session_id)

        return self._parse_decision_json(text)

    def _build_classify_prompt(self, agent_codes: List[str]) -> str:
        """构造不含 history 段的 system prompt。"""
        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}

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

    def _build_default_classify_messages(
        self,
        agent_codes: List[str],
    ) -> List[Dict[str, Any]]:
        """默认 messages(KV 完全空 / 损坏时用)。"""
        return [
            {"role": "system", "content": self._build_classify_prompt(agent_codes=agent_codes)},
            {"role": "user", "content": ""},
        ]

    @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)

        # 清空 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.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)
        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:
        """actionable 分支:分发到 AgentHub。"""
        query = decision.rewritten_query or ""
        if not query:
            logger.warning("[MessageGate] session=%s actionable 但无 query,跳过", session_id)
            return

        # 清空 intent_session(AgentHub 内部的 save_to_db 会顺带写库)
        from app.infrastructure.session_store import SessionStore
        store = SessionStore()
        data = store.get(session_id) or {}
        data["intent_session"] = ""
        store.set(session_id, data)

        # 提取 file_url(兼容 image 和 file 类型)
        file_url = None
        for m in pending:
            if m.get("msg_type") in ("image", "file") 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()