diff --git a/main/live-agent-api/schemas/device.py b/main/live-agent-api/schemas/device.py index d8f6d931e..643e4697c 100644 --- a/main/live-agent-api/schemas/device.py +++ b/main/live-agent-api/schemas/device.py @@ -1,8 +1,6 @@ from datetime import datetime from typing import Optional, List -from typing import Literal from pydantic import BaseModel, Field -from schemas.agent import AgentConfigResponse # ==================== Request Schemas ==================== @@ -60,20 +58,3 @@ class DeviceBoundAgentsResponse(BaseModel): device_id: str agents: List[AgentBindingResponse] = [] - -class DeviceAgentResolveResponse(BaseModel): - """Resolve agent for device by wake word or default""" - device_id: str - agent_id: str - owner_id: Optional[str] = None # Device owner's user_id for memory storage - is_default: bool - match_type: Literal["wake_word", "default"] - agent_config: AgentConfigResponse - - -class DefaultAgentResponse(BaseModel): - """Default agent for a device""" - device_id: str - agent: AgentConfigResponse - is_default: bool = True - diff --git a/main/xiaozhi-server/config/live_agent_api_client.py b/main/xiaozhi-server/config/live_agent_api_client.py index cabcd17a2..d526fd380 100644 --- a/main/xiaozhi-server/config/live_agent_api_client.py +++ b/main/xiaozhi-server/config/live_agent_api_client.py @@ -5,10 +5,12 @@ Features: 1. Singleton pattern ensures global unique httpx.Client instance 2. Connection pool reuse for better performance 3. Thread-safe for concurrent requests +4. JWT token parsing for user_id extraction """ import os import httpx +import jwt from config.logger import setup_logging from typing import Optional, List, Dict @@ -20,6 +22,7 @@ class LiveAgentApiClient: _instance = None _client: httpx.Client = None _base_url: str = None + _secret_key: str = None # JWT secret key for token parsing def __new__(cls, config: dict = None): """Singleton pattern ensures global unique instance""" @@ -35,6 +38,7 @@ class LiveAgentApiClient: """Initialize persistent connection pool""" live_api_config = config.get("live-agent-api", {}) cls._base_url = live_api_config.get("url", "http://live-agent-api:8080/api/live_agent/v1") + cls._secret_key = live_api_config.get("secret_key") timeout = live_api_config.get("timeout", 30) cls._client = httpx.Client( @@ -47,6 +51,8 @@ class LiveAgentApiClient: timeout=timeout, ) logger.info(f"LiveAgentApiClient initialized: {cls._base_url}") + if cls._secret_key: + logger.info("JWT secret_key configured for user_id extraction") @classmethod def _request(cls, method: str, endpoint: str, **kwargs) -> dict: @@ -212,3 +218,54 @@ def report_chat_message( def live_agent_api_safe_close(): """Safe close for shutdown""" LiveAgentApiClient.safe_close() + + +def extract_user_id_from_jwt(token: str, config: dict = None) -> Optional[str]: + """ + Extract user_id from live-agent-api JWT token. + + This allows xiaozhi-server to identify the user from the Bearer token + passed by the App, enabling proper memory initialization with user_id. + + Args: + token: JWT token string (with or without 'Bearer ' prefix) + config: System config (optional if client already initialized) + + Returns: + user_id string if extraction successful, None otherwise + """ + try: + # Ensure client is initialized to get secret_key + if LiveAgentApiClient._instance is None: + if config is None: + logger.warning("LiveAgentApiClient not initialized, cannot extract user_id from JWT") + return None + LiveAgentApiClient(config) + + secret_key = LiveAgentApiClient._secret_key + if not secret_key: + logger.debug("No secret_key configured, skipping JWT user_id extraction") + return None + + # Remove 'Bearer ' prefix if present + if token.startswith("Bearer "): + token = token[7:] + + # Decode JWT token + payload = jwt.decode(token, secret_key, algorithms=['HS256']) + user_id = payload.get('user_id') + + if user_id: + logger.debug(f"Successfully extracted user_id from JWT: {user_id[:20]}...") + + return user_id + + except jwt.ExpiredSignatureError: + logger.debug("JWT token expired, cannot extract user_id") + return None + except jwt.InvalidTokenError as e: + logger.debug(f"Invalid JWT token: {e}") + return None + except Exception as e: + logger.warning(f"Failed to extract user_id from JWT: {e}") + return None diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 957537997..865611d8e 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -46,6 +46,7 @@ from core.utils import textUtils from config.live_agent_api_client import ( get_agent_config_from_api, get_agent_by_wake_from_api, + extract_user_id_from_jwt, ) TAG = __name__ @@ -195,6 +196,17 @@ class ConnectionHandler: self.device_id = self.headers.get("device-id", None) self.agent_id = self.headers.get("agent-id", None) + + # Extract user_id from JWT token (if live-agent-api secret_key configured) + # This enables proper memory initialization with the real user identity + auth_header = self.headers.get("authorization", "") + if auth_header and self.read_config_from_live_agent_api: + jwt_user_id = extract_user_id_from_jwt(auth_header, self.config) + if jwt_user_id: + self.owner_id = jwt_user_id + self.logger.bind(tag=TAG).info( + f"Extracted owner_id from JWT: {jwt_user_id[:20]}..." + ) # 认证通过,继续处理 self.websocket = ws @@ -257,6 +269,7 @@ class ConnectionHandler: context = { "session_id": self.session_id, "device_id": self.device_id, + "user_id": self.owner_id, # 设备所有者的 user_id "mac_address": getattr(self, 'mac_address', None), "agent_id": getattr(self, 'agent_id', None), } @@ -969,7 +982,9 @@ class ConnectionHandler: self.need_bind = True return False self.agent_id = resolved.get("agent_id") - self.owner_id = resolved.get("owner_id") # Device owner's user_id + # Only set owner_id from API if not already extracted from JWT + if not self.owner_id: + self.owner_id = resolved.get("owner_id") # Device owner's user_id private_config = resolved.get("agent_config") if private_config is None: diff --git a/main/xiaozhi-server/core/providers/memory/memu/memu.py b/main/xiaozhi-server/core/providers/memory/memu/memu.py index 3bb4b09bf..0b075726a 100644 --- a/main/xiaozhi-server/core/providers/memory/memu/memu.py +++ b/main/xiaozhi-server/core/providers/memory/memu/memu.py @@ -137,6 +137,8 @@ class MemoryProvider(MemoryProviderBase): context_info["mac_address"] = context["mac_address"] if "device_id" in context: context_info["device_id"] = context["device_id"] + if "user_id" in context: + context_info["user_id"] = context["user_id"] if "agent_id" in context and context["agent_id"]: agent_id = context["agent_id"] context_info["agent_id"] = agent_id @@ -153,7 +155,7 @@ class MemoryProvider(MemoryProviderBase): agent_name=self.agent_name, session_date=session_date ) - logger.bind(tag=TAG).info(f"保存记忆成功,context: {context_info}, session_date: {session_date}") + logger.bind(tag=TAG).info(f"保存记忆成功,user_id: {self.role_id}, agent_id: {agent_id}, context: {context_info}, session_date: {session_date}") logger.bind(tag=TAG).debug(f"Save memory result: {result}") except Exception as e: logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}") diff --git a/main/xiaozhi-server/custom_config.yaml b/main/xiaozhi-server/custom_config.yaml index bcf34a877..dc5609035 100644 --- a/main/xiaozhi-server/custom_config.yaml +++ b/main/xiaozhi-server/custom_config.yaml @@ -35,6 +35,8 @@ manager-api: live-agent-api: url: http://live-agent-api:8080/api/live_agent/v1 chat_history_conf: 2 + # JWT secret key for extracting user_id from App token (shared with live-agent-api) + secret_key: ${SECRET_KEY:-} # MySQL配置(用于聊天记录和记忆关联) mysql: