""" backend/app/services/agent_registry/admin_payload.py 用途:Admin Agent CRUD 载荷校验、列写入与 extra_config 已迁移键清理。 依赖:agent_registry.catalog、agent_registry.resolver.normalize_capabilities。 逻辑:agent_service.create/update 调用;校验 agent_code Catalog 与 provider 枚举。 """ from __future__ import annotations from typing import Any from app.core.errors import ValidationError from app.models import Agent from app.services.agent_registry.catalog import get_catalog_entry, list_agent_type_codes from app.services.agent_registry.catalog_loader import ( coerce_manifest_boolean, get_dify_required_providers, get_platform_enum_set, ) from app.services.agent_registry.catalog_validation import ( apply_catalog_capabilities, catalog_progress_requires_schedule_task, default_capabilities_copy, normalize_handler_config, validate_required_fields, ) from app.services.agent_registry.content_profiles import VALID_CONTENT_PROFILES from app.services.agent_registry.intent_routes import validate_intent_routes from app.services.agent_registry.resolver import normalize_capabilities # 曾 mirror 到 extra_config 的 Registry 键;Admin save 时清理(保留 training_* 等实验字段)。 MIGRATED_EXTRA_REGISTRY_KEYS = frozenset({ 'agent_code', 'runtime_provider', 'conversation_mode', 'dify_app_type', 'iframe_url', 'category', 'sub_category', 'sort_order', 'welcome_message', 'suggested_questions_style', 'suggested_questions', 'capabilities', 'tool_run_progress', 'is_aggregate', }) def _strip(value: Any) -> str: return str(value or '').strip() def _legacy_type_from_provider(runtime_provider: str) -> str: return 'iframe' if runtime_provider == 'iframe' else 'api' def _parse_capabilities(raw: Any) -> dict[str, bool]: if isinstance(raw, dict): return normalize_capabilities(raw, strict=True) return normalize_capabilities(None, strict=True) def _parse_is_active(raw: Any, *, default: bool) -> bool: """Admin is_active 布尔归一化;支持字符串 false/true。""" if raw is None: return default return coerce_manifest_boolean(raw, context='is_active') def _parse_is_aggregate(raw: Any, *, default: bool) -> bool: """Admin is_aggregate 布尔归一化;只有为 true 时才保留目录成员配置。""" if raw is None: return default return coerce_manifest_boolean(raw, context='is_aggregate') def _parse_bound_schedule_task_id(raw: Any) -> int | None: if raw is None or raw == '': return None try: task_id = int(raw) except (TypeError, ValueError): raise ValidationError('bound_schedule_task_id 必须为有效整数') return task_id if task_id > 0 else None def _parse_handler_config( raw: Any, *, agent_code: str, existing: dict | None = None, explicit: bool = False, ) -> dict | None: """ 归一化 handler_config。 Args: raw: 请求值;None 且 explicit=True 表示显式清空。 explicit: True 表示请求体包含 handler_config 键(含 null)。 """ if raw is None: if explicit: return normalize_handler_config(agent_code, None) return existing if isinstance(existing, dict) else None if not isinstance(raw, dict): raise ValidationError('handler_config 必须为 JSON 对象') if explicit: merged = dict(raw) else: merged = dict(existing or {}) merged.update(raw) if 'intent_routes' in raw: from app.services.chat.intent_route_registry import ensure_intent_routes_loaded ensure_intent_routes_loaded() merged['intent_routes'] = validate_intent_routes(raw.get('intent_routes')) if 'content_profile' in raw: profile = _strip(raw.get('content_profile')) if profile and profile not in VALID_CONTENT_PROFILES: raise ValidationError(f'无效的 handler_config.content_profile: {profile}') merged['content_profile'] = profile or None return normalize_handler_config(agent_code, merged) def validate_agent_payload( data: dict[str, Any], *, agent: Agent | None = None, provided_fields: frozenset[str] | None = None, ) -> dict[str, Any]: """ 校验并归一化 Admin Agent 创建/更新载荷。 Args: data: 请求 JSON(update 时为 merged 载荷)。 agent: 更新时的现有 Agent;创建时为 None。 provided_fields: 更新时原始请求体包含的键;用于区分未传字段与显式 null。 Returns: 归一化后的字段 dict,供 apply_agent_payload 写入 ORM。 Raises: ValidationError: agent_code / provider / file_check 绑定等校验失败。 """ if not _strip(data.get('name')): raise ValidationError('Name is required') valid_runtime_providers = get_platform_enum_set('runtime_providers') valid_conversation_modes = get_platform_enum_set('conversation_modes') valid_dify_app_types = get_platform_enum_set('dify_app_types') valid_suggested_styles = get_platform_enum_set('suggested_questions_styles') dify_required_providers = get_dify_required_providers() agent_code = _strip(data.get('agent_code')) or (agent.agent_code if agent else 'generic') if agent_code not in list_agent_type_codes(): raise ValidationError(f'无效的应用类型 agent_code: {agent_code}') runtime_provider = _strip(data.get('runtime_provider')) or (agent.runtime_provider if agent else '') if not runtime_provider: catalog = get_catalog_entry(agent_code) or {} runtime_provider = _strip(catalog.get('runtime_provider_default')) or 'dify' if runtime_provider not in valid_runtime_providers: raise ValidationError(f'无效的 runtime_provider: {runtime_provider}') conversation_mode = _strip(data.get('conversation_mode')) or (agent.conversation_mode if agent else '') if not conversation_mode: catalog = get_catalog_entry(agent_code) or {} conversation_mode = _strip(catalog.get('conversation_mode_default')) or 'chat' if conversation_mode not in valid_conversation_modes: raise ValidationError(f'无效的 conversation_mode: {conversation_mode}') dify_app_type = _strip(data.get('dify_app_type')) or (getattr(agent, 'dify_app_type', None) if agent else 'chatflow') or 'chatflow' if dify_app_type not in valid_dify_app_types: dify_app_type = 'chatflow' dify_app_id = _strip(data.get('dify_app_id')) or (agent.dify_app_id if agent else '') if runtime_provider in dify_required_providers and not dify_app_id: raise ValidationError('runtime_provider 含 dify 时 dify_app_id 必填') iframe_url = _strip(data.get('iframe_url')) or (getattr(agent, 'iframe_url', None) if agent else None) if runtime_provider == 'iframe' and not iframe_url: raise ValidationError('runtime_provider=iframe 时 iframe_url 必填') bound_schedule_task_id = data.get('bound_schedule_task_id', getattr(agent, 'bound_schedule_task_id', None) if agent else None) bound_schedule_task_id = _parse_bound_schedule_task_id(bound_schedule_task_id) if not catalog_progress_requires_schedule_task(agent_code): bound_schedule_task_id = None capabilities = _parse_capabilities(data.get('capabilities', getattr(agent, 'capabilities', None) if agent else None)) capabilities = apply_catalog_capabilities(agent_code, capabilities) validate_required_fields(agent_code, bound_schedule_task_id=bound_schedule_task_id) handler_explicit = ( 'handler_config' in provided_fields if provided_fields is not None else 'handler_config' in data ) existing_handler = ( getattr(agent, 'handler_config', None) if agent and isinstance(getattr(agent, 'handler_config', None), dict) else None ) handler_config = _parse_handler_config( data.get('handler_config') if handler_explicit else None, agent_code=agent_code, existing=existing_handler, explicit=handler_explicit, ) if handler_config is not None and not isinstance(handler_config, dict): raise ValidationError('handler_config 必须为 JSON 对象') suggested_style = _strip(data.get('suggested_questions_style')) or ( getattr(agent, 'suggested_questions_style', None) if agent else 'plain' ) or 'plain' if suggested_style not in valid_suggested_styles: suggested_style = 'plain' suggested_questions = data.get('suggested_questions', getattr(agent, 'suggested_questions', None) if agent else None) if suggested_questions is not None and not isinstance(suggested_questions, list): raise ValidationError('suggested_questions 必须为数组') sort_raw = data.get('sort_order', getattr(agent, 'sort_order', 0) if agent else 0) try: sort_order = int(sort_raw) except (TypeError, ValueError): sort_order = 0 if sort_order < 0: sort_order = 0 file_upload_policy = data.get('file_upload_policy', getattr(agent, 'file_upload_policy', None) if agent else None) if file_upload_policy is not None and not isinstance(file_upload_policy, dict): raise ValidationError('file_upload_policy 必须为 JSON 对象') is_active_default = agent.is_active if agent else True is_active = ( _parse_is_active(data.get('is_active'), default=is_active_default) if 'is_active' in data else is_active_default ) is_aggregate_default = bool(getattr(agent, 'is_aggregate', False)) if agent else False is_aggregate = ( _parse_is_aggregate(data.get('is_aggregate'), default=is_aggregate_default) if 'is_aggregate' in data else is_aggregate_default ) return { 'name': _strip(data.get('name')), 'description': data.get('description'), 'icon_url': data.get('icon_url'), 'is_active': is_active, 'is_aggregate': is_aggregate, 'dify_app_id': dify_app_id or None, 'dify_api_key': _strip(data.get('dify_api_key')) or None, 'api_base_url': _strip(data.get('api_base_url')) or None, 'type': _legacy_type_from_provider(runtime_provider), 'agent_code': agent_code, 'runtime_provider': runtime_provider, 'conversation_mode': conversation_mode, 'dify_app_type': dify_app_type, 'iframe_url': iframe_url or None, 'category': _strip(data.get('category')) or None, 'sub_category': _strip(data.get('sub_category')) or None, 'sort_order': sort_order, 'welcome_message': data.get('welcome_message'), 'suggested_questions_style': suggested_style, 'suggested_questions': suggested_questions, 'capabilities': capabilities, 'file_upload_policy': file_upload_policy, 'bound_schedule_task_id': bound_schedule_task_id, 'handler_config': handler_config, 'extra_config': data.get('extra_config') if isinstance(data.get('extra_config'), dict) else None, } def apply_agent_payload(agent: Agent, normalized: dict[str, Any]) -> None: """ 将归一化载荷写入 Agent ORM,并清理 extra_config 中已迁移 Registry 键。 Args: agent: 目标 Agent 实例。 normalized: validate_agent_payload 的返回值。 """ column_fields = ( 'name', 'description', 'icon_url', 'is_active', 'is_aggregate', 'dify_app_id', 'api_base_url', 'type', 'agent_code', 'runtime_provider', 'conversation_mode', 'dify_app_type', 'iframe_url', 'category', 'sub_category', 'sort_order', 'welcome_message', 'suggested_questions_style', 'suggested_questions', 'capabilities', 'file_upload_policy', 'bound_schedule_task_id', 'handler_config', ) for key in column_fields: if key in normalized: setattr(agent, key, normalized[key]) if normalized.get('dify_api_key'): agent.dify_api_key = normalized['dify_api_key'] if normalized.get('extra_config') is not None: agent.extra_config = normalized['extra_config'] strip_migrated_extra_registry_keys(agent) def strip_migrated_extra_registry_keys(agent: Agent) -> None: """ 从 extra_config 移除已迁移至结构化列的 mirror 键。 保留 training_* 等未结构化实验字段;不再向 extra 写入 Registry 列。 """ extra = dict(agent.extra_config or {}) if isinstance(agent.extra_config, dict) else {} for key in MIGRATED_EXTRA_REGISTRY_KEYS: extra.pop(key, None) agent.extra_config = extra or None def default_capabilities() -> dict[str, bool]: """返回 capabilities 默认 schema 副本。""" return default_capabilities_copy()