feat(file-check): 持久化 chat_tool_runs 并统一 agent_runtime_context 注入

新增跨 worker 进度绑定表与显式 hxops_turn_id 链路;Dify Start 仅注入
agent_runtime_context,task_id/turn_id 写入 refs 供画布解析后回传 Tool。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-07-09 18:39:05 +08:00
1 parent c778f40fbc
commit f4e74f7b07
23 files changed
+1580 -196

No files matched your search

@@ -2,8 +2,8 @@
backend/app/services/agent_registry/handlers/file_check.py
用途:文件检核 Agent Handler — 聊天流 turn 注册与 Dify 进度绑定。
依赖:file_check_tools.chat_turn_registry、agent_registry.handlers.registry、resolver。
逻辑:DifyChatExecutor 经 resolve_handler_for_agent_code 调用 prepare_stream 注册 hxops_turn_id。
依赖:file_check_tools.chat_tool_run_binding、chat_turn_registry、agent_registry.handlers.registry、resolver。
逻辑:DifyChatExecutor 经 resolve_handler_for_agent_code 调用 prepare_stream 注册 hxops_turn_id 并写入 chat_tool_runs。
"""
from __future__ import annotations
@@ -38,7 +38,9 @@ class FileCheckHandler(AgentHandler):
return ctx
turn_id = uuid.uuid4().hex
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn
from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent
register_file_check_chat_turn(
turn_id=turn_id,
@@ -47,5 +49,13 @@ class FileCheckHandler(AgentHandler):
agent_id=int(getattr(ctx.agent, 'id', 0) or 0),
query=ctx.query,
)
register_pending_turn(
turn_id=turn_id,
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
user_id=int(getattr(ctx.user, 'id', 0) or 0),
agent_id=int(getattr(ctx.agent, 'id', 0) or 0),
user_message=ctx.query,
schedule_task_id=resolve_schedule_task_id_from_agent(ctx.agent),
)
ctx.hxops_turn_id = turn_id
return ctx
@@ -33,10 +33,13 @@ ALLOWED_PARSE_PATHS: frozenset[str] = frozenset(
"refs.run_purpose",
"refs.file_name",
"refs.schedule_task_id",
"refs.hxops_turn_id",
"domain.type",
"domain.summary",
"domain.state_hint.batch_no",
"domain.state_hint.focus_task_no",
"domain.state_hint.schedule_task_id",
"domain.state_hint.hxops_turn_id",
"domain.state_hint.current_step",
"domain.state_hint.status",
"domain.state_hint.review_status",
+2 -2
View File
@@ -38,9 +38,9 @@ def build_dify_inputs_for_context(ctx: ChatStreamContext) -> dict[str, Any]:
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
request_id=ctx.request_id,
trigger_source='frontend_chat',
user_role=str(getattr(ctx.user, 'role', '') or '').strip() or None,
adapter_hints=ctx.adapter_hints,
user_role=getattr(ctx.user, 'role', None),
hxops_turn_id=ctx.hxops_turn_id,
user_role=str(getattr(ctx.user, 'role', '') or '').strip() or None,
)
+20
View File
@@ -1276,6 +1276,26 @@ class DifyService:
)
if not chat_log_id:
return None
try:
from app.services.file_check_tools.chat_tool_run_binding import bind_chat_log
bind_chat_log(
chat_log_id=int(chat_log_id),
turn_id=hxops_turn_id,
session_id=session_id,
query=query,
schedule_run_id=run_id,
)
except Exception as exc:
if current_app:
current_app.logger.warning(
'[file-check-bind] bind_chat_log failed chat_log_id=%s session_id=%s turn_id=%s request_id=%s err=%s',
chat_log_id,
session_id or None,
hxops_turn_id or None,
request_id,
exc,
)
return {"chat_log_id": chat_log_id, "run_id": run_id}
@staticmethod
@@ -2,7 +2,7 @@
services/file_check_tools/chat_log_run_binding.py
用途:将文件检核批次 ID 写入 ChatLog.run_id(按轮问答绑定)。
依赖:ChatLog、ScheduleRun、chat_turn_registry。
依赖:ChatLog、ScheduleRun、chat_tool_run_binding、chat_turn_registry。
逻辑:启动检核 API 写入 ScheduleRun.api_request_json;message_end 落 ChatLog 时解析并绑定 run_id。
"""
from __future__ import annotations
@@ -15,6 +15,10 @@ from flask import current_app
from app import db
from app.models import ChatLog, ScheduleRun
from app.services.file_check_tools.chat_tool_run_binding import (
resolve_schedule_run_id_by_turn,
resolve_schedule_run_id_for_session,
)
from app.services.file_check_tools.chat_turn_registry import (
attach_run_to_turn,
resolve_run_id_by_session_query,
@@ -69,7 +73,8 @@ def resolve_run_id_for_chat_log(
"""
匹配本轮问答应对绑定的检核批次 ID。
优先级:hxops_turn_id > session_id + 归一化 query > session_id + 近期 bind。
优先级:chat_tool_runs(turn_id)> 内存 registry > session_id + 归一化 query > ScheduleRun.api_request_json 兜底。
有 turn_id 时仅走 turn 路径,禁止降级到 session/query,避免同文案误绑。
Returns:
匹配到的 ScheduleRun.id,或 None。
@@ -88,6 +93,9 @@ def resolve_run_id_for_chat_log(
return run.api_request_json if isinstance(run.api_request_json, dict) else {}
if turn_key:
persisted_run_id = resolve_schedule_run_id_by_turn(turn_key)
if persisted_run_id:
return persisted_run_id
registry_run_id = resolve_run_id_by_turn(turn_key)
if registry_run_id:
return registry_run_id
@@ -96,8 +104,15 @@ def resolve_run_id_for_chat_log(
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)
return None
if session_key and query_key:
persisted_run_id = resolve_schedule_run_id_for_session(
session_id=session_key,
user_message=query_key,
)
if persisted_run_id:
return persisted_run_id
for run in rows:
req = _req(run)
bind_session = str(req.get("bind_session_id") or req.get("hxops_session_id") or "").strip()
@@ -2,17 +2,30 @@
services/file_check_tools/chat_log_run_resolver.py
用途:按 ChatLog.run_id 解析文件检核进度(按轮问答)。
依赖:ChatLog、ScheduleRun、chat_log_run_binding、chat_turn_registry。
逻辑:for-log API 调用;优先读 chat_logs.run_id,缺失时按 session/query 兜底匹配并懒回写。
依赖:ChatLog、ScheduleRun、chat_tool_run_binding、chat_log_run_binding。
逻辑:for-log API 调用;优先读 chat_logs.run_id,其次 chat_tool_runs,最后 session/query 兜底。
"""
from __future__ import annotations
from dataclasses import dataclass
from app import db
from app.models import ChatLog, ScheduleRun
from app.services.file_check_tools.chat_log_run_binding import (
resolve_run_id_for_chat_log,
update_chat_log_run_id,
)
from app.services.file_check_tools.chat_tool_run_binding import (
resolve_schedule_run_id_by_chat_log,
)
@dataclass
class ChatLogRunMatch:
"""ChatLog 与 ScheduleRun 的解析结果。"""
run: ScheduleRun | None
match_source: str | None = None
def find_run_for_chat_log(
@@ -30,16 +43,46 @@ def find_run_for_chat_log(
Returns:
绑定的 ScheduleRun,或 None。
"""
return find_run_for_chat_log_with_source(task_id=task_id, chat_log_id=chat_log_id).run
def find_run_for_chat_log_with_source(
*,
task_id: int,
chat_log_id: int,
) -> ChatLogRunMatch:
"""
查询某条问答记录绑定的检核批次,并返回匹配来源。
优先级:chat_logs.run_id > chat_tool_runs > session/query 兜底。
Args:
task_id: ScheduleTask.id。
chat_log_id: ChatLog.id。
Returns:
ChatLogRunMatch(含 run 与 match_source)。
"""
if chat_log_id <= 0 or task_id <= 0:
return None
return ChatLogRunMatch(run=None, match_source=None)
log = db.session.get(ChatLog, chat_log_id)
if not log:
return None
return ChatLogRunMatch(run=None, match_source=None)
run_id = int(log.run_id) if log.run_id else None
match_source = 'chat_log' if run_id else None
if not run_id:
# [STEP 1] message_end 可能早于 Tool 启动完成,按 session/query 从注册表或 ScheduleRun 兜底
# [STEP 1] 持久绑定表兜底(Tool 先启动、ChatLog 后落库)
persisted = resolve_schedule_run_id_by_chat_log(chat_log_id)
if persisted:
update_chat_log_run_id(chat_log_id, persisted)
run_id = persisted
match_source = 'chat_tool_runs'
if not run_id:
# [STEP 2] message_end 可能早于 Tool 启动完成,按 session/query 从注册表或 ScheduleRun 兜底
resolved = resolve_run_id_for_chat_log(
session_id=log.session_id,
query=log.query,
@@ -47,16 +90,19 @@ def find_run_for_chat_log(
if resolved:
update_chat_log_run_id(chat_log_id, resolved)
run_id = resolved
match_source = 'legacy'
if not run_id:
return None
return ChatLogRunMatch(run=None, match_source=None)
run = db.session.get(ScheduleRun, run_id)
if run and run.schedule_task_id == task_id:
return run
return None
return ChatLogRunMatch(run=run, match_source=match_source)
return ChatLogRunMatch(run=None, match_source=None)
__all__ = [
"find_run_for_chat_log",
'ChatLogRunMatch',
'find_run_for_chat_log',
'find_run_for_chat_log_with_source',
]
@@ -0,0 +1,407 @@
"""
services/file_check_tools/chat_tool_run_binding.py
用途:持久化 hxops_turn_id / chat_log_id / schedule_run_id 绑定关系。
依赖:ChatToolRun、ChatLog、ScheduleRun。
逻辑:file_check Handler 登记 turn;Tool API 绑定 run;Dify 落 ChatLog 回写 chat_log_id。
"""
from __future__ import annotations
import re
from datetime import datetime, timedelta
from typing import Any
from app import db
from app.models import ChatLog, ChatToolRun, ScheduleRun
try:
from flask import current_app
except ImportError: # pragma: no cover
current_app = None # type: ignore
_STATUS_PENDING = 'pending'
_STATUS_RUN_BOUND = 'run_bound'
_STATUS_COMPLETE = 'complete'
_RECENT_WINDOW = timedelta(minutes=30)
def _normalize_text(text: str | None) -> str:
"""折叠空白,便于 user_message 与 ChatLog.query 对齐。"""
return re.sub(r'\s+', ' ', str(text or '').strip())
def _derive_status(row: ChatToolRun) -> str:
"""根据已绑定字段推导状态。"""
if row.chat_log_id and row.schedule_run_id:
return _STATUS_COMPLETE
if row.schedule_run_id:
return _STATUS_RUN_BOUND
return _STATUS_PENDING
def register_pending_turn(
*,
turn_id: str,
session_id: str,
user_id: int,
agent_id: int,
user_message: str,
tool_name: str = 'run_file_check',
schedule_task_id: int | None = None,
bind_source: str = 'turn_register',
) -> ChatToolRun | None:
"""
登记本轮对话的 pending 绑定记录(chat API 在调用 Dify 前执行)。
Args:
turn_id: 本轮唯一标识(hxops_turn_id)。
session_id: ChatSession.session_id。
user_id: 当前用户 ID。
agent_id: 当前 Agent ID。
user_message: 用户输入原文。
tool_name: Tool 名称,默认 run_file_check。
schedule_task_id: 绑定的 ScheduleTask.id(可选)。
bind_source: 绑定来源标记。
Returns:
新建或已存在的 ChatToolRun;turn_id/session_id 无效时返回 None。
"""
turn_key = str(turn_id or '').strip()
session_key = str(session_id or '').strip()
if not turn_key or not session_key:
return None
existing = ChatToolRun.query.filter_by(turn_id=turn_key).first()
if existing:
changed = False
if not existing.user_message and user_message:
existing.user_message = str(user_message)
changed = True
if schedule_task_id and not existing.schedule_task_id:
existing.schedule_task_id = int(schedule_task_id)
changed = True
if changed:
existing.updated_at = datetime.utcnow()
db.session.commit()
return existing
row = ChatToolRun(
tool_name=str(tool_name or 'run_file_check'),
agent_id=int(agent_id) if agent_id else None,
user_id=int(user_id) if user_id else None,
session_id=session_key,
turn_id=turn_key,
user_message=str(user_message or ''),
schedule_task_id=int(schedule_task_id) if schedule_task_id else None,
status=_STATUS_PENDING,
bind_source=bind_source,
)
db.session.add(row)
db.session.commit()
return row
def _has_ambiguous_pending_turns(
*,
session_id: str | None,
user_message: str | None,
schedule_task_id: int | None = None,
tool_name: str = 'run_file_check',
) -> bool:
"""同会话同文案存在多个未绑定 run 的 pending turn 时返回 True。"""
session_key = str(session_id or '').strip()
query_key = _normalize_text(user_message)
if not session_key or not query_key:
return False
cutoff = datetime.utcnow() - _RECENT_WINDOW
query = ChatToolRun.query.filter(
ChatToolRun.session_id == session_key,
ChatToolRun.created_at >= cutoff,
ChatToolRun.schedule_run_id.is_(None),
)
if schedule_task_id and schedule_task_id > 0:
query = query.filter(ChatToolRun.schedule_task_id == int(schedule_task_id))
if tool_name:
query = query.filter(ChatToolRun.tool_name == str(tool_name))
rows = query.order_by(ChatToolRun.id.desc()).limit(20).all()
return len(_message_matches(rows, query_key)) > 1
def bind_schedule_run(
*,
schedule_run_id: int,
turn_id: str | None = None,
session_id: str | None = None,
user_message: str | None = None,
schedule_task_id: int | None = None,
tool_name: str = 'run_file_check',
bind_source: str = 'tool_start',
) -> bool:
"""
将检核批次 ID 写入 chat_tool_runs(Tool 启动成功或复用 running run 后执行)。
Args:
schedule_run_id: ScheduleRun.id。
turn_id: hxops_turn_id(优先匹配)。
session_id: 会话 ID(turn_id 缺失时兜底)。
user_message: 用户输入(session 兜底时用于消歧)。
schedule_task_id: ScheduleTask.id。
tool_name: Tool 名称。
bind_source: 绑定来源标记。
Returns:
是否成功绑定。
"""
if schedule_run_id <= 0:
return False
run = db.session.get(ScheduleRun, schedule_run_id)
if not run:
return False
turn_key = str(turn_id or '').strip()
session_key = str(session_id or '').strip()
if turn_key and session_key and not ChatToolRun.query.filter_by(turn_id=turn_key).first():
db.session.add(
ChatToolRun(
tool_name=str(tool_name or 'run_file_check'),
session_id=session_key,
turn_id=turn_key,
user_message=str(user_message or ''),
schedule_task_id=int(schedule_task_id or run.schedule_task_id or 0) or None,
status=_STATUS_PENDING,
bind_source='tool_start_lazy',
)
)
db.session.commit()
row = _find_binding_row(
turn_id=turn_id,
session_id=session_id,
user_message=user_message,
schedule_task_id=schedule_task_id or run.schedule_task_id,
tool_name=tool_name,
require_unbound_run=True,
)
if not row:
if current_app:
current_app.logger.warning(
'[file-check-bind] bind_schedule_run skipped schedule_run_id=%s turn_id=%s session_id=%s message_len=%s',
schedule_run_id,
str(turn_id or '').strip() or None,
str(session_id or '').strip() or None,
len(str(user_message or '')),
)
return False
row.schedule_run_id = int(schedule_run_id)
if schedule_task_id:
row.schedule_task_id = int(schedule_task_id)
elif not row.schedule_task_id:
row.schedule_task_id = int(run.schedule_task_id)
row.bind_source = bind_source
row.status = _derive_status(row)
row.updated_at = datetime.utcnow()
if row.chat_log_id:
log = db.session.get(ChatLog, row.chat_log_id)
if log and not log.run_id:
log.run_id = int(schedule_run_id)
db.session.commit()
return True
def bind_chat_log(
*,
chat_log_id: int,
turn_id: str | None = None,
session_id: str | None = None,
query: str | None = None,
schedule_run_id: int | None = None,
bind_source: str = 'chat_log',
) -> bool:
"""
ChatLog 落库后回写 chat_log_id,并同步 chat_logs.run_id。
Args:
chat_log_id: ChatLog.id。
turn_id: hxops_turn_id(优先匹配)。
session_id: 会话 ID。
query: 用户输入(session 兜底消歧)。
schedule_run_id: 已解析的 run_id(可选,用于同步 chat_logs.run_id)。
bind_source: 绑定来源标记。
Returns:
是否成功绑定。
"""
if chat_log_id <= 0:
return False
log = db.session.get(ChatLog, chat_log_id)
if not log:
return False
row = _find_binding_row(
turn_id=turn_id,
session_id=session_id or log.session_id,
user_message=query or log.query,
schedule_task_id=None,
tool_name='run_file_check',
require_unbound_run=False,
)
if not row:
return False
row.chat_log_id = int(chat_log_id)
row.bind_source = bind_source
if schedule_run_id and schedule_run_id > 0:
row.schedule_run_id = int(schedule_run_id)
elif row.schedule_run_id and not log.run_id:
log.run_id = int(row.schedule_run_id)
elif log.run_id and not row.schedule_run_id:
row.schedule_run_id = int(log.run_id)
row.status = _derive_status(row)
row.updated_at = datetime.utcnow()
db.session.commit()
return True
def resolve_schedule_run_id_by_turn(turn_id: str | None) -> int | None:
"""按 turn_id 读取已绑定的 schedule_run_id。"""
turn_key = str(turn_id or '').strip()
if not turn_key:
return None
row = ChatToolRun.query.filter_by(turn_id=turn_key).first()
if not row or not row.schedule_run_id or row.schedule_run_id <= 0:
return None
return int(row.schedule_run_id)
def resolve_schedule_run_id_by_chat_log(chat_log_id: int) -> int | None:
"""按 chat_log_id 读取已绑定的 schedule_run_id。"""
if chat_log_id <= 0:
return None
row = (
ChatToolRun.query.filter_by(chat_log_id=chat_log_id)
.order_by(ChatToolRun.id.desc())
.first()
)
if not row or not row.schedule_run_id or row.schedule_run_id <= 0:
return None
return int(row.schedule_run_id)
def resolve_schedule_run_id_for_session(
*,
session_id: str | None,
schedule_task_id: int | None = None,
user_message: str | None = None,
) -> int | None:
"""
按 session_id + user_message 从 chat_tool_runs 解析 schedule_run_id。
核心逻辑:优先精确匹配 user_message,其次取近期唯一 run_bound 记录。
"""
session_key = str(session_id or '').strip()
if not session_key:
return None
query_key = _normalize_text(user_message)
cutoff = datetime.utcnow() - _RECENT_WINDOW
query = ChatToolRun.query.filter(
ChatToolRun.session_id == session_key,
ChatToolRun.created_at >= cutoff,
ChatToolRun.schedule_run_id.isnot(None),
)
if schedule_task_id and schedule_task_id > 0:
query = query.filter(ChatToolRun.schedule_task_id == int(schedule_task_id))
rows = query.order_by(ChatToolRun.id.desc()).limit(20).all()
if not rows:
return None
if query_key:
exact_matches = [
row for row in rows
if _normalize_text(row.user_message) == query_key and row.schedule_run_id
]
if len(exact_matches) > 1:
return None
if len(exact_matches) == 1 and exact_matches[0].schedule_run_id:
return int(exact_matches[0].schedule_run_id)
if len(rows) == 1 and rows[0].schedule_run_id:
return int(rows[0].schedule_run_id)
return None
def _message_matches(rows: list[ChatToolRun], query_key: str) -> list[ChatToolRun]:
"""按归一化 user_message 过滤候选行。"""
if not query_key:
return []
return [row for row in rows if _normalize_text(row.user_message) == query_key]
def _find_binding_row(
*,
turn_id: str | None,
session_id: str | None,
user_message: str | None,
schedule_task_id: int | None,
tool_name: str,
require_unbound_run: bool,
) -> ChatToolRun | None:
"""内部:按 turn_id 或 session+message 查找可更新的绑定行。"""
turn_key = str(turn_id or '').strip()
if turn_key:
row = ChatToolRun.query.filter_by(turn_id=turn_key).first()
if row:
if require_unbound_run and row.schedule_run_id:
return None
return row
session_key = str(session_id or '').strip()
if not session_key:
return None
query_key = _normalize_text(user_message)
cutoff = datetime.utcnow() - _RECENT_WINDOW
query = ChatToolRun.query.filter(
ChatToolRun.session_id == session_key,
ChatToolRun.created_at >= cutoff,
)
if schedule_task_id and schedule_task_id > 0:
query = query.filter(ChatToolRun.schedule_task_id == int(schedule_task_id))
if tool_name:
query = query.filter(ChatToolRun.tool_name == str(tool_name))
rows = query.order_by(ChatToolRun.id.desc()).limit(20).all()
if require_unbound_run:
rows = [row for row in rows if not row.schedule_run_id]
if query_key:
matches = _message_matches(rows, query_key)
if len(matches) > 1 and not turn_key:
return None
if len(matches) == 1:
return matches[0]
if len(rows) == 1:
return rows[0]
return None
def clear_chat_tool_runs_for_tests() -> None:
"""测试专用:清空 chat_tool_runs 表。"""
ChatToolRun.query.delete()
db.session.commit()
__all__ = [
'bind_chat_log',
'bind_schedule_run',
'clear_chat_tool_runs_for_tests',
'register_pending_turn',
'resolve_schedule_run_id_by_chat_log',
'resolve_schedule_run_id_by_turn',
'resolve_schedule_run_id_for_session',
]
@@ -1,7 +1,7 @@
"""
backend/app/services/file_check_tools/context_adapter.py
用途:文件检核 Agent 的 Context Adapter,构建 task_id Dify inputs。
用途:文件检核 Agent 的 Context Adapter,构建 agent_runtime_context Dify inputs。
依赖:file_check_tools.dify_inputs、agent_runtime_context.registry。
逻辑:agent_code=file_check 时由 build_chat_dify_inputs 分发;缺失 bound_schedule_task_id 时抛 ValidationError。
"""
@@ -28,17 +28,17 @@ def build_file_check_context_adapter(
"""
构建文件检核 Chatflow Dify Start inputs。
核心逻辑:从 bound_schedule_task_id 列注入 task_id;
session_id 存在时附带 agent_runtime_context(迭代 5 Dify Start 联调);
required=True 时未配置 bound_schedule_task_id 立即失败,避免 Dify 长连接挂死。
核心逻辑:仅输出 agent_runtime_context;refs.schedule_task_id / refs.hxops_turn_id
供 Dify parse_agent_runtime_context 或 Code 解析后传给 RUN_FILE_CHECK。
Args:
agent: 当前对话 Agent。
session_id: HXOPS 会话 ID(检核 Tool 链路由 turn 注册表推断,不传入 Dify)。
session_id: HXOPS 会话 ID。
hxops_turn_id: 本轮对话唯一标识(由 Handler.prepare_stream 生成)。
adapter_hints: 预留;检核当前不消费领域 hints。
Returns:
含 task_id 与可选 agent_runtime_context 的 inputs dict。
仅含 agent_runtime_context 的 inputs dict。
Raises:
ValidationError: bound_schedule_task_id 未配置或非法。
@@ -50,4 +50,5 @@ def build_file_check_context_adapter(
request_id=request_id,
trigger_source=trigger_source,
locale=locale,
hxops_turn_id=kwargs.get('hxops_turn_id'),
)
@@ -3,7 +3,8 @@ services/file_check_tools/dify_inputs.py
用途:构建文件检核 Chatflow 的 Dify chat inputs,并在 task_id 缺失时快速失败。
依赖:task_resolver、agent_runtime_context.builder、errors.ValidationError。
逻辑:Context Adapter 调用本模块;必注入 task_id;session_id 存在时可选附带 agent_runtime_context(迭代 5 Dify Start 联调)。
逻辑:Context Adapter 调用本模块;仅输出 agent_runtime_context(与 shipping_notice 等平台 Agent 一致)。
schedule_task_id / hxops_turn_id 写入 refs,由 parse_agent_runtime_context 或画布 Code 解析后传给 Tool。
"""
from __future__ import annotations
@@ -12,8 +13,12 @@ from app.services.agent_runtime_context.builder import build_agent_runtime_conte
from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT
from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent
# Dify Chatflow「用户输入」变量名 — 须与画布 Start 节点配置一致
# refs 内字段名(非 Dify Start 顶层变量;Start 仅配置 agent_runtime_context)
FILE_CHECK_SCHEDULE_TASK_REF = "schedule_task_id"
FILE_CHECK_TURN_REF = "hxops_turn_id"
# 历史文档/画布曾用 Start 变量名 task_id,新画布请改读 refs.schedule_task_id
FILE_CHECK_TASK_ID_INPUT = "task_id"
FILE_CHECK_TURN_ID_INPUT = "hxops_turn_id"
FILE_CHECK_TASK_ID_MISSING_CODE = "file_check_task_id_required"
@@ -58,40 +63,6 @@ def ensure_file_check_task_id_configured(agent) -> int:
return task_id
def _build_file_check_runtime_context(
*,
session_id: str,
schedule_task_id: int,
agent,
request_id: str | None = None,
trigger_source: str | None = None,
locale: str | None = None,
) -> dict[str, str]:
"""
构建 file_check 可选 agent_runtime_context 快照。
核心逻辑:refs 携带 schedule_task_id;domain.state_hint 供 Dify 理解检核任务锚点。
"""
agent_name = str(getattr(agent, 'name', None) or '').strip() or '文件检核'
runtime_context = build_agent_runtime_context(
agent_code='file_check',
scope='chat_turn',
session_id=session_id,
request_id=request_id,
trigger_source=trigger_source or 'frontend_chat',
locale=locale,
refs={'schedule_task_id': str(schedule_task_id)},
domain={
'type': 'file_check',
'summary': agent_name,
'state_hint': {'schedule_task_id': str(schedule_task_id)},
},
)
if not runtime_context:
return {}
return {AGENT_RUNTIME_CONTEXT_INPUT: serialize_for_dify(runtime_context)}
def build_file_check_dify_inputs(
agent,
*,
@@ -100,25 +71,25 @@ def build_file_check_dify_inputs(
request_id: str | None = None,
trigger_source: str | None = None,
locale: str | None = None,
include_runtime_context: bool = True,
hxops_turn_id: str | None = None,
) -> dict[str, str]:
"""
构建文件检核 Chatflow 的 Dify chat inputs。
核心逻辑:必注入 task_id(Start 节点变量);session_id 存在且 include_runtime_context 时附带 agent_runtime_context。
hxops_turn_id 由 Executor 注册 turn 注册表,不传入 Dify 画布。
核心逻辑:仅注入 agent_runtime_context JSON 字符串;refs.schedule_task_id、refs.hxops_turn_id
供 Dify parse_agent_runtime_context Tool 或 Code 节点解析后传入 RUN_FILE_CHECK。
Args:
agent: 当前对话 Agent;task_id 从 bound_schedule_task_id 列解析。
agent: 当前对话 Agent;schedule_task_id 从 bound_schedule_task_id 列解析。
required: 为 True 时若 task_id 缺失立即抛 ValidationError,避免 Dify 流式挂死。
session_id: HXOPS 会话 ID;存在时可生成 agent_runtime_context。
session_id: HXOPS 会话 ID;为空时返回空 dict。
request_id: 请求追踪 ID。
trigger_source: 触发来源。
locale: 用户语言。
include_runtime_context: 是否在 task_id 之外附带 agent_runtime_context。
hxops_turn_id: 本轮对话唯一标识;由 Handler.prepare_stream 生成后传入。
Returns:
含 task_id(及可选 agent_runtime_context)的 inputs;required=False 且未配置时返回空 dict。
仅含 agent_runtime_context 的 inputs;session_id 为空或未配置 task 且 required=False 时返回 {}。
Raises:
ValidationError: required=True 且 bound_schedule_task_id 未配置或非法。
@@ -129,26 +100,44 @@ def build_file_check_dify_inputs(
raise _missing_task_id_error(agent)
return {}
inputs: dict[str, str] = {FILE_CHECK_TASK_ID_INPUT: str(task_id)}
normalized_session_id = str(session_id or '').strip()
if include_runtime_context and normalized_session_id:
inputs.update(
_build_file_check_runtime_context(
session_id=normalized_session_id,
schedule_task_id=task_id,
agent=agent,
request_id=request_id,
trigger_source=trigger_source,
locale=locale,
)
)
return inputs
if not normalized_session_id:
return {}
agent_name = str(getattr(agent, 'name', None) or '').strip() or '文件检核'
refs: dict[str, str] = {FILE_CHECK_SCHEDULE_TASK_REF: str(task_id)}
turn_key = str(hxops_turn_id or '').strip()
if turn_key:
refs[FILE_CHECK_TURN_REF] = turn_key
state_hint: dict[str, str] = {FILE_CHECK_SCHEDULE_TASK_REF: str(task_id)}
if turn_key:
state_hint[FILE_CHECK_TURN_REF] = turn_key
runtime_context = build_agent_runtime_context(
agent_code='file_check',
scope='chat_turn',
session_id=normalized_session_id,
request_id=request_id,
trigger_source=trigger_source or 'frontend_chat',
locale=locale,
refs=refs,
domain={
'type': 'file_check',
'summary': agent_name,
'state_hint': state_hint,
},
)
if not runtime_context:
return {}
return {AGENT_RUNTIME_CONTEXT_INPUT: serialize_for_dify(runtime_context)}
__all__ = [
"FILE_CHECK_SCHEDULE_TASK_REF",
"FILE_CHECK_TURN_REF",
"FILE_CHECK_TASK_ID_INPUT",
"FILE_CHECK_TURN_ID_INPUT",
"FILE_CHECK_TASK_ID_MISSING_CODE",
"build_file_check_dify_inputs",
"ensure_file_check_task_id_configured",
]
@@ -546,12 +546,22 @@
"user_message": {
"type": "string",
"nullable": true
},
"hxops_turn_id": {
"type": "string",
"nullable": true,
"description": "本轮对话唯一标识;须与 agent_runtime_context.refs.hxops_turn_id(经画布 §3.1A 解析)一致,Tool 原样回传"
},
"hxops_session_id": {
"type": "string",
"nullable": true,
"description": "HXOPS 会话 ID;可与 sys.conversation_id 二选一,优先显式传入"
}
},
"required": [
"task_id"
],
"description": "Chatflow Tool 节点绑定 task_id(来自 Start 用户输入);user_message 用于进度卡片 turn 匹配"
"description": "Chatflow Tool 节点绑定 task_id、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底"
},
"RunCheckSuccessResponse": {
"type": "object",