""" backend/app/services/agent_user_access.py 用途:统一约束哪些 Agent 可以进入用户授权、工作台和普通对话链路。 依赖:SQLAlchemy Session、Agent/User 模型、统一业务异常。 逻辑:内部执行器只允许 Runtime Binding 后台调用;所有用户入口仅接受 workspace 应用。 """ from __future__ import annotations from collections.abc import Iterable from app import db from app.core.errors import ForbiddenError, NotFoundError, ValidationError from app.models import Agent, User USER_ACCESS_FORBIDDEN_CODE = 'AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN' def is_user_application(agent: Agent | None, *, require_active: bool = False) -> bool: """判断 Agent 是否可进入用户侧;可选同时要求启用状态。""" if agent is None or agent.exposure_mode != 'workspace': return False return bool(agent.is_active) if require_active else True def load_grantable_agents(agent_ids: Iterable[object] | None) -> list[Agent]: """ 加载可授予用户的应用并保持输入顺序。 参数约束:所有 ID 必须存在且属于 workspace;内部执行器不得被授权给任何用户。 """ if agent_ids is not None and not isinstance(agent_ids, (list, tuple, set)): raise ValidationError('agent_ids must be an array') raw_ids = list(agent_ids or []) try: normalized_ids = list(dict.fromkeys(int(agent_id) for agent_id in raw_ids)) except (TypeError, ValueError) as exc: raise ValidationError('agent_ids must be an integer array') from exc if not normalized_ids: return [] agents = db.session.query(Agent).filter(Agent.id.in_(normalized_ids)).all() by_id = {agent.id: agent for agent in agents} missing_ids = [agent_id for agent_id in normalized_ids if agent_id not in by_id] if missing_ids: raise ValidationError('Some agent_ids are invalid', details={'agent_ids': missing_ids}) internal_ids = [agent_id for agent_id in normalized_ids if not is_user_application(by_id[agent_id])] if internal_ids: raise ValidationError( 'Internal executors cannot be assigned to users', code=USER_ACCESS_FORBIDDEN_CODE, details={'agent_ids': internal_ids}, ) return [by_id[agent_id] for agent_id in normalized_ids] def require_user_application(agent: Agent | None, *, require_active: bool = False) -> Agent: """要求目标是 workspace 应用;用户入口可额外要求启用状态。""" if agent is None or (require_active and not agent.is_active): raise NotFoundError('Agent not found') if not is_user_application(agent): raise ForbiddenError( 'Internal executors are unavailable from user-facing APIs', code=USER_ACCESS_FORBIDDEN_CODE, ) return agent def require_user_application_access(agent: Agent | None, user: User) -> Agent: """ 校验普通用户入口的 Agent 访问。 核心逻辑:先阻断停用项和内部执行器,再处理管理员全 workspace 可见、普通用户按授权可见。 """ agent = require_user_application(agent, require_active=True) if user.role != 'admin' and agent not in user.agents: raise ForbiddenError('Permission denied for this agent') return agent def visible_default_agent_id(user: User) -> int | None: """返回可用于用户入口的默认应用 ID;历史内部执行器引用按未配置处理。""" if user.default_agent_id is None: return None agent = db.session.get(Agent, user.default_agent_id) if not is_user_application(agent, require_active=True): return None if user.role != 'admin' and agent not in user.agents: return None return int(agent.id) def visible_agent_ids(user: User, *, active_only: bool = True) -> set[int]: """返回当前用户在用户侧实际可见的应用 ID 集合。""" if user.role == 'admin': query = db.session.query(Agent.id).filter(Agent.exposure_mode == 'workspace') if active_only: query = query.filter(Agent.is_active.is_(True)) return {int(row[0]) for row in query.all()} return { int(agent.id) for agent in user.agents if is_user_application(agent, require_active=active_only) }