""" backend/app/services/agent_runtime_binding_service.py 用途:解析、校验和管理 Agent 的命名运行能力 Provider 绑定。 依赖:Agent/AgentRuntimeBinding、Agent Catalog、统一 AppError。 逻辑:Catalog 声明 owner 需要的能力和 Provider 约束;管理员只保存 Agent 外键,运行时禁止名称或环境变量回退。 """ from __future__ import annotations from typing import Any from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import Agent, AgentRuntimeBinding from app.services.agent_registry.catalog import get_catalog_entry from app.services.agent_registry.resolver import resolve_effective_role def _capability_definition(owner: Agent, capability_code: str) -> dict[str, Any]: """读取 owner Agent Catalog 中声明的能力定义;未声明能力不可由管理员任意绑定。""" entry = get_catalog_entry(owner.agent_code) or {} definitions = entry.get('required_runtime_capabilities') definitions = definitions if isinstance(definitions, dict) else {} definition = definitions.get(capability_code) if not isinstance(definition, dict): raise ValidationError( 'Runtime capability is not declared by the Agent Catalog', code='AGENT.RUNTIME_CAPABILITY_NOT_DECLARED', ) return definition def _normalize_config(raw: Any) -> dict[str, Any]: """限制通用超时/重试配置,避免任意 JSON 成为隐式业务配置后门。""" if raw is None: raw = {} if not isinstance(raw, dict): raise ValidationError('config must be an object', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID') unknown = set(raw) - { 'timeout_seconds', 'max_attempts', 'unit_concurrency', 'unit_max_attempts', 'unit_retry_backoff_ms', 'max_model_units', 'provider_max_concurrency', 'circuit_failure_threshold', 'circuit_cooldown_seconds', 'auto_create_enabled', } if unknown: raise ValidationError( 'Unsupported runtime binding config keys', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID', details={'keys': sorted(unknown)}, ) try: timeout_seconds = int(raw.get('timeout_seconds', 900)) max_attempts = int(raw.get('max_attempts', 3)) unit_concurrency = int(raw.get('unit_concurrency', 2)) unit_max_attempts = int(raw.get('unit_max_attempts', 2)) unit_retry_backoff_ms = int(raw.get('unit_retry_backoff_ms', 500)) max_model_units = int(raw.get('max_model_units', 20)) provider_max_concurrency = int(raw.get('provider_max_concurrency', 4)) circuit_failure_threshold = int(raw.get('circuit_failure_threshold', 5)) circuit_cooldown_seconds = int(raw.get('circuit_cooldown_seconds', 60)) auto_create_enabled = raw.get('auto_create_enabled', False) except (TypeError, ValueError) as exc: raise ValidationError( 'Runtime binding execution settings must be integers', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID', ) from exc if not 30 <= timeout_seconds <= 3600 or not 1 <= max_attempts <= 10: raise ValidationError( 'Runtime binding config is outside allowed limits', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID', ) if not 2 <= unit_concurrency <= 4 or not 1 <= unit_max_attempts <= 3: raise ValidationError( 'Runtime binding unit concurrency/attempts are outside allowed limits', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID', ) if not 100 <= unit_retry_backoff_ms <= 5000: raise ValidationError( 'Runtime binding unit retry backoff is outside allowed limits', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID', ) if not 1 <= max_model_units <= 100 or not 1 <= provider_max_concurrency <= 20: raise ValidationError('Runtime binding provider budget is outside allowed limits', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID') if not 2 <= circuit_failure_threshold <= 20 or not 10 <= circuit_cooldown_seconds <= 600: raise ValidationError('Runtime binding circuit settings are outside allowed limits', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID') if not isinstance(auto_create_enabled, bool): raise ValidationError('Runtime binding auto-create gate must be boolean', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID') return { 'timeout_seconds': timeout_seconds, 'max_attempts': max_attempts, 'unit_concurrency': unit_concurrency, 'unit_max_attempts': unit_max_attempts, 'unit_retry_backoff_ms': unit_retry_backoff_ms, 'max_model_units': max_model_units, 'provider_max_concurrency': provider_max_concurrency, 'circuit_failure_threshold': circuit_failure_threshold, 'circuit_cooldown_seconds': circuit_cooldown_seconds, 'auto_create_enabled': auto_create_enabled, } def _validate_provider(provider: Agent, definition: dict[str, Any]) -> None: """按 Catalog 校验 Provider 类型、可见性和 Dify 配置完整性。""" allowed_providers = set(definition.get('allowed_runtime_providers') or []) allowed_app_types = set(definition.get('allowed_dify_app_types') or []) allowed_exposure = set(definition.get('allowed_exposure_modes') or []) allowed_roles = set(definition.get('allowed_effective_roles') or []) if not provider.is_active: raise ConflictError('Runtime provider is disabled', code='AGENT.RUNTIME_PROVIDER_DISABLED') if allowed_providers and provider.runtime_provider not in allowed_providers: raise ValidationError('Runtime provider type is invalid', code='AGENT.RUNTIME_PROVIDER_INVALID') if allowed_app_types and provider.dify_app_type not in allowed_app_types: raise ValidationError('Dify application type is invalid', code='AGENT.RUNTIME_PROVIDER_INVALID') if allowed_exposure and provider.exposure_mode not in allowed_exposure: raise ValidationError('Runtime provider exposure mode is invalid', code='AGENT.RUNTIME_PROVIDER_INVALID') if allowed_roles and resolve_effective_role(provider) not in allowed_roles: raise ValidationError('Runtime provider role is invalid', code='AGENT.RUNTIME_PROVIDER_INVALID') if provider.runtime_provider in {'dify', 'hybrid'} and ( not str(provider.dify_app_id or '').strip() or not str(provider.dify_api_key or '').strip() or not str(provider.api_base_url or '').strip() ): raise ConflictError( 'Runtime provider Dify configuration is incomplete', code='AGENT.RUNTIME_PROVIDER_CONFIG_INCOMPLETE', ) def serialize_runtime_binding(binding: AgentRuntimeBinding) -> dict[str, Any]: """输出管理端安全视图;不返回 Provider API Key。""" provider = binding.provider_agent return { 'id': binding.id, 'owner_agent_id': binding.owner_agent_id, 'capability_code': binding.capability_code, 'provider_agent_id': binding.provider_agent_id, 'provider': { 'id': provider.id, 'name': provider.name, 'runtime_provider': provider.runtime_provider, 'dify_app_type': provider.dify_app_type, 'exposure_mode': provider.exposure_mode, 'is_active': provider.is_active, } if provider else None, 'enabled': bool(binding.enabled), 'config': dict(binding.config_json or {}), } def list_runtime_bindings(owner_agent_id: int) -> list[dict[str, Any]]: """列出指定 owner Agent 的全部显式运行能力绑定。""" owner = db.session.get(Agent, owner_agent_id) if owner is None: raise NotFoundError('Agent not found') rows = AgentRuntimeBinding.query.filter_by(owner_agent_id=owner.id).order_by( AgentRuntimeBinding.capability_code.asc(), ).all() return [serialize_runtime_binding(row) for row in rows] def save_runtime_binding( *, owner_agent_id: int, capability_code: str, provider_agent_id: int, enabled: bool, config: Any, commit: bool = True, ) -> AgentRuntimeBinding: """创建或更新能力绑定;owner/provider 必须是不同 Agent 且满足 Catalog 约束。""" owner = db.session.get(Agent, owner_agent_id) provider = db.session.get(Agent, provider_agent_id) if owner is None or provider is None: raise NotFoundError('Agent not found') code = str(capability_code or '').strip() if owner.id == provider.id: raise ValidationError('Owner and provider must be different Agents', code='AGENT.RUNTIME_PROVIDER_INVALID') definition = _capability_definition(owner, code) if enabled: _validate_provider(provider, definition) normalized_config = _normalize_config(config) binding = AgentRuntimeBinding.query.filter_by( owner_agent_id=owner.id, capability_code=code, ).first() if binding is None: binding = AgentRuntimeBinding(owner_agent_id=owner.id, capability_code=code) db.session.add(binding) binding.provider_agent_id = provider.id binding.enabled = bool(enabled) binding.config_json = normalized_config if commit: db.session.commit() else: db.session.flush() return binding def resolve_runtime_binding(*, owner_agent_id: int, capability_code: str) -> AgentRuntimeBinding: """运行时解析启用绑定并复检 Provider;未配置时明确阻断,禁止任何隐式回退。""" binding = AgentRuntimeBinding.query.filter_by( owner_agent_id=owner_agent_id, capability_code=capability_code, enabled=True, ).first() if binding is None: raise ConflictError( 'Runtime capability provider is not configured', code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_NOT_CONFIGURED', ) definition = _capability_definition(binding.owner_agent, capability_code) _validate_provider(binding.provider_agent, definition) return binding