"""会话 / 消息 / 用户记忆 Mongo 实现。""" from __future__ import annotations from datetime import datetime from typing import Any import re from bson import ObjectId from motor.motor_asyncio import AsyncIOMotorDatabase from domain.models import ( ChatMessage, MemoryKind, MemoryStatus, MessageRole, Session, SessionStatus, UserMemory, ) from domain.ports import MemoryRepository, MessageRepository, SessionRepository def _dt(v: Any) -> datetime: if isinstance(v, datetime): return v return datetime.utcnow() class MongoSessionRepository(SessionRepository): def __init__(self, db: AsyncIOMotorDatabase) -> None: self._col = db.agent_sessions async def create(self, session: Session) -> Session: doc = { "thread_id": session.thread_id, "company_id": session.company_id, "user_id": session.user_id, "title": session.title, "status": session.status.value, "summary": session.summary, "created_at": session.created_at, "updated_at": session.updated_at, "last_message_at": session.last_message_at, } await self._col.insert_one(doc) return session async def get(self, company_id: int, user_id: str, thread_id: str) -> Session | None: doc = await self._col.find_one( {"company_id": company_id, "user_id": user_id, "thread_id": thread_id} ) return None if doc is None else self._to_session(doc) async def list_active(self, company_id: int, user_id: str, limit: int = 50) -> list[Session]: cursor = ( self._col.find( { "company_id": company_id, "user_id": user_id, "status": SessionStatus.ACTIVE.value, } ) .sort("updated_at", -1) .limit(limit) ) return [self._to_session(d) async for d in cursor] async def update(self, session: Session) -> Session: session.updated_at = datetime.utcnow() await self._col.update_one( { "company_id": session.company_id, "user_id": session.user_id, "thread_id": session.thread_id, }, { "$set": { "title": session.title, "status": session.status.value, "summary": session.summary, "updated_at": session.updated_at, "last_message_at": session.last_message_at, } }, ) return session @staticmethod def _to_session(doc: dict[str, Any]) -> Session: return Session( thread_id=doc["thread_id"], company_id=int(doc["company_id"]), user_id=str(doc["user_id"]), title=doc.get("title") or "新对话", status=SessionStatus(doc.get("status") or SessionStatus.ACTIVE.value), summary=doc.get("summary"), created_at=_dt(doc.get("created_at")), updated_at=_dt(doc.get("updated_at")), last_message_at=doc.get("last_message_at"), ) class MongoMessageRepository(MessageRepository): def __init__(self, db: AsyncIOMotorDatabase) -> None: self._col = db.agent_messages async def next_seq(self, company_id: int, user_id: str, thread_id: str) -> int: doc = await self._col.find_one( {"company_id": company_id, "user_id": user_id, "thread_id": thread_id}, sort=[("seq", -1)], projection={"seq": 1}, ) return 1 if doc is None else int(doc["seq"]) + 1 async def append(self, message: ChatMessage) -> ChatMessage: doc = { "company_id": message.company_id, "user_id": message.user_id, "thread_id": message.thread_id, "seq": message.seq, "role": message.role.value, "content": message.content, "tool_name": message.tool_name, "tool_call_id": message.tool_call_id, "created_at": message.created_at, } result = await self._col.insert_one(doc) message.id = str(result.inserted_id) return message async def list_recent( self, company_id: int, user_id: str, thread_id: str, limit: int ) -> list[ChatMessage]: cursor = ( self._col.find( {"company_id": company_id, "user_id": user_id, "thread_id": thread_id} ) .sort("seq", -1) .limit(limit) ) rows = [self._to_msg(d) async for d in cursor] rows.reverse() return rows @staticmethod def _to_msg(doc: dict[str, Any]) -> ChatMessage: return ChatMessage( id=str(doc.get("_id")), company_id=int(doc["company_id"]), user_id=str(doc["user_id"]), thread_id=doc["thread_id"], seq=int(doc["seq"]), role=MessageRole(doc["role"]), content=doc.get("content") or "", tool_name=doc.get("tool_name"), tool_call_id=doc.get("tool_call_id"), created_at=_dt(doc.get("created_at")), ) class MongoMemoryRepository(MemoryRepository): def __init__(self, db: AsyncIOMotorDatabase) -> None: self._col = db.agent_user_memory async def list_active( self, company_id: int, user_id: str, limit: int ) -> list[UserMemory]: cursor = ( self._col.find( { "company_id": company_id, "user_id": user_id, "status": MemoryStatus.ACTIVE.value, } ) .sort("updated_at", -1) .limit(limit) ) return [self._to_mem(d) async for d in cursor] async def count_active(self, company_id: int, user_id: str) -> int: return int( await self._col.count_documents( { "company_id": company_id, "user_id": user_id, "status": MemoryStatus.ACTIVE.value, } ) ) async def search( self, company_id: int, user_id: str, query: str, limit: int ) -> list[UserMemory]: """按摘要/正文关键词匹配(非向量);无关键词时退化为最近更新列表。""" tokens = _keyword_tokens(query) filt: dict[str, Any] = { "company_id": company_id, "user_id": user_id, "status": MemoryStatus.ACTIVE.value, } if tokens: token_clauses = [] for t in tokens: escaped = re.escape(t) token_clauses.append( { "$or": [ {"summary": {"$regex": escaped, "$options": "i"}}, {"text": {"$regex": escaped, "$options": "i"}}, ] } ) filt["$and"] = token_clauses cursor = self._col.find(filt).sort("updated_at", -1).limit(max(1, min(limit, 20))) return [self._to_mem(d) async for d in cursor] async def get_by_ids( self, company_id: int, user_id: str, memory_ids: list[str] ) -> list[UserMemory]: oids: list[ObjectId] = [] for mid in memory_ids: try: oids.append(ObjectId(mid)) except Exception: continue if not oids: return [] cursor = self._col.find( { "_id": {"$in": oids}, "company_id": company_id, "user_id": user_id, "status": MemoryStatus.ACTIVE.value, } ) by_id: dict[str, UserMemory] = {} async for d in cursor: by_id[str(d["_id"])] = self._to_mem(d) # 保持调用方 id 顺序 return [by_id[mid] for mid in memory_ids if mid in by_id] async def upsert(self, memory: UserMemory) -> UserMemory: memory.updated_at = datetime.utcnow() if not (memory.summary or "").strip(): memory.summary = _fallback_summary(memory.text) payload = { "company_id": memory.company_id, "user_id": memory.user_id, "kind": memory.kind.value, "key": memory.key, "text": memory.text, "summary": memory.summary, "value": memory.value, "source_thread_id": memory.source_thread_id, "status": memory.status.value, "confidence": memory.confidence, "updated_at": memory.updated_at, } if memory.key: existing = await self._col.find_one( { "company_id": memory.company_id, "user_id": memory.user_id, "key": memory.key, "status": {"$ne": MemoryStatus.DELETED.value}, } ) if existing: await self._col.update_one({"_id": existing["_id"]}, {"$set": payload}) memory.id = str(existing["_id"]) memory.created_at = _dt(existing.get("created_at")) return memory payload["created_at"] = memory.created_at result = await self._col.insert_one(payload) memory.id = str(result.inserted_id) return memory async def soft_delete(self, company_id: int, user_id: str, memory_id: str) -> bool: try: oid = ObjectId(memory_id) except Exception: return False result = await self._col.update_one( {"_id": oid, "company_id": company_id, "user_id": user_id}, { "$set": { "status": MemoryStatus.DELETED.value, "updated_at": datetime.utcnow(), } }, ) return result.modified_count > 0 @staticmethod def _to_mem(doc: dict[str, Any]) -> UserMemory: text = doc.get("text") or "" summary = (doc.get("summary") or "").strip() or _fallback_summary(text) return UserMemory( id=str(doc.get("_id")), company_id=int(doc["company_id"]), user_id=str(doc["user_id"]), kind=MemoryKind(doc.get("kind") or MemoryKind.FACT.value), key=doc.get("key"), text=text, summary=summary, value=doc.get("value") or {}, source_thread_id=doc.get("source_thread_id"), status=MemoryStatus(doc.get("status") or MemoryStatus.ACTIVE.value), confidence=float(doc.get("confidence") or 0.8), created_at=_dt(doc.get("created_at")), updated_at=_dt(doc.get("updated_at")), ) def _fallback_summary(text: str, max_len: int = 80) -> str: s = (text or "").strip().replace("\n", " ") if len(s) <= max_len: return s return s[: max_len - 1] + "…" def _keyword_tokens(query: str) -> list[str]: """按空白与常见标点切词;过短 token 丢弃。""" parts = re.split(r"[\s,,。.!!??;;::、/\\|]+", (query or "").strip()) out: list[str] = [] for p in parts: t = p.strip() if len(t) >= 1 and t not in out: out.append(t) return out[:8]