from __future__ import annotations from datetime import datetime from typing import Any from app import db from app.models import Agent, ScheduleRun, ScheduleTask from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id def build_dify_execution_snapshot(task: ScheduleTask) -> dict[str, Any]: """Capture Dify agent + system prompt used at execution time for audit.""" captured_at = datetime.utcnow().isoformat() + "Z" if not task.dify_agent_id: return { "dify_enabled": False, "dify_agent_id": None, "dify_agent_name": None, "dify_app_id": None, "dify_system_prompt": "", "captured_at": captured_at, } cfg = get_schedule_sql_config_by_task_id(task.id) prompt = str(cfg.dify_system_prompt if cfg else "").strip() agent = db.session.get(Agent, task.dify_agent_id) return { "dify_enabled": True, "dify_agent_id": task.dify_agent_id, "dify_agent_name": getattr(agent, "name", None) if agent else None, "dify_app_id": getattr(agent, "dify_app_id", None) if agent else None, "dify_system_prompt": prompt, "captured_at": captured_at, } def capture_dify_execution_snapshot(run: ScheduleRun, task: ScheduleTask) -> dict[str, Any]: snapshot = build_dify_execution_snapshot(task) run.dify_execution_snapshot = snapshot return snapshot