""" backend/app/api/agent_runtime_context_tools.py 用途:暴露 agent_runtime_context 只读 Tool API,供 Dify Chatflow 解析 HXOPS 上下文。 依赖:app.core.errors、agent_runtime_context.parser/openapi_spec、shipping_notice.tool_api_url。 逻辑:OpenAPI 文档接口放行;parse 工具复用 Authorization Bearer / X-Integration-Key 鉴权,不推进业务状态。 """ from __future__ import annotations from flask import Blueprint, current_app, jsonify, request from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError from app.services.agent_runtime_context.openapi_spec import build_agent_runtime_context_openapi_spec from app.services.agent_runtime_context.parser import parse_agent_runtime_context from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url agent_runtime_context_bp = Blueprint("agent_runtime_context_tools", __name__) def _require_tool_auth() -> None: """ 校验 agent_runtime_context Tool API 鉴权 Header。 【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;Dify 请求 parse 工具时由 before_request 自动触发。 核心逻辑:只接受 Authorization Bearer 或 X-Integration-Key,复用 INTEGRATION_API_KEY 作为平台工具密钥。 Raises: ServiceUnavailableError: 未配置 INTEGRATION_API_KEY。 UnauthorizedError: 缺少或传入错误鉴权。 """ configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip() if not configured: raise ServiceUnavailableError("INTEGRATION_API_KEY is not configured", code="missing_auth") bearer = str(request.headers.get("Authorization") or "").strip() token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else "" integration_key = str(request.headers.get("X-Integration-Key") or "").strip() if configured in {token, integration_key}: return if not token and not integration_key: raise UnauthorizedError("missing_auth") raise UnauthorizedError("invalid_auth") def _tool_error_code(exc: AppError) -> str: """ 归一化 Tool API 错误码。 核心逻辑:保持与 shipping/file-check Tool API 的 ok:false 响应风格一致,便于 Dify 侧统一处理。 Args: exc: 业务异常。 Returns: Tool 侧错误码。 """ message = str(exc.message or "").strip() if message in {"missing_auth", "invalid_auth"}: return message if exc.code == "AUTH.UNAUTHORIZED": return "invalid_auth" if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower(): return "missing_auth" return exc.code @agent_runtime_context_bp.errorhandler(AppError) def _handle_tool_app_error(exc: AppError): """把业务异常统一转成 Tool 侧约定的 JSON 结构。""" return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status @agent_runtime_context_bp.before_request def _verify_tool_access(): """ 对上下文解析 Tool 做统一 Header 鉴权。 核心逻辑:OpenAPI 导入文档无需鉴权;parse 工具必须携带平台 Tool Key。 """ if request.path.endswith("/openapi.json"): return None _require_tool_auth() return None @agent_runtime_context_bp.route("/tools/openapi.json", methods=["GET"]) def openapi_spec(): """返回 Dify 导入用的 OpenAPI JSON 文档。""" return jsonify(build_agent_runtime_context_openapi_spec(resolve_tool_api_base_url())) @agent_runtime_context_bp.route("/tools/parse", methods=["POST"]) def parse_context_tool(): """ 解析 agent_runtime_context 的白名单字段。 【AI 触发时机】:Dify 需要读取 HXOPS session/task/batch/run_purpose/state_hint 等上下文字段时调用; 不用于推进业务状态。 """ payload = request.get_json(silent=True) or {} return jsonify( parse_agent_runtime_context( payload.get("agent_runtime_context"), payload.get("paths"), ) )