Commit 13413f47 by sunqi02 Committed by 胡悦

将后端服务与agent服务的代码进行物理隔离

1 parent 8ea607b3
...@@ -72,9 +72,6 @@ class ActiveSessionService: ...@@ -72,9 +72,6 @@ class ActiveSessionService:
"conversation_history": json.loads( "conversation_history": json.loads(
db_sess.conversation_history or "[]" db_sess.conversation_history or "[]"
), ),
"intent_session": json.loads(
db_sess.intent_session or "[]",
),
"context_entities": {}, "context_entities": {},
"created_at": ( "created_at": (
db_sess.created_at.isoformat() db_sess.created_at.isoformat()
...@@ -96,7 +93,6 @@ class ActiveSessionService: ...@@ -96,7 +93,6 @@ class ActiveSessionService:
"channel": channel, "channel": channel,
"room_id": room_id, "room_id": room_id,
"conversation_history": [], "conversation_history": [],
"intent_session": [],
"context_entities": {}, "context_entities": {},
"created_at": _utcnow_iso(), "created_at": _utcnow_iso(),
"updated_at": _utcnow_iso(), "updated_at": _utcnow_iso(),
...@@ -137,10 +133,6 @@ class ActiveSessionService: ...@@ -137,10 +133,6 @@ class ActiveSessionService:
existing.conversation_history = json.dumps( existing.conversation_history = json.dumps(
data.get("conversation_history", []), ensure_ascii=False data.get("conversation_history", []), ensure_ascii=False
) )
existing.intent_session = json.dumps(
data.get("intent_session", []),
ensure_ascii=False,
)
else: else:
db_sess = Session( db_sess = Session(
session_id=session_id, session_id=session_id,
...@@ -149,10 +141,6 @@ class ActiveSessionService: ...@@ -149,10 +141,6 @@ class ActiveSessionService:
conversation_history=json.dumps( conversation_history=json.dumps(
data.get("conversation_history", []), ensure_ascii=False data.get("conversation_history", []), ensure_ascii=False
), ),
intent_session=json.dumps(
data.get("intent_session", []),
ensure_ascii=False,
),
) )
db.add(db_sess) db.add(db_sess)
......
...@@ -88,7 +88,6 @@ class MessageGate: ...@@ -88,7 +88,6 @@ class MessageGate:
user_id: str, user_id: str,
bot_id_mapping: Dict[str, str], bot_id_mapping: Dict[str, str],
wait_seconds: float = 6.0, wait_seconds: float = 6.0,
offline_agents_info: Optional[list] = None,
) -> None: ) -> None:
"""评估入口:等待、分类、重写、分发。 """评估入口:等待、分类、重写、分发。
...@@ -185,7 +184,6 @@ class MessageGate: ...@@ -185,7 +184,6 @@ class MessageGate:
query=query, query=query,
file_url=file_url, file_url=file_url,
bot_id_mapping=bot_id_mapping, bot_id_mapping=bot_id_mapping,
offline_agents_info=offline_agents_info,
) )
finally: finally:
self._running_tasks.pop(session_id, None) self._running_tasks.pop(session_id, None)
...@@ -280,7 +278,7 @@ class MessageGate: ...@@ -280,7 +278,7 @@ class MessageGate:
# 清空 intent_session # 清空 intent_session
data = store.get(session_id) or {} data = store.get(session_id) or {}
data["intent_session"] = [] data["intent_session"] = ""
store.set(session_id, data) store.set(session_id, data)
self.session_service.save_to_db(session_id) self.session_service.save_to_db(session_id)
...@@ -321,8 +319,6 @@ class MessageGate: ...@@ -321,8 +319,6 @@ class MessageGate:
intent_msgs = [{"role": "user", "content": merged_text}] intent_msgs = [{"role": "user", "content": merged_text}]
data["intent_session"] = intent_msgs data["intent_session"] = intent_msgs
store.set(session_id, data) store.set(session_id, data)
# 持久化到 DB,防止进程崩溃导致 intent_session 丢失
self.session_service.save_to_db(session_id)
await self.post_reply_hook.execute({ await self.post_reply_hook.execute({
"agent_name": self.main_agent_key, "agent_name": self.main_agent_key,
"response_content": BUSY_REPLY, "response_content": BUSY_REPLY,
...@@ -379,7 +375,6 @@ class MessageGate: ...@@ -379,7 +375,6 @@ class MessageGate:
query: str, query: str,
file_url: Optional[str], file_url: Optional[str],
bot_id_mapping: Dict[str, str], bot_id_mapping: Dict[str, str],
offline_agents_info: Optional[list] = None,
) -> None: ) -> None:
"""pass 分支:分发到 AgentHub。query/file_url 由调用方在锁内预先提取。""" """pass 分支:分发到 AgentHub。query/file_url 由调用方在锁内预先提取。"""
if not query: if not query:
...@@ -394,7 +389,6 @@ class MessageGate: ...@@ -394,7 +389,6 @@ class MessageGate:
user_query=query, user_query=query,
file_url=file_url, file_url=file_url,
allowed_agent_codes=None, # Phase 1 简化:不传 allowed_agent_codes=None, # Phase 1 简化:不传
offline_agents_info=offline_agents_info,
bot_id_mapping=bot_id_mapping, bot_id_mapping=bot_id_mapping,
) )
except asyncio.CancelledError: except asyncio.CancelledError:
......
...@@ -2,8 +2,8 @@ import logging ...@@ -2,8 +2,8 @@ import logging
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from typing import Optional, List from typing import Optional, List
from app.service.agent_hub import AgentHub from app.agent_core.agent_hub import AgentHub
from app.service.message_gate import MessageGate from app.agent_core.message_gate import MessageGate
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
......
...@@ -40,10 +40,10 @@ from app.model.wecom_sync import ( # noqa: F401 ...@@ -40,10 +40,10 @@ from app.model.wecom_sync import ( # noqa: F401
WeComSyncCheckpoint, WeComSyncCheckpoint,
) )
from app.schema.common import error_response_payload, is_wrapped_payload, success_response_payload from app.schema.common import error_response_payload, is_wrapped_payload, success_response_payload
from app.service.agent_hub import AgentHub from app.agent_core.agent_hub import AgentHub
from app.service.active_session_service import ActiveSessionService from app.agent_core.active_session_service import ActiveSessionService
from app.service.console_im_service import ConsoleIMService from app.agent_core.console_im_service import ConsoleIMService
from app.service.im_service import IMService from app.agent_core.im_service import IMService
agent_hub_instance = None agent_hub_instance = None
message_gate_instance = None message_gate_instance = None
...@@ -101,7 +101,7 @@ async def lifespan(app: FastAPI): ...@@ -101,7 +101,7 @@ async def lifespan(app: FastAPI):
) )
# ── MessageGate 实例化 ── # ── MessageGate 实例化 ──
from app.service.message_gate import MessageGate from app.agent_core.message_gate import MessageGate
from app.hooks.post_reply import PostReplyHook from app.hooks.post_reply import PostReplyHook
main_agent_key = next((k for k, v in agents.items() if v.is_steward), "main") main_agent_key = next((k for k, v in agents.items() if v.is_steward), "main")
......
from __future__ import annotations
import json
import logging
from dataclasses import dataclass
from datetime import datetime
from app.infrastructure.time import china_now
from typing import Callable, Optional
from sqlalchemy.orm import Session as SASession
from app.infrastructure.session_store import SessionStore
from app.model.session import Session
logger = logging.getLogger(__name__)
def _utcnow_iso() -> str:
return china_now().isoformat()
@dataclass(frozen=True)
class ActiveSessionInfo:
id: str
session_id: str
channel: str
room_id: str
status: str = "active"
class ActiveSessionService:
def __init__(self, store: Optional[SessionStore] = None, db_factory: Optional[Callable[[], SASession]] = None) -> None:
self.store = store or SessionStore()
self._db_factory = db_factory
def get_or_create_session(
self,
session_id: str,
room_id: str = "",
channel: str = "wechat_group",
) -> ActiveSessionInfo:
# 1. 先查内存(热路径)
existing = self.store.get(session_id)
if existing:
# SessionBuffer 可能预创建 session 但不带 room_id,这里补上
if room_id and not existing.get("room_id"):
existing["room_id"] = room_id
self.store.set(session_id, existing)
return ActiveSessionInfo(
id=session_id,
session_id=session_id,
channel=existing.get("channel", channel),
room_id=existing.get("room_id", room_id),
)
# 2. 查 DB(冷恢复)
if self._db_factory:
try:
with self._db_factory() as db:
db_sess = db.query(Session).filter(
Session.session_id == session_id
).first()
# with 块结束 → db 关闭、连接归还池
except Exception:
logger.exception("Failed to cold-recover session %s from DB, 降级新建", session_id)
db_sess = None
if db_sess:
payload = {
"session_id": db_sess.session_id,
"channel": db_sess.channel,
"room_id": db_sess.room_id,
"conversation_history": json.loads(
db_sess.conversation_history or "[]"
),
"context_entities": {},
"created_at": (
db_sess.created_at.isoformat()
if db_sess.created_at else _utcnow_iso()
),
"updated_at": _utcnow_iso(),
}
self.store.set(session_id, payload)
return ActiveSessionInfo(
id=session_id,
session_id=session_id,
channel=db_sess.channel,
room_id=db_sess.room_id,
)
# 3. 都没有,创建新 session
payload = {
"session_id": session_id,
"channel": channel,
"room_id": room_id,
"conversation_history": [],
"context_entities": {},
"created_at": _utcnow_iso(),
"updated_at": _utcnow_iso(),
}
self.store.set(session_id, payload)
return ActiveSessionInfo(
id=session_id,
session_id=session_id,
channel=channel,
room_id=room_id,
)
def save_to_db(self, session_id: str) -> None:
if not self._db_factory:
logger.warning("[save_to_db] session=%s db_factory 为 None,跳过持久化", session_id)
return
data = self.store.get(session_id)
if not data:
logger.warning("[save_to_db] session=%s KV 中无数据,跳过持久化", session_id)
return
history = data.get("conversation_history") or []
logger.info(
"[save_to_db] session=%s conversation_history 长度=%d",
session_id, len(history),
)
try:
with self._db_factory() as db:
existing = db.query(Session).filter(
Session.session_id == session_id
).first()
if existing:
existing.room_id = data.get("room_id", "")
existing.channel = data.get("channel", "wechat_group")
existing.conversation_history = json.dumps(
data.get("conversation_history", []), ensure_ascii=False
)
else:
db_sess = Session(
session_id=session_id,
room_id=data.get("room_id", ""),
channel=data.get("channel", "wechat_group"),
conversation_history=json.dumps(
data.get("conversation_history", []), ensure_ascii=False
),
)
db.add(db_sess)
db.commit()
except Exception:
logger.exception("Failed to persist session %s to DB", session_id)
"""SessionBuffer - 封装 pending_messages 的存取操作。"""
from __future__ import annotations
import logging
from typing import Any, Dict, List, Optional, TYPE_CHECKING
from app.infrastructure.session_store import SessionStore
if TYPE_CHECKING:
from app.service.active_session_service import ActiveSessionService
logger = logging.getLogger(__name__)
def _ensure_session_exists(
store: SessionStore,
session_id: str,
session_service: Optional["ActiveSessionService"] = None,
) -> Dict[str, Any]:
"""确保 session payload 存在于 KV。KV miss 时先尝试 DB 冷恢复。"""
existing = store.get(session_id)
if existing is None:
# KV miss → 尝试 DB 冷恢复
if session_service is not None:
session_service.get_or_create_session(session_id=session_id)
existing = store.get(session_id)
if existing is None:
logger.warning(
"[SessionBuffer] session=%s KV+DB 均不存在,新建 session",
session_id,
)
existing = {
"session_id": session_id,
"conversation_history": [],
"pending_messages": [],
}
store.set(session_id, existing)
return existing
else:
logger.info(
"[SessionBuffer] session=%s 从 DB 冷恢复成功",
session_id,
)
if "pending_messages" not in existing:
existing["pending_messages"] = []
store.set(session_id, existing)
history_len = len(existing.get("conversation_history") or [])
logger.info(
"[SessionBuffer] session=%s 已存在,conversation_history 长度=%d",
session_id, history_len,
)
return existing
class SessionBuffer:
"""操作指定 session 的 pending_messages 缓冲区。"""
def __init__(
self,
store: SessionStore,
session_id: str,
session_service: Optional["ActiveSessionService"] = None,
) -> None:
self.store = store
self.session_id = session_id
_ensure_session_exists(store, session_id, session_service=session_service)
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
\ No newline at end of file \ No newline at end of file
...@@ -7,9 +7,9 @@ from app.main import app as fastapi_app ...@@ -7,9 +7,9 @@ from app.main import app as fastapi_app
# ── AgentHub 测试实例 ──────────────────────────────────────────── # ── AgentHub 测试实例 ────────────────────────────────────────────
from app.config.settings import AgentConfig from app.config.settings import AgentConfig
from app.service.active_session_service import ActiveSessionService from app.agent_core.active_session_service import ActiveSessionService
from app.service.agent_hub import AgentHub, AgentHubError, _route_context_var, _background_tasks from app.agent_core.agent_hub import AgentHub, AgentHubError, _route_context_var, _background_tasks
from app.service.memory import SessionMemory from app.agent_core.memory import SessionMemory
async def _drain_background_tasks(): async def _drain_background_tasks():
...@@ -98,7 +98,7 @@ def _override_get_agent_hub(): ...@@ -98,7 +98,7 @@ def _override_get_agent_hub():
def _override_get_message_gate(): def _override_get_message_gate():
from unittest.mock import MagicMock, AsyncMock from unittest.mock import MagicMock, AsyncMock
from app.service.message_gate import MessageGate, GateDecision from app.agent_core.message_gate import MessageGate, GateDecision
mock_gate = MagicMock(spec=MessageGate) mock_gate = MagicMock(spec=MessageGate)
mock_gate.evaluate = AsyncMock(return_value=None) mock_gate.evaluate = AsyncMock(return_value=None)
# 让 evaluate 同步调用 agent_hub.process_message(模拟 actionable 分支) # 让 evaluate 同步调用 agent_hub.process_message(模拟 actionable 分支)
...@@ -897,7 +897,7 @@ async def test_summarize_thinking_long_text_calls_model(): ...@@ -897,7 +897,7 @@ async def test_summarize_thinking_long_text_calls_model():
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_hook_summarizes_thinking_before_send(): async def test_hook_summarizes_thinking_before_send():
"""hook 应在发送 IM 前对长 thinking 调用摘要化。""" """hook 应在发送 IM 前对长 thinking 调用摘要化。"""
from app.service.agent_hub import _im_post_reasoning_hook from app.agent_core.agent_hub import _im_post_reasoning_hook
mock_im = AsyncMock() mock_im = AsyncMock()
mock_im.send_message.return_value = {"code": 200} mock_im.send_message.return_value = {"code": 200}
...@@ -930,7 +930,7 @@ async def test_hook_summarizes_thinking_before_send(): ...@@ -930,7 +930,7 @@ async def test_hook_summarizes_thinking_before_send():
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_hook_summarizes_even_short_thinking(): async def test_hook_summarizes_even_short_thinking():
"""即使是短 thinking,也应走摘要化(不直接暴露内部推理)。""" """即使是短 thinking,也应走摘要化(不直接暴露内部推理)。"""
from app.service.agent_hub import _im_post_reasoning_hook from app.agent_core.agent_hub import _im_post_reasoning_hook
mock_im = AsyncMock() mock_im = AsyncMock()
mock_im.send_message.return_value = {"code": 200} mock_im.send_message.return_value = {"code": 200}
...@@ -960,7 +960,7 @@ async def test_hook_summarizes_even_short_thinking(): ...@@ -960,7 +960,7 @@ async def test_hook_summarizes_even_short_thinking():
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_hook_skips_after_call_sub_agent_result(): async def test_hook_skips_after_call_sub_agent_result():
"""call_sub_agent 工具结果后的 post_reasoning 应跳过 IM 发送。""" """call_sub_agent 工具结果后的 post_reasoning 应跳过 IM 发送。"""
from app.service.agent_hub import _im_post_reasoning_hook from app.agent_core.agent_hub import _im_post_reasoning_hook
mock_im = AsyncMock() mock_im = AsyncMock()
mock_summarize = AsyncMock() mock_summarize = AsyncMock()
......
...@@ -20,7 +20,7 @@ def _make_test_agents(): ...@@ -20,7 +20,7 @@ def _make_test_agents():
class TestSkillRegistration: class TestSkillRegistration:
def test_agent_hub_registers_skills_on_init(self): def test_agent_hub_registers_skills_on_init(self):
"""AgentHub.__init__ should register skills to Toolkit via register_agent_skill.""" """AgentHub.__init__ should register skills to Toolkit via register_agent_skill."""
from app.service.agent_hub import AgentHub from app.agent_core.agent_hub import AgentHub
mock_loader = MagicMock() mock_loader = MagicMock()
mock_model_config = MagicMock() mock_model_config = MagicMock()
...@@ -42,7 +42,7 @@ class TestSkillRegistration: ...@@ -42,7 +42,7 @@ class TestSkillRegistration:
def test_agent_hub_skills_loaded_from_toolkit(self): def test_agent_hub_skills_loaded_from_toolkit(self):
"""Skills dict should come from load_skills_from_toolkit, not load_skills.""" """Skills dict should come from load_skills_from_toolkit, not load_skills."""
from app.service.agent_hub import AgentHub from app.agent_core.agent_hub import AgentHub
expected_skills = { expected_skills = {
"buddy-sings": { "buddy-sings": {
......
"""MessageGate 激活识别测试。""" """MessageGate 激活识别测试。"""
import pytest import pytest
from unittest.mock import MagicMock, AsyncMock from unittest.mock import MagicMock, AsyncMock
from app.service.message_gate import MessageGate, GateDecision from app.agent_core.message_gate import MessageGate, GateDecision
def test_message_gate_can_be_constructed(): def test_message_gate_can_be_constructed():
...@@ -124,7 +124,7 @@ async def test_handle_actionable_calls_agent_hub(): ...@@ -124,7 +124,7 @@ async def test_handle_actionable_calls_agent_hub():
def test_extract_query_and_file_url_text_only(): def test_extract_query_and_file_url_text_only():
"""仅包含文本消息时,提取 query 且 file_url 为 None。""" """仅包含文本消息时,提取 query 且 file_url 为 None。"""
from app.service.message_gate import MessageGate from app.agent_core.message_gate import MessageGate
pending = [{"msg_type": "text", "msg_content": "帮我整理纪要"}] pending = [{"msg_type": "text", "msg_content": "帮我整理纪要"}]
query, file_url = MessageGate._extract_query_and_file_url(pending) query, file_url = MessageGate._extract_query_and_file_url(pending)
assert query == "帮我整理纪要" assert query == "帮我整理纪要"
...@@ -133,7 +133,7 @@ def test_extract_query_and_file_url_text_only(): ...@@ -133,7 +133,7 @@ def test_extract_query_and_file_url_text_only():
def test_extract_query_and_file_url_with_file(): def test_extract_query_and_file_url_with_file():
"""混合文本+文件消息时,提取 query 和 file_url。""" """混合文本+文件消息时,提取 query 和 file_url。"""
from app.service.message_gate import MessageGate from app.agent_core.message_gate import MessageGate
pending = [ pending = [
{"msg_type": "text", "msg_content": "分析这份报表"}, {"msg_type": "text", "msg_content": "分析这份报表"},
{"msg_type": "file", "msg_content": "https://oss.example.com/report.xlsx"}, {"msg_type": "file", "msg_content": "https://oss.example.com/report.xlsx"},
...@@ -145,7 +145,7 @@ def test_extract_query_and_file_url_with_file(): ...@@ -145,7 +145,7 @@ def test_extract_query_and_file_url_with_file():
def test_extract_query_and_file_url_append_url(): def test_extract_query_and_file_url_append_url():
"""文本中已含 URL 时,不重复追加。""" """文本中已含 URL 时,不重复追加。"""
from app.service.message_gate import MessageGate from app.agent_core.message_gate import MessageGate
pending = [ pending = [
{"msg_type": "text", "msg_content": "看下这个 https://example.com/doc"}, {"msg_type": "text", "msg_content": "看下这个 https://example.com/doc"},
] ]
...@@ -157,7 +157,7 @@ def test_extract_query_and_file_url_append_url(): ...@@ -157,7 +157,7 @@ def test_extract_query_and_file_url_append_url():
def test_extract_query_and_file_url_empty(): def test_extract_query_and_file_url_empty():
"""空 pending 返回空 query。""" """空 pending 返回空 query。"""
from app.service.message_gate import MessageGate from app.agent_core.message_gate import MessageGate
query, file_url = MessageGate._extract_query_and_file_url([]) query, file_url = MessageGate._extract_query_and_file_url([])
assert query == "" assert query == ""
assert file_url is None assert file_url is None
......
...@@ -5,8 +5,8 @@ import shutil ...@@ -5,8 +5,8 @@ import shutil
from pathlib import Path from pathlib import Path
from unittest.mock import MagicMock, AsyncMock from unittest.mock import MagicMock, AsyncMock
from app.service.active_session_service import ActiveSessionService from app.agent_core.active_session_service import ActiveSessionService
from app.service.agent_hub import AgentHub from app.agent_core.agent_hub import AgentHub
from agentscope.message._message_block import TextBlock from agentscope.message._message_block import TextBlock
......
"""SessionBuffer 单元测试 - 测试 pending_messages 的存取。""" """SessionBuffer 单元测试 - 测试 pending_messages 的存取。"""
import pytest import pytest
from app.infrastructure.session_store import SessionStore from app.infrastructure.session_store import SessionStore
from app.service.session_buffer import SessionBuffer from app.agent_core.session_buffer import SessionBuffer
@pytest.fixture @pytest.fixture
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!