feat(file-check): 新增文件检核相关 API 和工具,替换 RoHS 检核功能

This commit is contained in:
hugo committed 2026-06-16 09:28:37 +08:00
1 parent fa0cdee8df
commit 24310b63b3
35 files changed
+3066 -659

No files matched your search

@@ -0,0 +1 @@
"""文件检核 Chatflow 工具包。"""
@@ -0,0 +1,60 @@
"""
services/file_check_tools/agent_resolver.py
用途:识别具备文件检核进度能力的对话 Agent。
依赖:Agent.extra_config(capabilities + tool_run_progress.schedule_task_id)。
逻辑:chat.py / dify.py / user.py 通过 capabilities 驱动;agent_declares_file_check_progress 用于缺参时快速失败。
"""
from __future__ import annotations
from app.models import Agent
def _resolve_task_id_from_mapping(mapping: dict | None) -> int | None:
if not isinstance(mapping, dict):
return None
raw = mapping.get("schedule_task_id", mapping.get("task_id"))
try:
task_id = int(raw)
except (TypeError, ValueError):
return None
return task_id if task_id > 0 else None
def _extra_dict(agent) -> dict:
extra = getattr(agent, "extra_config", None) or {}
return extra if isinstance(extra, dict) else {}
def agent_declares_file_check_progress(agent) -> bool:
"""
判断 Agent 是否声明了文件检核进度能力(不要求 schedule_task_id 已配齐)。
用途:识别「已声明 tool_run_progress 但未配置 task_id」的 Agent,在调 Dify 前快速报错。
"""
extra = _extra_dict(agent)
caps = extra.get("capabilities") or []
if isinstance(caps, list) and "tool_run_progress" in caps:
return True
return isinstance(extra.get("tool_run_progress"), dict)
def is_file_check_chat_agent(agent) -> bool:
"""
判断 Agent 是否为文件检核对话入口。
核心逻辑:extra_config.capabilities 含 tool_run_progress,且配置了 schedule_task_id。
"""
extra = _extra_dict(agent)
if not agent_declares_file_check_progress(agent):
return False
tool_cfg = extra.get("tool_run_progress")
if isinstance(tool_cfg, dict) and _resolve_task_id_from_mapping(tool_cfg):
return True
return bool(_resolve_task_id_from_mapping(extra))
def resolve_chat_agent() -> Agent | None:
"""返回第一个具备文件检核进度能力的活跃 Agent(测试/运维辅助)。"""
rows = Agent.query.filter(Agent.is_active.is_(True)).order_by(Agent.id.asc()).all()
return next((row for row in rows if is_file_check_chat_agent(row)), None)
@@ -0,0 +1,181 @@
"""
services/file_check_tools/chat_log_run_binding.py
用途:将文件检核批次 ID 写入 ChatLog.run_id(按轮问答绑定)。
依赖:ChatLog、ScheduleRun、chat_turn_registry。
逻辑:启动检核 API 写入 ScheduleRun.api_request_json;message_end 落 ChatLog 时解析并绑定 run_id。
"""
from __future__ import annotations
import re
from datetime import datetime, timedelta
from typing import Any
from flask import current_app
from app import db
from app.models import ChatLog, ScheduleRun
from app.services.file_check_tools.chat_turn_registry import (
attach_run_to_turn,
resolve_run_id_by_session_query,
resolve_run_id_by_turn,
)
def _normalize_bind_text(text: str | None) -> str:
"""折叠空白,便于 user_message 与 ChatLog.query 对齐。"""
return re.sub(r"\s+", " ", str(text or "").strip())
def merge_chat_log_bind_context(run: ScheduleRun | None, data: dict[str, Any] | None) -> None:
"""
在 ScheduleRun 上记录本轮问答的绑定上下文,供 ChatLog 落库时匹配。
Args:
run: 新建或复用的检核批次。
data: 启动检核 HTTP Body。
"""
if not run:
return
payload = data if isinstance(data, dict) else {}
session_id = str(payload.get("hxops_session_id") or "").strip()
turn_id = str(payload.get("hxops_turn_id") or "").strip()
user_message = str(payload.get("user_message") or "").strip()
if not session_id and not turn_id and not user_message:
return
req = dict(run.api_request_json or {}) if isinstance(run.api_request_json, dict) else {}
if session_id:
req["bind_session_id"] = session_id
req["hxops_session_id"] = session_id
if turn_id:
req["bind_turn_id"] = turn_id
req["hxops_turn_id"] = turn_id
if user_message:
req["bind_user_message"] = user_message
req["user_message"] = user_message
if payload.get("conversation_id"):
req["conversation_id"] = payload.get("conversation_id")
req["bind_requested_at"] = datetime.utcnow().isoformat()
run.api_request_json = req
def resolve_run_id_for_chat_log(
*,
session_id: str | None = None,
query: str | None = None,
turn_id: str | None = None,
) -> int | None:
"""
匹配本轮问答应对绑定的检核批次 ID。
优先级:hxops_turn_id > session_id + 归一化 query > session_id + 近期 bind。
Returns:
匹配到的 ScheduleRun.id,或 None。
"""
session_key = str(session_id or "").strip()
turn_key = str(turn_id or "").strip()
query_key = _normalize_bind_text(query)
rows = (
ScheduleRun.query.order_by(ScheduleRun.id.desc())
.limit(120)
.all()
)
def _req(run: ScheduleRun) -> dict:
return run.api_request_json if isinstance(run.api_request_json, dict) else {}
if turn_key:
registry_run_id = resolve_run_id_by_turn(turn_key)
if registry_run_id:
return registry_run_id
for run in rows:
req = _req(run)
bind_turn = str(req.get("bind_turn_id") or req.get("hxops_turn_id") or "").strip()
if bind_turn == turn_key:
return int(run.id)
if session_key and query_key:
for run in rows:
req = _req(run)
bind_session = str(req.get("bind_session_id") or req.get("hxops_session_id") or "").strip()
bind_query = _normalize_bind_text(req.get("bind_user_message") or req.get("user_message"))
if bind_session == session_key and bind_query == query_key:
return int(run.id)
if session_key and query_key:
for run in rows:
req = _req(run)
bind_session = str(req.get("bind_session_id") or req.get("hxops_session_id") or "").strip()
bind_query = _normalize_bind_text(req.get("bind_user_message") or req.get("user_message"))
if bind_session == session_key and bind_query and (
query_key in bind_query or bind_query in query_key
):
return int(run.id)
if session_key:
cutoff = datetime.utcnow() - timedelta(minutes=15)
for run in rows:
req = _req(run)
bind_session = str(req.get("bind_session_id") or req.get("hxops_session_id") or "").strip()
if bind_session != session_key:
continue
bind_at_raw = str(req.get("bind_requested_at") or run.started_at or "")
try:
bind_at = datetime.fromisoformat(bind_at_raw.replace("Z", ""))
except ValueError:
bind_at = run.started_at
if bind_at and bind_at >= cutoff and run.status == "running":
return int(run.id)
registry_run_id = resolve_run_id_by_session_query(session_key, query_key)
if registry_run_id:
return registry_run_id
if current_app and (turn_key or session_key):
current_app.logger.warning(
"[file-check-bind] resolve run_id miss turn_id=%s session_id=%s query_len=%s",
turn_key or None,
session_key or None,
len(query_key),
)
return None
def update_chat_log_run_id(chat_log_id: int, run_id: int | None) -> bool:
"""回写已有 ChatLog.run_id(workflow_finished 二次绑定)。"""
if not chat_log_id or not run_id or run_id <= 0:
return False
log = db.session.get(ChatLog, chat_log_id)
if not log:
return False
if log.run_id == run_id:
return True
run = db.session.get(ScheduleRun, run_id)
if not run:
return False
log.run_id = run_id
db.session.commit()
return True
def bind_run_id_to_chat_log(*, chat_log: ChatLog | None, run_id: int | None) -> bool:
"""将检核批次 ID 写入 ChatLog.run_id。"""
if not chat_log or not run_id or run_id <= 0:
return False
run = db.session.get(ScheduleRun, run_id)
if not run:
return False
chat_log.run_id = run_id
db.session.commit()
return True
__all__ = [
"bind_run_id_to_chat_log",
"merge_chat_log_bind_context",
"resolve_run_id_for_chat_log",
"update_chat_log_run_id",
]
@@ -0,0 +1,44 @@
"""
services/file_check_tools/chat_log_run_resolver.py
用途:按 ChatLog.run_id 解析文件检核进度(按轮问答)。
依赖:ChatLog、ScheduleRun。
逻辑:由 for-log API 调用;run_id 在 message_end 写入 chat_logs 表。
"""
from __future__ import annotations
from app import db
from app.models import ChatLog, ScheduleRun
def find_run_for_chat_log(
*,
task_id: int,
chat_log_id: int,
) -> ScheduleRun | None:
"""
查询某条问答记录绑定的检核批次。
Args:
task_id: ScheduleTask.id。
chat_log_id: ChatLog.id。
Returns:
绑定的 ScheduleRun,或 None。
"""
if chat_log_id <= 0 or task_id <= 0:
return None
log = db.session.get(ChatLog, chat_log_id)
if not log or not log.run_id:
return None
run = db.session.get(ScheduleRun, log.run_id)
if run and run.schedule_task_id == task_id:
return run
return None
__all__ = [
"find_run_for_chat_log",
]
@@ -0,0 +1,217 @@
"""
services/file_check_tools/chat_turn_registry.py
用途:文件检核对话轮次与检核批次的内存注册表(HXOPS 侧登记 turn,不依赖 Dify HTTP 传参)。
依赖:threading、datetime。
逻辑:chat.py 发消息时 register;run API 推断绑定并 attach_run;message_end 按 turn_id 解析 run_id。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from datetime import datetime, timedelta
from threading import Lock
from typing import Any
_REGISTRY_TTL = timedelta(hours=2)
_MAX_ENTRIES = 500
def _normalize_text(text: str | None) -> str:
"""折叠空白,便于 query / user_message 对齐。"""
return re.sub(r"\s+", " ", str(text or "").strip())
@dataclass
class FileCheckChatTurn:
"""单轮文件检核对话的绑定上下文。"""
turn_id: str
session_id: str
user_id: int
agent_id: int
query: str
created_at: datetime
run_id: int | None = None
_lock = Lock()
_turns_by_id: dict[str, FileCheckChatTurn] = {}
def _prune_locked(now: datetime | None = None) -> None:
"""清理过期或超量的轮次记录。"""
current = now or datetime.utcnow()
cutoff = current - _REGISTRY_TTL
expired = [key for key, item in _turns_by_id.items() if item.created_at < cutoff]
for key in expired:
_turns_by_id.pop(key, None)
if len(_turns_by_id) <= _MAX_ENTRIES:
return
ordered = sorted(_turns_by_id.items(), key=lambda pair: pair[1].created_at)
overflow = len(_turns_by_id) - _MAX_ENTRIES
for key, _ in ordered[:overflow]:
_turns_by_id.pop(key, None)
def register_file_check_chat_turn(
*,
turn_id: str,
session_id: str,
user_id: int,
agent_id: int,
query: str,
) -> None:
"""
登记本轮文件检核对话上下文(chat API 在调用 Dify 前执行)。
Args:
turn_id: 本轮唯一标识(hxops_turn_id)。
session_id: ChatSession.session_id。
user_id: 当前用户 ID。
agent_id: 当前 Agent ID。
query: 用户输入原文。
"""
turn_key = str(turn_id or "").strip()
session_key = str(session_id or "").strip()
if not turn_key or not session_key:
return
item = FileCheckChatTurn(
turn_id=turn_key,
session_id=session_key,
user_id=int(user_id),
agent_id=int(agent_id),
query=str(query or ""),
created_at=datetime.utcnow(),
)
with _lock:
_turns_by_id[turn_key] = item
_prune_locked()
def attach_run_to_turn(turn_id: str, run_id: int) -> bool:
"""将检核批次 ID 关联到已登记轮次。"""
turn_key = str(turn_id or "").strip()
if not turn_key or run_id <= 0:
return False
with _lock:
item = _turns_by_id.get(turn_key)
if not item:
return False
item.run_id = int(run_id)
return True
def resolve_run_id_by_turn(turn_id: str | None) -> int | None:
"""按 turn_id 读取已关联的检核批次 ID。"""
turn_key = str(turn_id or "").strip()
if not turn_key:
return None
with _lock:
item = _turns_by_id.get(turn_key)
if not item or not item.run_id or item.run_id <= 0:
return None
return int(item.run_id)
def infer_bind_context_for_run_request(data: dict[str, Any] | None) -> dict[str, str]:
"""
为启动检核 HTTP Body 推断缺失的 hxops_session_id / hxops_turn_id。
Args:
data: 启动检核请求 Body。
Returns:
可合并进 Body 的绑定字段 dict(可能为空)。
"""
payload = data if isinstance(data, dict) else {}
session_id = str(payload.get("hxops_session_id") or "").strip()
turn_id = str(payload.get("hxops_turn_id") or "").strip()
if session_id and turn_id:
return {}
user_message = _normalize_text(payload.get("user_message"))
now = datetime.utcnow()
recent_cutoff = now - timedelta(minutes=15)
with _lock:
_prune_locked(now)
candidates = [
item for item in _turns_by_id.values()
if item.created_at >= recent_cutoff
]
if turn_id and not session_id:
matched = next((item for item in candidates if item.turn_id == turn_id), None)
if matched:
return {"hxops_session_id": matched.session_id, "hxops_turn_id": matched.turn_id}
if session_id and not turn_id:
scoped = [item for item in candidates if item.session_id == session_id]
if user_message:
exact = next(
(item for item in scoped if _normalize_text(item.query) == user_message),
None,
)
if exact:
return {"hxops_session_id": exact.session_id, "hxops_turn_id": exact.turn_id}
unbound = [item for item in scoped if not item.run_id]
if len(unbound) == 1:
item = unbound[0]
return {"hxops_session_id": item.session_id, "hxops_turn_id": item.turn_id}
if not session_id and not turn_id:
if user_message:
exact = next(
(item for item in candidates if _normalize_text(item.query) == user_message and not item.run_id),
None,
)
if exact:
return {"hxops_session_id": exact.session_id, "hxops_turn_id": exact.turn_id}
unbound = [item for item in candidates if not item.run_id]
if len(unbound) == 1:
item = unbound[0]
return {"hxops_session_id": item.session_id, "hxops_turn_id": item.turn_id}
return {}
def resolve_run_id_by_session_query(
session_id: str | None,
query: str | None,
) -> int | None:
"""按 session_id + query 从注册表读取已关联 run_id。"""
session_key = str(session_id or "").strip()
query_key = _normalize_text(query)
if not session_key:
return None
now = datetime.utcnow()
recent_cutoff = now - timedelta(minutes=15)
with _lock:
candidates = [
item for item in _turns_by_id.values()
if item.session_id == session_key and item.created_at >= recent_cutoff and item.run_id
]
if query_key:
exact = next((item for item in candidates if _normalize_text(item.query) == query_key), None)
if exact and exact.run_id:
return int(exact.run_id)
if len(candidates) == 1 and candidates[0].run_id:
return int(candidates[0].run_id)
return None
def clear_registry_for_tests() -> None:
"""测试专用:清空注册表。"""
with _lock:
_turns_by_id.clear()
__all__ = [
"attach_run_to_turn",
"clear_registry_for_tests",
"infer_bind_context_for_run_request",
"register_file_check_chat_turn",
"resolve_run_id_by_session_query",
"resolve_run_id_by_turn",
]
@@ -0,0 +1,93 @@
"""␍
services/file_check_tools/dify_inputs.py␍
␍
用途:构建文件检核 Chatflow 的 Dify chat inputs,并在 task_id 缺失时快速失败。␍
依赖:task_resolver、agent_resolver、errors.ValidationError。␍
逻辑:chat.py 在调 Dify 前调用本模块;缺失 schedule_task_id 时抛 ValidationError,避免 Dify 长连接挂死。␍
"""␍
from __future__ import annotations␍
␍
from app.errors import ValidationError␍
from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent␍
␍
# Dify Chatflow「用户输入」变量名 — 须与画布 Start 节点配置一致␍
FILE_CHECK_TASK_ID_INPUT = "task_id"␍
FILE_CHECK_TASK_ID_MISSING_CODE = "file_check_task_id_required"␍
␍
␍
def _missing_task_id_error(agent) -> ValidationError:␍
"""␍
构造 task_id 未配置时的业务异常。␍
␍
核心逻辑:返回可操作的配置提示,供管理后台与前端直接展示。␍
"""␍
return ValidationError(␍
"文件检核 Agent 未配置有效的 schedule_task_id,无法调用 Dify Chatflow。"␍
"请在管理后台编辑该 Agent,于 extra_config 中设置 "␍
"tool_run_progress.schedule_task_id(绑定排程任务 ID)。",␍
details={␍
"error_code": FILE_CHECK_TASK_ID_MISSING_CODE,␍
"agent_id": getattr(agent, "id", None),␍
"agent_name": getattr(agent, "name", None) or "",␍
"config_hint": {␍
"capabilities": ["tool_run_progress"],␍
"tool_run_progress": {␍
"type": "file_check",␍
"schedule_task_id": "<ScheduleTask.id>",␍
},␍
},␍
},␍
)␍
␍
␍
def ensure_file_check_task_id_configured(agent) -> int:␍
"""␍
解析并校验文件检核 Agent 绑定的 schedule_task_id。␍
␍
Args:␍
agent: 当前对话 Agent。␍
␍
Returns:␍
有效的 ScheduleTask.id。␍
␍
Raises:␍
ValidationError: extra_config 未配置或 schedule_task_id 非法。␍
"""␍
task_id = resolve_schedule_task_id_from_agent(agent)␍
if not task_id:␍
raise _missing_task_id_error(agent)␍
return task_id␍
␍
␍
def build_file_check_dify_inputs(agent, *, required: bool = False) -> dict[str, str]:␍
"""␍
构建文件检核 Chatflow 的 Dify chat inputs。␍
␍
仅注入 task_id。hxops_session_id / hxops_turn_id 由 chat.py 登记 turn 注册表,␍
Tool API 启动时通过 user_message 推断,无需传入 Dify 画布。␍
␍
Args:␍
agent: 当前对话 Agent;task_id 从其 extra_config 解析。␍
required: 为 True 时若 task_id 缺失立即抛 ValidationError,避免 Dify 流式挂死。␍
␍
Returns:␍
含 task_id 的 inputs 字典;required=False 且未配置时返回空 dict。␍
␍
Raises:␍
ValidationError: required=True 且 schedule_task_id 未配置。␍
"""␍
task_id = resolve_schedule_task_id_from_agent(agent)␍
if not task_id:␍
if required:␍
raise _missing_task_id_error(agent)␍
return {}␍
return {FILE_CHECK_TASK_ID_INPUT: str(task_id)}␍
␍
␍
__all__ = [␍
"FILE_CHECK_TASK_ID_INPUT",␍
"FILE_CHECK_TASK_ID_MISSING_CODE",␍
"build_file_check_dify_inputs",␍
"ensure_file_check_task_id_configured",␍
]␍
␍
@@ -0,0 +1,724 @@
{
"openapi": "3.0.3",
"info": {
"title": "HXOPS File Check Tool API",
"description": "文件检核 Chatflow 显式 HTTP Tool API:检核任务列表、发起检核、查询检核批次、下载检核报告。鉴权:Authorization Bearer 或 X-Integration-Key。",
"version": "1.0.0"
},
"servers": [
{
"url": "https://your-hxops-host",
"description": "部署时设为 HXOPS_TOOLS_API_BASE;GET /tools/openapi.json 会按服务端配置自动覆盖"
}
],
"security": [
{
"BearerAuth": []
},
{
"IntegrationKey": []
}
],
"paths": {
"/api/file-check/tools/tasks": {
"get": {
"operationId": "list_file_check_tasks",
"summary": "查询指定文件检核任务",
"tags": [
"File Check"
],
"parameters": [
{
"name": "task_id",
"in": "query",
"required": true,
"schema": {
"type": "integer",
"example": 12
},
"description": "检核任务 ID(Agent 绑定的 schedule_task_id)"
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ListTasksResponse"
}
}
}
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"404": {
"$ref": "#/components/responses/TaskNotFound"
},
"503": {
"$ref": "#/components/responses/MissingAuth"
}
}
}
},
"/api/file-check/tools/tasks/run": {
"post": {
"operationId": "run_file_check",
"summary": "异步启动 文件检核",
"tags": [
"File Check"
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RunCheckRequest"
}
}
}
},
"responses": {
"200": {
"description": "启动成功;或已有 文件检核进行中,返回 ok=false/error_code=check_running",
"content": {
"application/json": {
"schema": {
"oneOf": [
{
"$ref": "#/components/schemas/RunCheckSuccessResponse"
},
{
"$ref": "#/components/schemas/CheckRunningResponse"
}
]
}
}
}
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"404": {
"$ref": "#/components/responses/TaskNotFound"
}
}
}
},
"/api/file-check/tools/runs": {
"get": {
"operationId": "list_file_check_runs",
"summary": "查询 文件检核批次列表",
"tags": [
"File Check"
],
"parameters": [
{
"name": "task_id",
"in": "query",
"required": false,
"schema": {
"type": "integer",
"example": 12
},
"description": "可选;指定检核任务 ID 时只返回该任务批次"
},
{
"name": "limit",
"in": "query",
"required": false,
"schema": {
"type": "integer",
"minimum": 1,
"maximum": 100,
"default": 20
},
"description": "返回条数,最大 100"
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ListRunsResponse"
}
}
}
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"404": {
"$ref": "#/components/responses/TaskNotFound"
}
}
}
},
"/api/file-check/tools/runs/{run_id}": {
"get": {
"operationId": "get_file_check_run",
"summary": "查询指定检核批次",
"tags": [
"File Check"
],
"parameters": [
{
"name": "run_id",
"in": "path",
"required": true,
"schema": {
"type": "integer",
"example": 88
}
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/GetRunResponse"
}
}
}
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"404": {
"$ref": "#/components/responses/RunNotFound"
}
}
}
},
"/api/file-check/tools/tasks/{task_id}/latest-run": {
"get": {
"operationId": "get_latest_file_check_run",
"summary": "查询检核任务最近一次检核",
"tags": [
"File Check"
],
"parameters": [
{
"name": "task_id",
"in": "path",
"required": true,
"schema": {
"type": "integer",
"example": 12
}
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/GetRunResponse"
}
}
}
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"404": {
"$ref": "#/components/responses/RunNotFound"
}
}
}
},
"/api/file-check/tools/runs/{run_id}/excel": {
"get": {
"operationId": "download_file_check_run_excel",
"summary": "下载检核报告 Excel(短期签名 token)",
"tags": [
"File Check"
],
"security": [],
"parameters": [
{
"name": "run_id",
"in": "path",
"required": true,
"schema": {
"type": "integer",
"example": 88
}
},
{
"name": "token",
"in": "query",
"required": true,
"description": "由 get_file_check_run 返回的 excel.download_url 中的 JWT,有效期 600 秒",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Excel 文件流",
"content": {
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
"schema": {
"type": "string",
"format": "binary"
}
}
}
},
"409": {
"$ref": "#/components/responses/ExcelNotReady"
}
}
}
}
},
"components": {
"securitySchemes": {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"description": "FILE_CHECK_TOOLS_API_KEY 或 INTEGRATION_API_KEY"
},
"IntegrationKey": {
"type": "apiKey",
"in": "header",
"name": "X-Integration-Key",
"description": "与 Bearer 二选一"
}
},
"schemas": {
"TaskSummary": {
"type": "object",
"properties": {
"task_id": {
"type": "integer",
"example": 12
},
"task_no": {
"type": "string",
"example": "CHK202606090001"
},
"name": {
"type": "string",
"example": "文件自动检核"
},
"enabled": {
"type": "boolean"
},
"last_status": {
"type": "string",
"nullable": true,
"example": "success"
},
"last_run_at": {
"type": "string",
"format": "date-time",
"nullable": true
},
"next_run_at": {
"type": "string",
"format": "date-time",
"nullable": true
}
}
},
"RunExcel": {
"type": "object",
"properties": {
"file_name": {
"type": "string",
"nullable": true,
"example": "RUN202606090001.xlsx"
},
"file_size": {
"type": "integer",
"nullable": true,
"example": 45678
},
"download_url": {
"type": "string",
"nullable": true,
"example": "https://your-hxops-host/api/file-check/tools/runs/88/excel?token=..."
}
}
},
"RunKnowledgeBase": {
"type": "object",
"properties": {
"enabled": {
"type": "boolean"
},
"sync_status": {
"type": "string",
"nullable": true,
"enum": [
"skipped",
"queued",
"cleaning",
"syncing",
"ready",
"success",
"failed"
]
},
"group_id": {
"type": "integer",
"nullable": true
},
"document_id": {
"type": "integer",
"nullable": true
},
"document_version_id": {
"type": "integer",
"nullable": true
},
"sync_job_id": {
"type": "integer",
"nullable": true
},
"error_message": {
"type": "string",
"nullable": true
}
}
},
"RunDetail": {
"type": "object",
"properties": {
"run_id": {
"type": "integer",
"example": 88
},
"run_no": {
"type": "string",
"example": "RUN202606090001"
},
"task_id": {
"type": "integer",
"example": 12
},
"task_name": {
"type": "string",
"example": "文件自动检核"
},
"status": {
"type": "string",
"enum": [
"running",
"success",
"partial_failed",
"failed",
"queued",
"cancelled"
]
},
"total_count": {
"type": "integer"
},
"success_count": {
"type": "integer"
},
"failed_count": {
"type": "integer"
},
"skipped_count": {
"type": "integer"
},
"started_at": {
"type": "string",
"format": "date-time",
"nullable": true
},
"finished_at": {
"type": "string",
"format": "date-time",
"nullable": true
},
"duration_ms": {
"type": "integer",
"nullable": true
},
"error_message": {
"type": "string",
"nullable": true
},
"excel": {
"$ref": "#/components/schemas/RunExcel"
},
"knowledge_base": {
"$ref": "#/components/schemas/RunKnowledgeBase"
}
}
},
"ListTasksResponse": {
"type": "object",
"required": [
"ok",
"tasks"
],
"properties": {
"ok": {
"type": "boolean",
"example": true
},
"tasks": {
"type": "array",
"items": {
"$ref": "#/components/schemas/TaskSummary"
}
}
}
},
"RunCheckRequest": {
"type": "object",
"properties": {
"task_id": {
"type": "integer",
"example": 12
},
"trigger_source": {
"type": "string",
"default": "dify_chatflow"
},
"conversation_id": {
"type": "string",
"nullable": true
},
"user_message": {
"type": "string",
"nullable": true
}
},
"required": [
"task_id"
],
"description": "Chatflow Tool 节点绑定 task_id(来自 Start 用户输入);user_message 用于进度卡片 turn 匹配"
},
"RunCheckSuccessResponse": {
"type": "object",
"required": [
"ok",
"message",
"run"
],
"properties": {
"ok": {
"type": "boolean",
"example": true
},
"message": {
"type": "string",
"example": "检核已启动"
},
"run": {
"$ref": "#/components/schemas/RunDetail"
}
}
},
"CheckRunningResponse": {
"type": "object",
"required": [
"ok",
"error_code",
"message",
"run"
],
"properties": {
"ok": {
"type": "boolean",
"example": false
},
"error_code": {
"type": "string",
"example": "check_running"
},
"message": {
"type": "string",
"example": "该检核任务正在执行中,请稍后查询结果"
},
"run": {
"$ref": "#/components/schemas/RunDetail"
}
}
},
"GetRunResponse": {
"type": "object",
"required": [
"ok",
"run"
],
"properties": {
"ok": {
"type": "boolean",
"example": true
},
"run": {
"$ref": "#/components/schemas/RunDetail"
}
}
},
"ListRunsResponse": {
"type": "object",
"required": [
"ok",
"runs",
"count"
],
"properties": {
"ok": {
"type": "boolean",
"example": true
},
"count": {
"type": "integer",
"example": 2
},
"runs": {
"type": "array",
"items": {
"$ref": "#/components/schemas/RunDetail"
}
}
}
},
"ErrorResponse": {
"type": "object",
"required": [
"ok",
"error_code",
"message"
],
"properties": {
"ok": {
"type": "boolean",
"example": false
},
"error_code": {
"type": "string"
},
"message": {
"type": "string"
}
}
}
},
"responses": {
"Unauthorized": {
"description": "鉴权失败",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"examples": {
"missing_auth": {
"value": {
"ok": false,
"error_code": "missing_auth",
"message": "missing_auth"
}
},
"invalid_auth": {
"value": {
"ok": false,
"error_code": "invalid_auth",
"message": "invalid_auth"
}
}
}
}
}
},
"MissingAuth": {
"description": "服务端未配置 FILE_CHECK_TOOLS_API_KEY / INTEGRATION_API_KEY",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": {
"ok": false,
"error_code": "missing_auth",
"message": "FILE_CHECK_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured"
}
}
}
},
"BadRequest": {
"description": "请求参数无效",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": {
"ok": false,
"error_code": "invalid_request",
"message": "invalid_request"
}
}
}
},
"TaskNotFound": {
"description": "检核任务不存在",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": {
"ok": false,
"error_code": "task_not_found",
"message": "task_not_found"
}
}
}
},
"RunNotFound": {
"description": "检核批次不存在",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": {
"ok": false,
"error_code": "run_not_found",
"message": "run_not_found"
}
}
}
},
"ExcelNotReady": {
"description": "Excel 尚未生成",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": {
"ok": false,
"error_code": "excel_not_ready",
"message": "excel_not_ready"
}
}
}
}
}
}
}
@@ -0,0 +1,31 @@
"""
services/file_check_tools/openapi_spec.py
用途:构建文件检核 Chatflow 的 OpenAPI 3.0 规范。
依赖:openapi_base.json。
逻辑:GET /api/file-check/tools/openapi.json 调用 build_file_check_openapi_spec。
"""
from __future__ import annotations
import copy
import json
from pathlib import Path
from typing import Any
_BASE_SPEC_PATH = Path(__file__).with_name("openapi_base.json")
def _load_base_spec() -> dict[str, Any]:
with _BASE_SPEC_PATH.open("r", encoding="utf-8") as fp:
return json.load(fp)
def build_file_check_openapi_spec(base_url: str) -> dict[str, Any]:
"""Build OpenAPI 3.0 spec for file-check Chatflow HTTP tools."""
spec = copy.deepcopy(_load_base_spec())
base = str(base_url or "").strip().rstrip("/")
servers = spec.get("servers")
if base and isinstance(servers, list) and servers:
servers[0]["url"] = base
servers[0]["description"] = "HXOPS_TOOLS_API_BASE"
return spec
@@ -0,0 +1,39 @@
"""
services/file_check_tools/progress_paths.py
用途:文件检核进度轮询 API 路径常量与展示标题解析。
依赖:ScheduleTask。
逻辑:前端/ enrich 由 schedule_task_id 推导 URL,管理员无需配置 log_progress_url。
"""
from __future__ import annotations
from app import db
from app.models import ScheduleTask
FILE_CHECK_LOG_PROGRESS_PATH = "/api/workspace/file-check/runs/for-log"
FILE_CHECK_DETAIL_PATH_TEMPLATE = "/api/workspace/file-check/runs/{run_id}"
def resolve_file_check_progress_title(task_id: int | None) -> str:
"""
从 ScheduleTask.name 解析进度卡片标题。
Args:
task_id: Agent extra_config 中的 schedule_task_id。
Returns:
排程任务名称;不存在时返回空字符串。
"""
if not task_id or task_id <= 0:
return ""
task = db.session.get(ScheduleTask, int(task_id))
if not task:
return ""
return str(getattr(task, "name", "") or "").strip()
__all__ = [
"FILE_CHECK_DETAIL_PATH_TEMPLATE",
"FILE_CHECK_LOG_PROGRESS_PATH",
"resolve_file_check_progress_title",
]
@@ -0,0 +1,117 @@
"""
services/file_check_tools/task_resolver.py
用途:解析文件检核 Chatflow 绑定的 ScheduleTask.id 与 Agent 进度配置。
依赖:ScheduleTask、Agent.extra_config、progress_paths、agent_resolver。
逻辑:task_id 来自 Agent extra_config;title 来自 ScheduleTask.name;轮询 URL 由代码推导。
"""
from __future__ import annotations
from app.models import Agent, ScheduleTask
from app.services.file_check_tools.agent_resolver import _resolve_task_id_from_mapping
from app.services.file_check_tools.progress_paths import resolve_file_check_progress_title
resolve_schedule_task_id_from_mapping = _resolve_task_id_from_mapping
def resolve_schedule_task_id_from_agent(agent) -> int | None:
"""从 Agent extra_config 解析绑定的检核排程 task_id。"""
extra = getattr(agent, "extra_config", None) or {}
if not isinstance(extra, dict):
return None
tool_cfg = extra.get("tool_run_progress")
if isinstance(tool_cfg, dict):
task_id = resolve_schedule_task_id_from_mapping(tool_cfg)
if task_id:
return task_id
return resolve_schedule_task_id_from_mapping(extra)
def is_file_check_schedule_task(task: ScheduleTask | None) -> bool:
"""判断排程任务是否存在(文件检核以 task_id 为准,不再按名称关键词过滤)。"""
return task is not None and int(getattr(task, "id", 0) or 0) > 0
def _has_tool_run_progress_capability(extra: dict) -> bool:
caps = extra.get("capabilities") or []
if isinstance(caps, list) and "tool_run_progress" in caps:
return True
if isinstance(extra.get("tool_run_progress"), dict):
return True
progress_type = str(extra.get("type") or "").strip().lower()
if progress_type == "file_check":
return True
tool_cfg = extra.get("tool_run_progress")
if isinstance(tool_cfg, dict):
nested_type = str(tool_cfg.get("type") or "").strip().lower()
if nested_type == "file_check":
return True
return False
def _apply_schedule_task_metadata(merged: dict) -> None:
"""按 schedule_task_id 写入展示 title(ScheduleTask.name)。"""
task_id = resolve_schedule_task_id_from_mapping(merged)
if not task_id:
return
schedule_title = resolve_file_check_progress_title(task_id)
if schedule_title:
merged["title"] = schedule_title
def enrich_tool_run_progress_extra(extra_config: dict | None, *, agent: Agent | None = None) -> dict:
"""
为文件检核 Agent 的 extra_config 补全 tool_run_progress 能力与轮询参数。
核心逻辑:管理员只需配置 schedule_task_id;进度轮询 URL 由前后端按 task_id 推导,无需 log_progress_url。
Returns:
新的 extra_config 副本。
"""
extra = dict(extra_config or {})
tool_cfg = extra.get("tool_run_progress")
merged = dict(tool_cfg) if isinstance(tool_cfg, dict) else {
"type": "file_check",
"poll_interval_seconds": 2,
"lock_input_when_running": True,
}
merged.setdefault("poll_interval_seconds", 2)
merged.setdefault("type", "file_check")
merged.setdefault("lock_input_when_running", True)
if not resolve_schedule_task_id_from_mapping(merged) and agent is not None:
task_id = resolve_schedule_task_id_from_agent(agent)
if task_id:
merged["schedule_task_id"] = task_id
_apply_schedule_task_metadata(merged)
# 历史字段:若 DB 仍存有 URL,去掉以免误导运维重复维护
merged.pop("log_progress_url", None)
merged.pop("detail_url_template", None)
merged.pop("session_progress_url", None)
extra["tool_run_progress"] = merged
capabilities = list(extra.get("capabilities") or [])
if "tool_run_progress" not in capabilities:
capabilities.append("tool_run_progress")
extra["capabilities"] = capabilities
return extra
def enrich_agent_extra_if_file_check(agent: Agent) -> dict:
"""若 Agent 已声明 tool_run_progress 能力则 enrich extra_config,否则原样返回。"""
extra = dict(agent.extra_config or {}) if isinstance(agent.extra_config, dict) else {}
if _has_tool_run_progress_capability(extra):
return enrich_tool_run_progress_extra(extra, agent=agent)
return extra
__all__ = [
"enrich_agent_extra_if_file_check",
"enrich_tool_run_progress_extra",
"is_file_check_schedule_task",
"resolve_schedule_task_id_from_agent",
"resolve_schedule_task_id_from_mapping",
]