message_gate.py 20.3 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 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
"""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  # 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 消息文本:text 类型原文照录,非 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}]")
        merged_text = "\n".join(parts) if parts else "(空消息)"

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

        # 构建子 agent 的 prompts(过滤 is_steward=True 的主 agent)
        agent_prompts: Dict[str, str] = {}
        if agent_codes:
            for code in agent_codes:
                cfg = self.agent_hub.agents.get(code) if hasattr(self.agent_hub, "agents") else None
                if cfg and not getattr(cfg, "is_steward", False):
                    agent_prompts[code] = getattr(cfg, "prompt", "")

        # 取 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=agent_codes or [], agent_prompts=agent_prompts,
            )

        # 抽 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 [], agent_prompts=agent_prompts,
                ),
            }

        # 拼 intent_session 中的非 system 消息(incomplete 路径追加的追问上下文)
        messages = [system_msg]
        for m in base_messages:
            content = (m.get("content") or "").strip()
            if m.get("role") != "system" and content:
                messages.append({"role": m["role"], "content": m.get("content", "")})
        # 拼 history 成多轮 messages 对
        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:保留 system + incomplete 追问上下文 + 本次 user_current
        # "## 当前用户消息" 前缀的消息是历次 classify 的 user_current,丢弃
        intent_session = [system_msg]
        for m in base_messages:
            content = (m.get("content") or "").strip()
            if m.get("role") != "system" and "## 当前用户消息" not in content and content:
                intent_session.append({"role": m["role"], "content": m.get("content", "")})
        intent_session.append({"role": "user", "content": user_prompt})
        data["intent_session"] = intent_session
        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], agent_prompts: Dict[str, str]
    ) -> str:
        """构造不含 history 段的 system prompt,注入子 agent 人设。"""
        if agent_prompts:
            lines = []
            for code in agent_codes:
                p = agent_prompts.get(code)
                if p:
                    lines.append(f"- {code}: {p}")
            agent_section = "\n".join(lines) if lines else "(未指定任何子 Agent)"
        else:
            agent_section = "(未指定任何子 Agent)"

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

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

## 当前会话可用的 Agent 及其职责
{agent_section}

## 消息结构说明
- 以 `## 当前用户消息` 标记的内容为**本轮输入**,是你需要分类和重写的目标
- 其余消息(不含该标记的)是历史上下文,仅供理解对话背景,**不作为本轮输入**

## 判定规则(必须遵守)
分类和重写时,**只依据 `## 当前用户消息` 标记的内容**。

- **actionable**: 任务类型明确 + `## 当前用户消息` 中已提供所需资源 + 可独立执行
  - 在已有对话上下文内可完成的任务(追问细节、引用历史结论、修改上一轮输出)也属此类
- **casual**: 打招呼、感谢、确认、闲聊
- **incomplete**: 满足以下任一:
  - 任务需要文件/数据等资源但 `## 当前用户消息` 中未提供(根据 Agent 职责判断需要什么)
  - 任务类型明确但缺少关键参数(收件人、目标语言等)
  - 意图模糊、缺少关键信息
- **ignore**: 纯表情、无意义字符、系统通知

## 追问规范
- reply 必须明确点出缺什么("请提供需要处理的音频文件"、"请补充收件人邮箱")
- 若历史上下文中有相关资源,可在 reply 中反问确认("您是想处理刚才的 xxx.mp3 吗?"),但**不能把历史资源写入 rewritten_query**

## 消息格式说明
- 非 text 消息(文件、图片等)会被标记为 [文件: URL]
- 用户输入的文本消息保持原样
- `## 当前用户消息` 中的 URL 是用户本轮主动提供的,应保留到 rewritten_query

## 输出格式(严格 JSON)
{{
  "intent": "actionable|casual|incomplete|ignore",
  "rewritten_query": "完整指令(actionable 时必填)。只包含 `## 当前用户消息` 中的内容,不从历史消息中提取链接或文件",
  "reply": "回复文本(casual/incomplete 时必填)"
}}
"""

    def _build_default_classify_messages(
        self,
        agent_codes: List[str],
        agent_prompts: Dict[str, str],
    ) -> List[Dict[str, Any]]:
        """默认 messages(KV 完全空 / 损坏时用)。"""
        return [
            {"role": "system", "content": self._build_classify_prompt(
                agent_codes=agent_codes, agent_prompts=agent_prompts)},
            {"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") == "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:
        """actionable 分支:分发到 AgentHub。"""
        query = decision.rewritten_query or ""
        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}"

        # 清空 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(取第一个非 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()