Files
syops/backend/app/services/agent_runtime_binding_service.py
T

220 lines
10 KiB
Python

"""
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
_EXECUTOR_GOVERNANCE_DEFAULTS = {
'provider_max_concurrency': 4,
'circuit_failure_threshold': 5,
'circuit_cooldown_seconds': 60,
}
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', '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))
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',
)
result = {
'timeout_seconds': timeout_seconds,
'max_attempts': max_attempts,
}
if 'auto_create_enabled' in raw:
if not isinstance(raw['auto_create_enabled'], bool):
raise ValidationError('auto_create_enabled must be boolean', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID')
result['auto_create_enabled'] = raw['auto_create_enabled']
return result
def resolve_executor_governance(provider: Agent) -> dict[str, int]:
"""读取内部执行器全局治理,供新 Run 冻结并避免入口应用绕过 Provider 保护。"""
raw_extra = provider.extra_config if isinstance(provider.extra_config, dict) else {}
raw = raw_extra.get('order_extraction_governance') if isinstance(raw_extra.get('order_extraction_governance'), dict) else {}
try:
config = {
'provider_max_concurrency': int(raw.get('provider_max_concurrency', _EXECUTOR_GOVERNANCE_DEFAULTS['provider_max_concurrency'])),
'circuit_failure_threshold': int(raw.get('circuit_failure_threshold', _EXECUTOR_GOVERNANCE_DEFAULTS['circuit_failure_threshold'])),
'circuit_cooldown_seconds': int(raw.get('circuit_cooldown_seconds', _EXECUTOR_GOVERNANCE_DEFAULTS['circuit_cooldown_seconds'])),
}
except (TypeError, ValueError) as exc:
raise ValidationError('Internal executor governance settings must be integers', code='AGENT.EXECUTOR_GOVERNANCE_INVALID') from exc
if not 1 <= config['provider_max_concurrency'] <= 20:
raise ValidationError('Internal executor concurrency is outside allowed limits', code='AGENT.EXECUTOR_GOVERNANCE_INVALID')
if not 2 <= config['circuit_failure_threshold'] <= 20 or not 10 <= config['circuit_cooldown_seconds'] <= 600:
raise ValidationError('Internal executor circuit settings are outside allowed limits', code='AGENT.EXECUTOR_GOVERNANCE_INVALID')
return config
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),
'quality_batch_id': binding.quality_batch_id,
'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,
quality_batch_id: int | None = None,
config: Any,
commit: bool = True,
) -> AgentRuntimeBinding:
"""创建或更新能力绑定;开启自动建单时必须引用已批准质量批次。"""
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)
if code == 'shipping.order_extraction' and normalized_config.get('auto_create_enabled'):
from app.services.shipping_notice.order_extraction_quality_service import require_approved_quality_batch
from app.services.shipping_notice.order_schema.runtime import published_version
require_approved_quality_batch(
batch_id=quality_batch_id,
owner_agent_id=owner.id,
schema_version_id=int(published_version().id),
)
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.quality_batch_id = int(quality_batch_id) if quality_batch_id is not None else None
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