session_service.py 13.9 KB
from __future__ import annotations

import json
import secrets
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from typing import Any, Optional

from sqlalchemy.orm import Session as OrmSession

from app.infrastructure.session_store import SESSION_TTL_SECONDS, SessionStore
from app.model.agent import Agent
from app.model.session import ConversationHistory, Session as DbSession, SessionStatus
from app.schema.session import (
    SessionArchiveResponse,
    SessionContextResponse,
    SessionCreateRequest,
    SessionCreateResponse,
    SessionDetailResponse,
    SessionHistoryTurn,
    SessionInfo,
    SessionUpdateRequest,
    SessionUpdateResponse,
)


def _utcnow() -> datetime:
    return datetime.now(timezone.utc)


def _gen_session_id() -> str:
    return f"sess_{secrets.token_urlsafe(12)}"


def _merge_entities(base: dict[str, Any], incoming: Optional[dict[str, Any]]) -> dict[str, Any]:
    if not incoming:
        return base
    merged = dict(base)
    merged.update(incoming)
    return merged


@dataclass(frozen=True)
class _ActiveSessionPayload:
    session_id: str
    user_id: str
    channel: str
    room_id: str = ""
    current_agent_id: int = 101
    current_agent_code: Optional[str] = None
    conversation_history: list[dict[str, Any]] = field(default_factory=list)
    context_entities: dict[str, Any] = field(default_factory=dict)
    created_at: str = ""
    updated_at: str = ""


class SessionService:
    def __init__(self, db: OrmSession, store: Optional[SessionStore] = None) -> None:
        self.db = db
        self.store = store or SessionStore()

    def _default_agent_id(self) -> int:
        agent = self.db.query(Agent).filter(Agent.is_deleted == False).order_by(Agent.id.asc()).first()
        return agent.id if agent else 101

    def create(self, req: SessionCreateRequest) -> SessionCreateResponse:
        session_id = _gen_session_id()
        now = _utcnow()
        current_agent_id = self._default_agent_id()

        payload = _ActiveSessionPayload(
            session_id=session_id,
            user_id=req.user_id,
            channel=req.channel,
            room_id="",
            current_agent_id=current_agent_id,
            current_agent_code=None,
            conversation_history=[],
            context_entities={},
            created_at=now.isoformat(),
            updated_at=now.isoformat(),
        )
        self.store.set(session_id, payload.__dict__)

        return SessionCreateResponse(
            session_id=session_id,
            user_id=req.user_id,
            channel=req.channel,
            current_agent_id=current_agent_id,
            created_at=now,
        )

    def append_and_merge(self, session_id: str, req: SessionUpdateRequest) -> SessionUpdateResponse:
        existing = self.store.get(session_id)
        if not existing:
            raise ValueError("会话不存在或已超时")

        now = _utcnow()
        history: list[dict[str, Any]] = list(existing.get("conversation_history") or [])
        history.append(
            {
                "role": req.role,
                "content": req.content,
                "agent_id": req.agent_id,
                "intent": req.intent,
                "timestamp": now.isoformat(),
            }
        )
        entities = _merge_entities(existing.get("context_entities") or {}, req.entities or {})

        existing["conversation_history"] = history
        existing["context_entities"] = entities
        existing["current_agent_id"] = req.agent_id
        existing["updated_at"] = now.isoformat()

        self.store.set(session_id, existing)

        return SessionUpdateResponse(success=True, updated_at=now, turn_count=len(history))

    def get_detail(self, session_id: str) -> SessionDetailResponse:
        existing = self.store.get(session_id)
        if existing:
            agent_name = None
            agent = self.db.query(Agent).filter(Agent.id == existing.get("current_agent_id")).first()
            if agent:
                agent_name = agent.name

            history_items = []
            for item in existing.get("conversation_history") or []:
                history_items.append(
                    SessionHistoryTurn(
                        role=item["role"],
                        content=item["content"],
                        agent_id=item.get("agent_id"),
                        intent=item.get("intent"),
                        timestamp=datetime.fromisoformat(item["timestamp"]),
                    )
                )

            return SessionDetailResponse(
                session_id=existing["session_id"],
                user_id=existing["user_id"],
                channel=existing["channel"],
                current_agent_id=existing["current_agent_id"],
                current_agent_name=agent_name,
                conversation_history=history_items,
                context_entities=existing.get("context_entities") or {},
                created_at=datetime.fromisoformat(existing["created_at"]),
                updated_at=datetime.fromisoformat(existing["updated_at"]),
            )

        db_sess = self.db.query(DbSession).filter(DbSession.session_id == session_id).first()
        if not db_sess:
            raise ValueError("会话不存在")

        history_rows = (
            self.db.query(ConversationHistory)
            .filter(ConversationHistory.session_id == session_id)
            .order_by(ConversationHistory.id.asc())
            .all()
        )
        history_items = []
        for row in history_rows:
            history_items.append(
                SessionHistoryTurn(
                    role=row.role,
                    content=row.content,
                    agent_id=row.agent_id,
                    intent=row.intent,
                    timestamp=row.timestamp.replace(tzinfo=timezone.utc) if row.timestamp.tzinfo is None else row.timestamp,
                )
            )

        agent_name = None
        agent = self.db.query(Agent).filter(Agent.id == db_sess.current_agent_id).first()
        if agent:
            agent_name = agent.name

        # Archived sessions do not keep transient context_entities.
        return SessionDetailResponse(
            session_id=db_sess.session_id,
            user_id=db_sess.user_id,
            channel=db_sess.channel,
            current_agent_id=db_sess.current_agent_id,
            current_agent_name=agent_name,
            conversation_history=history_items,
            context_entities={},
            created_at=db_sess.created_at.replace(tzinfo=timezone.utc) if db_sess.created_at.tzinfo is None else db_sess.created_at,
            updated_at=db_sess.updated_at.replace(tzinfo=timezone.utc) if db_sess.updated_at.tzinfo is None else db_sess.updated_at,
        )

    def get_context(self, session_id: str) -> SessionContextResponse:
        existing = self.store.get(session_id)
        if not existing:
            return SessionContextResponse(
                session_id=session_id,
                current_agent_id=0,
                last_entities={},
                inheritance_valid=False,
                expires_at=None,
            )

        updated_at = datetime.fromisoformat(existing["updated_at"])
        expires_at = updated_at + timedelta(seconds=SESSION_TTL_SECONDS)
        return SessionContextResponse(
            session_id=session_id,
            current_agent_id=existing["current_agent_id"],
            last_entities=existing.get("context_entities") or {},
            inheritance_valid=True,
            expires_at=expires_at,
        )

    def archive(self, session_id: str) -> SessionArchiveResponse:
        existing = self.store.get(session_id)
        if not existing:
            raise ValueError("会话不存在或已超时")

        now = _utcnow()

        db_sess = self.db.query(DbSession).filter(DbSession.session_id == session_id).first()
        if not db_sess:
            db_sess = DbSession(
                session_id=session_id,
                user_id=existing["user_id"],
                channel=existing["channel"],
                current_agent_id=existing["current_agent_id"],
                status=SessionStatus.archived.value,
            )
            self.db.add(db_sess)
        else:
            db_sess.status = SessionStatus.archived.value
            db_sess.current_agent_id = existing["current_agent_id"]

        for item in existing.get("conversation_history") or []:
            self.db.add(
                ConversationHistory(
                    session_id=session_id,
                    role=item["role"],
                    content=item["content"],
                    agent_id=item.get("agent_id"),
                    intent=item.get("intent"),
                    entities_json=json.dumps(existing.get("context_entities") or {}, ensure_ascii=False),
                )
            )

        self.db.commit()
        self.store.delete(session_id)

        return SessionArchiveResponse(success=True, archived_at=now)

    # ── AgentHub 内部 API ──────────────────────────────────────────────

    def get_or_create_session(
        self,
        session_id: str,
        room_id: str = "",
        user_id: str = "",
        channel: str = "wechat_group",
    ) -> SessionInfo:
        """获取或创建活跃会话。session_id 为空时自动生成。先查 KV store,再查 DB。"""
        from app.schema.session import SessionInfo

        if not session_id:
            session_id = _gen_session_id()

        existing = self.store.get(session_id)
        if existing:
            return SessionInfo(
                id=session_id,
                session_id=session_id,
                user_id=existing.get("user_id", user_id),
                channel=existing.get("channel", channel),
                room_id=existing.get("room_id", room_id),
                current_agent_code=existing.get("current_agent_code"),
                status="active",
            )

        now = _utcnow()
        current_agent_id = self._default_agent_id()
        payload = {
            "session_id": session_id,
            "user_id": user_id,
            "channel": channel,
            "room_id": room_id,
            "current_agent_id": current_agent_id,
            "current_agent_code": None,
            "conversation_history": [],
            "context_entities": {},
            "created_at": now.isoformat(),
            "updated_at": now.isoformat(),
        }
        self.store.set(session_id, payload)
        return SessionInfo(
            id=session_id,
            session_id=session_id,
            user_id=user_id,
            channel=channel,
            room_id=room_id,
            current_agent_code=None,
            status="active",
        )

    def add_message(
        self,
        session_id: str,
        role: str,
        content: str,
        agent_code: Optional[str] = None,
    ) -> None:
        """向活跃会话的 conversation_history 追加一条消息。session_id 是字符串(如 sess_xxx)。"""
        existing = self.store.get(session_id)
        if not existing:
            return
        history: list[dict[str, Any]] = list(existing.get("conversation_history") or [])
        history.append({
            "role": role,
            "content": content,
            "agent_code": agent_code,
            "agent_id": None,
            "intent": None,
            "timestamp": _utcnow().isoformat(),
        })
        existing["conversation_history"] = history
        existing["updated_at"] = _utcnow().isoformat()
        self.store.set(session_id, existing)

    def get_session_messages(self, session_id: str) -> list[dict[str, Any]]:
        """返回 conversation_history 原始 dict 列表。AgentHub 自行决定取最近 N 条。"""
        existing = self.store.get(session_id)
        if not existing:
            return []
        return list(existing.get("conversation_history") or [])

    def update_current_agent(self, session_id: str, agent_code: str) -> None:
        """更新活跃会话的 current_agent_code,用于继承路由。"""
        existing = self.store.get(session_id)
        if not existing:
            return
        existing["current_agent_code"] = agent_code
        existing["updated_at"] = _utcnow().isoformat()
        self.store.set(session_id, existing)

    def get_session(self, session_id: str) -> Optional[SessionInfo]:
        """按 session_id 获取单个会话(仅 KV store 活跃会话)。"""
        from app.schema.session import SessionInfo

        existing = self.store.get(session_id)
        if not existing:
            return None
        return SessionInfo(
            id=session_id,
            session_id=session_id,
            user_id=existing.get("user_id", ""),
            channel=existing.get("channel", ""),
            room_id=existing.get("room_id", ""),
            current_agent_code=existing.get("current_agent_code"),
            status="active",
        )

    def get_session_by_uuid(self, session_id: str) -> Optional[SessionInfo]:
        """按 UUID 获取会话(= get_session 的别名,语义一致)。"""
        return self.get_session(session_id)

    def ensure_active_session(self, session_id: str, user_id: str, channel: str, room_id: str = "") -> None:
        """Ensure session exists in KV store (create if not found, refresh TTL if exists)."""
        existing = self.store.get(session_id)
        if existing:
            self.store.refresh_ttl(session_id)
            return
        now = _utcnow()
        current_agent_id = self._default_agent_id()
        payload = {
            "session_id": session_id,
            "user_id": user_id,
            "channel": channel,
            "room_id": room_id,
            "current_agent_id": current_agent_id,
            "current_agent_code": None,
            "conversation_history": [],
            "context_entities": {},
            "created_at": now.isoformat(),
            "updated_at": now.isoformat(),
        }
        self.store.set(session_id, payload)