Commit 5d405ad0 by sunqi02

docs(message-gate): mark plan complete, add implementation notes

All Tasks 1-7 verified against actual implementation. Noted 6 minor
deviations (model injection param, test race fix, endpoint wiring)
and 1 additional fix (room_id persistence in active_session_service).
Design doc confirmed consistent with no critical deviations.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent e4ba679c
# MessageGate 实施计划
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [x]`) syntax for tracking.
**Goal:** 在 API 入口和 AgentHub 之间插入 MessageGate 服务,统一处理消息等待、意图分类、query 重写和运行任务协调,消除"用户发一半消息 Agent 就开始行动"的体验问题。
**Architecture:** MessageGate 独立 Service 层,由 API endpoint 在 BackgroundTask 中调用。`pending_messages` 持久化到 SessionStore(已有 KV),`_session_locks` / `_running_tasks` 进程内维护。采用完整骨架 + 逐步补齐策略:Phase 1 跑通主流程(cancel 走简化跳过,incomplete 走 actionable 临时分支),后续 phase 完善。
**Tech Stack:** Python 3.12+ / FastAPI / AgentScope / OpenAI 兼容 API / asyncio / SQLAlchemy 2.0 / pytest
**Design Doc:** `ai-workflow/Vibe coding for SQ/docs/superpowers/specs/2026-06-01-message-gate-design.md`
---
## 文件结构总览
| 文件 | 操作 | 任务 |
|------|------|------|
| `config/models.json` | 修改 | Task 1 |
| `app/service/message_gate.py` | 新增 | Task 2,3,4,5,6 |
| `app/service/session_buffer.py` | 新增 | Task 3 |
| `app/api/v1/endpoints/agent_hub.py` | 修改 | Task 4 |
| `app/main.py` | 修改 | Task 4 |
| `tests/test_message_gate.py` | 新增 | Task 2,3,4,5,6 |
| `tests/test_session_buffer.py` | 新增 | Task 3 |
---
## Task 1: 模型配置新增 message_gate 条目
**Files:**
- Modify: `config/models.json`
- [x] **Step 1: 在 models.json 添加 message_gate 条目**
打开 `config/models.json`,在 `models` 字典中添加:
```json
"message_gate": {
"type": "openai_compatible",
"api_base": "https://api.deepseek.com/v1",
"model_name": "deepseek-v4-flash",
"api_key": "${DEEPSEEK_API_KEY}"
}
```
完整 `models` 块形如:
```json
{
"models": {
"main": { ... },
"summary": { ... },
"message_gate": {
"type": "openai_compatible",
"api_base": "https://api.deepseek.com/v1",
"model_name": "deepseek-v4-flash",
"api_key": "${DEEPSEEK_API_KEY}"
}
},
...
}
```
- [x] **Step 2: 验证 config 仍能正常加载**
Run:
```bash
cd /Users/imac/Desktop/GLSK/program/postAgent/ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -c "from app.config.loader import ConfigLoader; cl = ConfigLoader(); print(cl.load_models().keys())"
```
Expected: 打印 `dict_keys(['main', 'summary', 'message_gate'])`,无异常。
- [x] **Step 3: 提交**
```bash
git add config/models.json
git commit -m "feat(message-gate): add message_gate model config"
```
---
## Task 2: MessageGate 骨架类与 evaluate() 接口
**Files:**
- Create: `app/service/message_gate.py`
- Create: `tests/test_message_gate.py`
- [x] **Step 1: 写测试:MessageGate 实例化**
在 `tests/test_message_gate.py` 创建文件:
```python
"""MessageGate 服务的单元测试。"""
import pytest
from unittest.mock import MagicMock, AsyncMock
from app.service.message_gate import MessageGate, GateDecision
def test_message_gate_can_be_constructed():
"""MessageGate 应能通过依赖注入的方式构造。"""
config_loader = MagicMock()
session_service = MagicMock()
post_reply_hook = MagicMock()
agent_hub = MagicMock()
main_agent_key = "main"
gate = MessageGate(
config_loader=config_loader,
session_service=session_service,
post_reply_hook=post_reply_hook,
agent_hub=agent_hub,
main_agent_key=main_agent_key,
)
assert gate is not None
assert gate.config_loader is config_loader
assert gate.session_service is session_service
assert gate.agent_hub is agent_hub
def test_gate_decision_dataclass_defaults():
"""GateDecision 默认字段正确。"""
d = GateDecision(intent="ignore")
assert d.intent == "ignore"
assert d.rewritten_query is None
assert d.reply is None
```
- [x] **Step 2: 运行测试确认失败**
Run:
```bash
cd /Users/imac/Desktop/GLSK/program/postAgent/ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -m pytest tests/test_message_gate.py -v --tb=short
```
Expected: ImportError 或 ModuleNotFoundError(因 `message_gate.py` 还不存在)。
- [x] **Step 3: 创建 MessageGate 骨架**
在 `app/service/message_gate.py` 创建文件:
```python
"""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 实例,Task 6 完整化
main_agent_key: str,
) -> 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] = {}
# 每次 evaluate 调用时由 endpoint 注入的 bot_id_mapping
self._current_bot_id_mapping: Dict[str, str] = {}
self.post_reply_hook = post_reply_hook
self.main_agent_key = main_agent_key
self.bot_id_mapping = bot_id_mapping
# 进程内运行时状态
self._session_locks: Dict[str, asyncio.Lock] = {}
self._running_tasks: Dict[str, asyncio.Task] = {}
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,
messages: List[Dict[str, Any]],
) -> None:
"""评估入口:等待、分类、重写、分发。
Args:
session_id: 会话 ID
room_id: 房间 ID
user_id: 用户 ID
messages: 原始消息列表(dict 形式,由 endpoint 转换)
"""
# 实现见后续 Task
raise NotImplementedError
```
- [x] **Step 4: 重新运行测试确认通过**
Run:
```bash
cd /Users/imac/Desktop/GLSK/program/postAgent/ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -m pytest tests/test_message_gate.py -v --tb=short
```
Expected: 2 个测试全 PASS。
- [x] **Step 5: 提交**
```bash
git add app/service/message_gate.py tests/test_message_gate.py
git commit -m "feat(message-gate): scaffold MessageGate service class"
```
---
## Task 3: SessionBuffer - 消息缓冲存取
**Files:**
- Create: `app/service/session_buffer.py`
- Create: `tests/test_session_buffer.py`
- [x] **Step 1: 写测试**
在 `tests/test_session_buffer.py` 创建文件:
```python
"""SessionBuffer 单元测试 - 测试 pending_messages 的存取。"""
import pytest
from app.infrastructure.session_store import SessionStore
from app.service.session_buffer import SessionBuffer
@pytest.fixture
def fresh_store():
"""每次测试前清空全局 KV 存储。"""
from app.infrastructure.session_store import clear_default_store_for_tests
clear_default_store_for_tests()
return SessionStore()
@pytest.fixture
def session_id():
return "sess_test_001"
def test_init_buffer_creates_empty_pending(fresh_store, session_id):
"""新会话的 pending_messages 应为空列表。"""
buffer = SessionBuffer(fresh_store, session_id)
msgs = buffer.get_pending()
assert msgs == []
def test_append_message_adds_to_pending(fresh_store, session_id):
"""append 应将消息加入 pending_messages。"""
buffer = SessionBuffer(fresh_store, session_id)
msg = {
"msg_id": "m1",
"msg_type": "text",
"msg_content": "你好",
"sender_id": "u1",
"msg_time": "2026-06-01T10:00:00Z",
}
buffer.append(msg)
pending = buffer.get_pending()
assert len(pending) == 1
assert pending[0]["msg_id"] == "m1"
def test_remove_by_msg_id_removes_only_target(fresh_store, session_id):
"""remove_by_msg_id 应只移除匹配的 msg_id。"""
buffer = SessionBuffer(fresh_store, session_id)
buffer.append({"msg_id": "m1", "msg_type": "text", "msg_content": "a", "sender_id": "u", "msg_time": "t"})
buffer.append({"msg_id": "m2", "msg_type": "text", "msg_content": "b", "sender_id": "u", "msg_time": "t"})
buffer.remove_by_msg_ids(["m1"])
pending = buffer.get_pending()
assert len(pending) == 1
assert pending[0]["msg_id"] == "m2"
def test_clear_pending_empties_list(fresh_store, session_id):
"""clear_pending 应清空 pending_messages。"""
buffer = SessionBuffer(fresh_store, session_id)
buffer.append({"msg_id": "m1", "msg_type": "text", "msg_content": "a", "sender_id": "u", "msg_time": "t"})
buffer.clear_pending()
assert buffer.get_pending() == []
def test_has_text_message_true(fresh_store, session_id):
"""has_text_message 在有 text 类型时返回 True。"""
buffer = SessionBuffer(fresh_store, session_id)
buffer.append({"msg_id": "m1", "msg_type": "file", "msg_content": "url", "sender_id": "u", "msg_time": "t"})
buffer.append({"msg_id": "m2", "msg_type": "text", "msg_content": "hi", "sender_id": "u", "msg_time": "t"})
assert buffer.has_text_message() is True
def test_has_text_message_false_when_no_text(fresh_store, session_id):
"""has_text_message 在无 text 类型时返回 False。"""
buffer = SessionBuffer(fresh_store, session_id)
buffer.append({"msg_id": "m1", "msg_type": "file", "msg_content": "url", "sender_id": "u", "msg_time": "t"})
assert buffer.has_text_message() is False
```
- [x] **Step 2: 运行测试确认失败**
Run:
```bash
cd /Users/imac/Desktop/GLSK/program/postAgent/ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -m pytest tests/test_session_buffer.py -v --tb=short
```
Expected: ModuleNotFoundError(`session_buffer.py` 不存在)。
- [x] **Step 3: 实现 SessionBuffer**
在 `app/service/session_buffer.py` 创建文件:
```python
"""SessionBuffer - 封装 pending_messages 的存取操作。"""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from app.infrastructure.session_store import SessionStore
def _ensure_session_exists(store: SessionStore, session_id: str) -> Dict[str, Any]:
"""确保 session payload 存在,否则创建空 payload。"""
existing = store.get(session_id)
if existing is None:
existing = {
"session_id": session_id,
"conversation_history": [],
"pending_messages": [],
}
store.set(session_id, existing)
return existing
if "pending_messages" not in existing:
existing["pending_messages"] = []
store.set(session_id, existing)
return existing
class SessionBuffer:
"""操作指定 session 的 pending_messages 缓冲区。"""
def __init__(self, store: SessionStore, session_id: str) -> None:
self.store = store
self.session_id = session_id
_ensure_session_exists(store, session_id)
def get_pending(self) -> List[Dict[str, Any]]:
"""返回当前 pending_messages 列表的副本。"""
data = self.store.get(self.session_id)
if not data:
return []
return list(data.get("pending_messages") or [])
def append(self, message: Dict[str, Any]) -> None:
"""追加一条消息到 pending_messages。"""
data = self.store.get(self.session_id) or {}
pending = list(data.get("pending_messages") or [])
pending.append(message)
data["pending_messages"] = pending
self.store.set(self.session_id, data)
def remove_by_msg_ids(self, msg_ids: List[str]) -> None:
"""按 msg_id 列表移除指定消息。"""
ids = set(msg_ids)
data = self.store.get(self.session_id) or {}
pending = list(data.get("pending_messages") or [])
data["pending_messages"] = [m for m in pending if m.get("msg_id") not in ids]
self.store.set(self.session_id, data)
def clear_pending(self) -> None:
"""清空 pending_messages。"""
data = self.store.get(self.session_id) or {}
data["pending_messages"] = []
self.store.set(self.session_id, data)
def has_text_message(self) -> bool:
"""检查 pending_messages 中是否有 text 类型消息。"""
for m in self.get_pending():
if m.get("msg_type") == "text":
return True
return False
```
- [x] **Step 4: 运行测试确认通过**
Run:
```bash
cd /Users/imac/Desktop/GLSK/program/postAgent/ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -m pytest tests/test_session_buffer.py -v --tb=short
```
Expected: 6 个测试全 PASS。
- [x] **Step 5: 提交**
```bash
git add app/service/session_buffer.py tests/test_session_buffer.py
git commit -m "feat(message-gate): add SessionBuffer for pending_messages management"
```
---
## Task 4: MessageGate 主流程骨架 - 等待 + 分类 + 重写 + 分发
**Files:**
- Modify: `app/service/message_gate.py`
- Modify: `app/api/v1/endpoints/agent_hub.py`
- Modify: `app/main.py`
- Modify: `tests/test_message_gate.py`
- [x] **Step 1: 添加测试:等待窗口 + 合并后分发**
在 `tests/test_message_gate.py` 末尾添加:
```python
import asyncio
from app.service.session_buffer import SessionBuffer
from app.infrastructure.session_store import clear_default_store_for_tests
@pytest.fixture
def message_gate_with_deps():
"""构造一个带假依赖的 MessageGate。"""
config_loader = MagicMock()
session_service = MagicMock()
post_reply_hook = MagicMock()
post_reply_hook.execute = AsyncMock()
agent_hub = MagicMock()
agent_hub.process_message = AsyncMock()
gate = MessageGate(
config_loader=config_loader,
session_service=session_service,
post_reply_hook=post_reply_hook,
agent_hub=agent_hub,
main_agent_key="main",
)
gate._current_bot_id_mapping = {"main": "bot-001"}
return gate
@pytest.mark.asyncio
async def test_evaluate_pure_file_triggers_wait(message_gate_with_deps):
"""纯 file 消息应等待(用 monkey-patched 短等待避免测试慢)。"""
gate = message_gate_with_deps
# 用 0.1 秒等待代替 6 秒
from app.service import message_gate as mg_module
original_sleep = mg_module.asyncio.sleep
async def fast_sleep(_):
await original_sleep(0.01)
mg_module.asyncio.sleep = fast_sleep
try:
# 模拟 LLM 返回 actionable(patch 内部方法)
gate._classify_and_rewrite = AsyncMock(return_value=GateDecision(
intent="actionable",
rewritten_query="请分析文件 [url]",
))
gate._dispatch_to_agent_hub = AsyncMock()
# 追加 file 消息到 buffer
from app.infrastructure.session_store import SessionStore
from app.infrastructure.session_store import clear_default_store_for_tests
clear_default_store_for_tests()
store = SessionStore()
buffer = SessionBuffer(store, "sess_001")
buffer.append({
"msg_id": "m1", "msg_type": "file",
"msg_content": "https://example.com/audio.mp3",
"sender_id": "u1", "msg_time": "t",
})
await gate.evaluate(
session_id="sess_001",
room_id="r1",
user_id="u1",
bot_id_mapping={"main": "bot-001"},
messages=[],
)
# 等待 0.01s 后分类被调用
assert gate._classify_and_rewrite.await_count == 1
finally:
mg_module.asyncio.sleep = original_sleep
```
- [x] **Step 2: 运行测试确认失败**
Run:
```bash
cd /Users/imac/Desktop/GLSK/program/postAgent/ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -m pytest tests/test_message_gate.py -v --tb=short
```
Expected: 测试失败,因 `evaluate` 还是 NotImplementedError。
- [x] **Step 3: 实现 evaluate() 主流程**
替换 `app/service/message_gate.py` 中的 `evaluate()` 方法:
```python
async def evaluate(
self,
session_id: str,
room_id: str,
user_id: str,
bot_id_mapping: Dict[str, str],
messages: List[Dict[str, Any]] = None,
wait_seconds: float = 6.0,
) -> None:
"""评估入口:等待、分类、重写、分发。
Args:
session_id: 会话 ID
room_id: 房间 ID
user_id: 用户 ID
bot_id_mapping: 由 endpoint 注入的 agent_key → bot_id 映射
messages: 原始消息列表(已由 endpoint 追加到 buffer,留空)
wait_seconds: 等待窗口(默认 6 秒,测试时可缩短)
"""
# 注入当前调用上下文
self._current_bot_id_mapping = bot_id_mapping
# 注入当前调用上下文
self._current_bot_id_mapping = bot_id_mapping
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(self._current_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,
)
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=self._current_bot_id_mapping,
)
buffer.clear_pending()
```
并在文件末尾添加辅助方法(占位实现,Task 5/6 完善):
```python
async def _classify_and_rewrite(
self,
session_id: str,
pending: List[Dict[str, Any]],
) -> "GateDecision":
"""调 LLM 进行意图分类 + query 重写。Phase 1 临时返回 actionable。"""
# 实现见 Task 5
merged_text = "\n".join(
m.get("msg_content", "")
for m in pending
if m.get("msg_type") in ("text", "other", "file")
)
return GateDecision(intent="actionable", rewritten_query=merged_text)
async def _handle_casual(
self,
session_id: str,
room_id: str,
user_id: str,
decision: "GateDecision",
pending: List[Dict[str, Any]],
) -> None:
"""casual 分支:直接发 IM 回复,并记录 user + assistant 到 history。"""
# 实现见 Task 5
if not decision.reply:
return
# 记录 user 消息 + assistant 回复到 conversation_history
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": self._current_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。"""
# 完整实现见 Task 6
pass
```
- [x] **Step 4: 运行测试**
Run:
```bash
cd /Users/imac/Desktop/GLSK/program/postAgent/ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -m pytest tests/test_message_gate.py -v --tb=short
```
Expected: 之前 2 个测试 + 1 个新测试全 PASS(evaluate 测试用 fast_sleep)。
- [x] **Step 5: 修改 endpoint 接入 MessageGate**
修改 `app/api/v1/endpoints/agent_hub.py`,替换 `_process_message_async` 调用:
先添加 import:
```python
from app.service.message_gate import MessageGate
from app.service.session_buffer import SessionBuffer
```
替换 `_process_message_async` 函数(约 130-152 行):
```python
async def _process_message_async_via_gate(
agent_hub: AgentHub,
message_gate: MessageGate,
session_id: str,
room_id: str,
user_id: str,
messages: list, # list[MessageInfo]
):
"""通过 MessageGate 评估后再决定是否走 AgentHub。"""
from app.infrastructure.session_store import SessionStore
store = SessionStore()
buffer = SessionBuffer(store, session_id)
# 追加原始消息到 buffer(步骤 2:锁外)
for msg in messages:
buffer.append(msg.model_dump())
try:
await message_gate.evaluate(
session_id=session_id,
room_id=room_id,
user_id=user_id,
messages=[], # 消息已在 buffer 中
)
except Exception:
logger.exception(
"MessageGate 评估失败: session=%s user=%s",
session_id, user_id,
)
# 兜底:直接走 AgentHub 保持旧行为
from app.service.session_buffer import SessionBuffer as SB
text_parts = [m["msg_content"] for m in SB(store, session_id).get_pending()
if m.get("msg_type") in ("text", "other", "file") and m.get("msg_content")]
fallback_query = "\n".join(text_parts) or "(无内容)"
try:
await agent_hub.process_message(
session_id=session_id,
room_id=room_id,
user_id=user_id,
user_query=fallback_query,
file_url=None,
allowed_agent_codes=None,
bot_id_mapping=None,
)
except Exception:
logger.exception("AgentHub 兜底执行也失败")
```
修改 `chat` endpoint 构造 message_gate 实例。先添加依赖:
```python
def get_message_gate():
from app.main import message_gate_instance
return message_gate_instance
```
在 `chat` endpoint 签名加 `message_gate: MessageGate = Depends(get_message_gate)`,并将 BackgroundTask 调用改为:
```python
background_tasks.add_task(
_process_message_async_via_gate,
agent_hub=agent_hub,
message_gate=message_gate,
session_id=session_id,
room_id=session_id,
user_id=user_id,
messages=request.messages,
)
```
同时删除原有的 `_process_message_async` 函数(或保留并注释为旧版兜底路径)。
- [x] **Step 6: 在 main.py 实例化 MessageGate**
修改 `app/main.py`:
在第 48 行 `agent_hub_instance = None` 后添加:
```python
message_gate_instance = None
```
在 lifespan 函数中(`agent_hub_instance = AgentHub(...)` 之后)添加:
```python
# 初始化 MessageGate
from app.service.message_gate import MessageGate
from app.hooks.post_reply import PostReplyHook
main_agent_key = next((k for k, v in agents.items() if v.is_steward), "main")
post_reply_hook = PostReplyHook(im_service=im_service)
global message_gate_instance
message_gate_instance = MessageGate(
config_loader=config_loader,
session_service=session_service,
post_reply_hook=post_reply_hook,
main_agent_key=main_agent_key,
bot_id_mapping={}, # 由 endpoint 动态构造
)
```
**注意**:`bot_id_mapping` 在 main.py 中为 `{}` 是临时的,endpoint 调用 evaluate 时需提供正确映射。本设计允许 evaluate 阶段用空 mapping(仅 casual 分支发 IM 需要),actionable 分发到 AgentHub 时 mapping 来自 endpoint 传入。
为了让 mapping 正确传递,需要修改 MessageGate 构造:把 `bot_id_mapping` 改为动态注入。修改 `MessageGate.__init__`,移除 `bot_id_mapping` 参数:
```python
def __init__(
self,
config_loader: ConfigLoader,
session_service: ActiveSessionService,
post_reply_hook: PostReplyHook,
main_agent_key: str,
) -> None:
self.config_loader = config_loader
self.session_service = session_service
self.post_reply_hook = post_reply_hook
self.main_agent_key = main_agent_key
# ... 运行时状态 ...
```
并修改 `_handle_casual` 接受 `bot_id_mapping` 参数,修改 `evaluate` 也接受 `bot_id_mapping` 参数。
具体修改(替换 `evaluate` 签名和调用):
```python
async def evaluate(
self,
session_id: str,
room_id: str,
user_id: str,
bot_id_mapping: Dict[str, str],
messages: List[Dict[str, Any]] = None,
wait_seconds: float = 6.0,
) -> None:
"""评估入口。"""
# bot_id_mapping 存为实例属性供内部使用
self._current_bot_id_mapping = bot_id_mapping
# ... 其余不变 ...
```
并在 `_handle_casual` 中使用 `self._current_bot_id_mapping`。
更新 endpoint 调用时传入 `bot_id_mapping=bot_id_mapping`。
- [x] **Step 7: 验证现有 endpoint 测试不回归**
Run:
```bash
cd /Users/imac/Desktop/GLSK/program/postAgent/ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -m pytest tests/test_agent_hub.py -v --tb=short
```
Expected: 测试全部通过(如果之前都是绿的)。如果失败,需修复 endpoint 接入的代码。
- [x] **Step 8: 提交**
```bash
git add app/service/message_gate.py app/api/v1/endpoints/agent_hub.py app/main.py tests/test_message_gate.py
git commit -m "feat(message-gate): implement evaluate() main flow and wire into endpoint"
```
---
## Task 5: LLM 调用意图分类 + Query 重写
**Files:**
- Modify: `app/service/message_gate.py`
- Modify: `tests/test_message_gate.py`
- [x] **Step 1: 添加测试:casual 分类和重写**
在 `tests/test_message_gate.py` 末尾添加:
```python
@pytest.mark.asyncio
async def test_classify_casual_intent(message_gate_with_deps, monkeypatch):
"""_classify_and_rewrite 应正确解析 LLM 返回的 casual JSON。"""
gate = message_gate_with_deps
# Mock OpenAIChatModel 返回 casual JSON
fake_response_text = '{"intent": "casual", "reply": "早~"}'
gate.model = AsyncMock(return_value=MagicMock(
content=[{"type": "text", "text": fake_response_text}]
))
pending = [{"msg_id": "m1", "msg_type": "text", "msg_content": "早上好",
"sender_id": "u1", "msg_time": "t"}]
decision = await gate._classify_and_rewrite(
session_id="sess_001",
pending=pending,
agent_codes=["11", "14"],
)
assert decision.intent == "casual"
assert decision.reply == "早~"
@pytest.mark.asyncio
async def test_classify_actionable_with_rewrite(message_gate_with_deps):
"""actionable 分类应包含 rewritten_query。"""
gate = message_gate_with_deps
fake_response_text = '{"intent": "actionable", "rewritten_query": "请总结这个文件"}'
gate.model = AsyncMock(return_value=MagicMock(
content=[{"type": "text", "text": fake_response_text}]
))
pending = [{"msg_id": "m1", "msg_type": "text", "msg_content": "帮我总结",
"sender_id": "u1", "msg_time": "t"}]
decision = await gate._classify_and_rewrite(
session_id="sess_001",
pending=pending,
agent_codes=["11"],
)
assert decision.intent == "actionable"
assert decision.rewritten_query == "请总结这个文件"
```
- [x] **Step 2: 运行测试确认失败**
Run:
```bash
cd /Users/imac/Desktop/GLSK/program/postAgent/ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -m pytest tests/test_message_gate.py -v --tb=short
```
Expected: 新加的 2 个测试失败(`_classify_and_rewrite` 签名不匹配 / `model` 属性不存在)。
- [x] **Step 3: 实现真实 LLM 调用**
修改 `app/service/message_gate.py`:
1. 在 `__init__` 中加载 message_gate 模型:
```python
def __init__(
self,
config_loader: ConfigLoader,
session_service: ActiveSessionService,
post_reply_hook: PostReplyHook,
main_agent_key: str,
) -> None:
self.config_loader = config_loader
self.session_service = session_service
self.post_reply_hook = post_reply_hook
self.main_agent_key = main_agent_key
# 加载 message_gate 专用模型
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},
)
self.formatter = None # 暂用默认
# 运行时状态
self._session_locks: Dict[str, asyncio.Lock] = {}
self._running_tasks: Dict[str, asyncio.Task] = {}
```
2. 替换 `_classify_and_rewrite` 为真实实现:
```python
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.service.memory import SessionMemory
from agentscope.message import Msg
# 合并文本
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")
```
3. 修改 `_classify_and_rewrite` 的调用(Task 4 中的 evaluate),传入 `agent_codes`。
修改 `evaluate` 方法中的调用:
```python
# 步骤 7:调 LLM 分类 + 重写
decision = await self._classify_and_rewrite(
session_id=session_id,
pending=pending,
agent_codes=list(self._current_bot_id_mapping.keys()),
)
```
- [x] **Step 4: 运行测试确认通过**
Run:
```bash
cd /Users/imac/Desktop/GLSK/program/postAgent/ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -m pytest tests/test_message_gate.py -v --tb=short
```
Expected: 5 个测试全 PASS(2 个骨架 + 1 个 evaluate + 2 个新加的 LLM 测试)。
- [x] **Step 5: 提交**
```bash
git add app/service/message_gate.py tests/test_message_gate.py
git commit -m "feat(message-gate): integrate LLM for intent classification and query rewrite"
```
---
## Task 6: Actionable 分发到 AgentHub
**Files:**
- Modify: `app/service/message_gate.py`
- Modify: `tests/test_message_gate.py`
- [x] **Step 1: 添加测试:actionable 分发到 AgentHub**
在 `tests/test_message_gate.py` 末尾添加:
```python
@pytest.mark.asyncio
async def test_actionable_dispatches_to_agent_hub(message_gate_with_deps):
"""actionable 分支应创建 asyncio.Task 调 AgentHub。"""
gate = message_gate_with_deps
gate.agent_hub = MagicMock()
gate.agent_hub.process_message = AsyncMock()
from app.infrastructure.session_store import SessionStore
from app.infrastructure.session_store import clear_default_store_for_tests
clear_default_store_for_tests()
store = SessionStore()
await gate._handle_actionable(
session_id="sess_001",
room_id="r1",
user_id="u1",
decision=GateDecision(intent="actionable", rewritten_query="请分析文件"),
pending=[{"msg_id": "m1", "msg_type": "file", "msg_content": "url",
"sender_id": "u1", "msg_time": "t"}],
bot_id_mapping={"main": "bot-001"},
)
# 等待 task 启动
await asyncio.sleep(0.1)
assert "sess_001" in gate._running_tasks
# 等 task 完成
task = gate._running_tasks["sess_001"]
await task
gate.agent_hub.process_message.assert_awaited_once()
```
- [x] **Step 2: 运行测试确认失败**
Run:
```bash
cd /Users/imac/Desktop/GLSK/program/postAgent/ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -m pytest tests/test_message_gate.py -v --tb=short
```
Expected: 新测试失败(`_handle_actionable` 签名错误 / `agent_hub` 属性不存在)。
- [x] **Step 3: 实现 actionable 分发**
修改 `app/service/message_gate.py`:
1. 在 `__init__` 中新增 `agent_hub` 参数:
```python
def __init__(
self,
config_loader: ConfigLoader,
session_service: ActiveSessionService,
post_reply_hook: PostReplyHook,
agent_hub: Any, # AgentHub 实例,避免循环 import
main_agent_key: str,
) -> 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
# ... 其余 ...
```
2. 替换 `_handle_actionable` 为真实实现:
```python
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))
```
3. 修改 `evaluate` 调用 `_handle_actionable` 时传入 `bot_id_mapping`:
```python
# 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=self._current_bot_id_mapping,
)
buffer.clear_pending()
```
4. 修改 `app/main.py` 的 MessageGate 构造:
```python
message_gate_instance = MessageGate(
config_loader=config_loader,
session_service=session_service,
post_reply_hook=post_reply_hook,
agent_hub=agent_hub_instance,
main_agent_key=main_agent_key,
)
```
注意:必须先有 `agent_hub_instance` 才能构造 message_gate。
5. `message_gate_with_deps` fixture 已在 Task 4 中创建(含 agent_hub),无需修改。
- [x] **Step 4: 运行测试**
Run:
```bash
cd /Users/imac/Desktop/GLSK/program/postAgent/ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -m pytest tests/test_message_gate.py -v --tb=short
```
Expected: 6 个测试全 PASS。
- [x] **Step 5: 端到端验证 - 启动服务并用 test_request.json 试发**
Run:
```bash
cd /Users/imac/Desktop/GLSK/program/postAgent/ai-workflow/workspace/agent-admin/backend
USE_CONSOLE_IM=true PYTHONPATH=. python -m app.main &
sleep 5
curl -X POST http://localhost:8000/api/v1/chat/completions \
-H "Content-Type: application/json" \
-d @test_request.json
sleep 15
# 检查控制台输出是否看到 MessageGate 评估日志
kill %1
```
Expected: 控制台输出应包含:
- `[MessageGate] session=xxx` 日志
- AgentHub 实际处理(ReAct 输出)
- ConsoleIM 打印
- [x] **Step 6: 提交**
```bash
git add app/service/message_gate.py app/main.py tests/test_message_gate.py
git commit -m "feat(message-gate): implement actionable dispatch to AgentHub"
```
---
## Task 7: 全部测试回归
**Files:**
- (no file changes)
- [x] **Step 1: 跑全量测试**
Run:
```bash
cd /Users/imac/Desktop/GLSK/program/postAgent/ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -m pytest tests/ -v --tb=short
```
Expected: 现有 24 个 pre-existing failures 保持不变(不新增失败),新加的 MessageGate 和 SessionBuffer 测试全 PASS。
- [x] **Step 2: 如果有失败,分析并修复**
逐个分析失败原因。常见的:
- import 错误:检查模块路径
- 异步测试问题:确认使用 `@pytest.mark.asyncio` 装饰器
- fixture 状态污染:检查 KV store 清理
修复后重跑直到稳定。
- [x] **Step 3: 提交(如有修改)**
```bash
git add -A
git commit -m "test(message-gate): fix test failures and stabilize test suite"
```
---
## Task 8: 文档更新 + 设计文档确认
**Files:**
- Modify: `docs/superpowers/specs/2026-06-01-message-gate-design.md`(如实施中发现与原设计有偏差)
- [x] **Step 1: 检查实施与设计文档的一致性**
回顾实施过程,对比原设计文档:
- `evaluate()` 签名是否与设计一致?
- SessionBuffer 字段是否完整?
- LLM prompt 是否包含所有要求的注入信息?
如果发现偏差,**更新设计文档**记录实际实现(不要回头改代码)。
- [x] **Step 2: 更新 plan 状态**
将本文档中所有 `- [x]` 改为 `- [x]`。
- [x] **Step 3: 提交**
```bash
git add docs/superpowers/specs/2026-06-01-message-gate-design.md docs/superpowers/sunqi/plans/2026-06-01-message-gate.md
git commit -m "docs(message-gate): sync design doc with implementation, mark plan complete"
```
---
## Phase 2 / Phase 3 留待后续
本计划仅实现 Phase 1:
- 消息等待(6s 窗口)
- 意图分类 + query 重写
- casual / actionable 分支
- running task 简化跳过
**Phase 2 待办**:
- 替换 Task 4 中"步骤 6 简化跳过"为真实 LLM cancel 判断
- 实施 Task 6 中 `allowed_agent_codes` 透传
- 处理 cancel 后的 cancellation cascade
**Phase 3 待办**:
- 启用 `pending_intent=incomplete`
- 实现 incomplete 分支完整 IM 追问
- 处理追问后用户回复的上下文关联
每个 Phase 单独拆 plan 实施。
---
## Implementation Notes
### Deviations from Plan
1. **`model` 参数注入(Task 2/5)**:实际实现的 `MessageGate.__init__` 增加了可选 `model` 参数(默认 `None`),用于测试场景注入 mock 模型,避免真实加载 `models.json`。当 `model=None` 时才从配置加载 `OpenAIChatModel`。Plan 原始骨架无此参数,测试代码相应传入 `model=MagicMock()`。
2. **`self.formatter` 未添加(Task 5)**:Plan 的 Task 5 Step 3 示例代码中有 `self.formatter = None`,实际实现省略(暂不需要)。
3. **`test_actionable_dispatches_to_agent_hub` 测试改进(Task 6)**:Plan 原始测试直接 `await asyncio.sleep(0.1)` 后检查 `_running_tasks`,存在竞态条件(task 可能在 0.1s 内完成被 `done_callback` 清理)。实际实现改用 `side_effect=_slow_process`(0.5s 延迟)确保 task 在检查时仍在运行。
4. **Endpoint `bot_id_mapping` 传递(Task 4)**:Plan 原始 endpoint 示例未传 `bot_id_mapping` 到 `evaluate()`。实际 endpoint 在 `_process_message_async_via_gate` 和 `background_tasks.add_task()` 中都正确传递了 `bot_id_mapping`。
5. **消息追加时机(Task 4)**:Plan 原始设计在 `_process_message_async_via_gate`(BackgroundTask 内)追加消息到 buffer。实际实现改为在 `chat()` endpoint 主函数中(BackgroundTask 之外)追加,确保消息在锁外立即可见,与设计的"步骤 2 在锁外"原则更一致。
6. **`_process_message_async` 保留(Task 4)**:Plan 建议删除旧版 `_process_message_async`。实际保留作为参考(未使用),新增 `_process_message_async_via_gate` 作为活跃路径。
### Additional Fixes
- **Task 7 regression fix(`active_session_service.py`)**:`SessionBuffer` 预创建 session 时不带 `room_id`,导致 `get_or_create_session` 查询到已有 session 时 `room_id` 为空。修复为:当 `room_id` 非空且 session 中 `room_id` 为空时补写(commit e4ba679)。
### Design Doc Consistency
设计文档 `2026-06-01-message-gate-design.md` 与实现一致,无关键偏差:
- 四意图分类(actionable/casual/incomplete/ignore)✓
- Phase 1 简化策略(cancel→跳过,incomplete→走 actionable)✓
- SessionStore 扩展 `pending_messages` 字段 ✓
- LLM 分类+重写单次调用 ✓
- 进程内 `_session_locks` / `_running_tasks` ✓
- 全局风格指南注入 ✓
- 模型配置 `message_gate` 条目 ✓
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!