sync: 鍚屾灞€鍩熺綉鏈€鏂颁唬鐮?(source master @ b69568e4)

This commit is contained in:
gozeros committed 2026-10-21 14:51:31 +08:00
1 parent 4f7f07504a
commit 8bc8b0e082
1651 files changed
+278599 -11416

No files matched your search

@@ -6,11 +6,12 @@ import os
import threading
from datetime import datetime
from functools import lru_cache
from pathlib import Path
from typing import TYPE_CHECKING
from zoneinfo import ZoneInfo
from deerflow.config.agents_config import load_agent_soul
from deerflow.config.system_settings import load_system_settings
from deerflow.config.agents_config import load_agent_soul
from deerflow.config.system_settings import load_system_settings
from deerflow.skills.storage import get_or_new_skill_storage
from deerflow.skills.types import Skill, SkillCategory
from deerflow.subagents import get_available_subagent_names
@@ -79,6 +80,7 @@ def _build_network_policy_section() -> str:
_ENABLED_SKILLS_REFRESH_WAIT_TIMEOUT_SECONDS = 5.0
_enabled_skills_lock = threading.Lock()
_enabled_skills_cache: list[Skill] | None = None
_enabled_skills_cache_root: str | None = None
_enabled_skills_refresh_active = False
_enabled_skills_refresh_version = 0
_enabled_skills_refresh_event = threading.Event()
@@ -143,7 +145,7 @@ def _start_enabled_skills_refresh_thread() -> None:
def _refresh_enabled_skills_cache_worker() -> None:
global _enabled_skills_cache, _enabled_skills_refresh_active
global _enabled_skills_cache, _enabled_skills_cache_root, _enabled_skills_refresh_active
while True:
with _enabled_skills_lock:
@@ -158,6 +160,7 @@ def _refresh_enabled_skills_cache_worker() -> None:
with _enabled_skills_lock:
if _enabled_skills_refresh_version == target_version:
_enabled_skills_cache = skills
_enabled_skills_cache_root = _current_skills_root()
_enabled_skills_refresh_active = False
_enabled_skills_refresh_event.set()
return
@@ -165,6 +168,7 @@ def _refresh_enabled_skills_cache_worker() -> None:
# A newer invalidation happened while loading. Keep the worker alive
# and loop again so the cache always converges on the latest version.
_enabled_skills_cache = None
_enabled_skills_cache_root = None
def _ensure_enabled_skills_cache() -> threading.Event:
@@ -183,12 +187,43 @@ def _ensure_enabled_skills_cache() -> threading.Event:
return _enabled_skills_refresh_event
def _current_skills_root() -> str | None:
try:
return str(Path(get_or_new_skill_storage().get_skills_root_path()).resolve())
except Exception:
logger.debug("Failed to resolve the skills root for the prompt cache", exc_info=True)
return None
def get_warm_enabled_skills(storage=None) -> list[Skill] | None:
"""Return the parsed enabled-skill catalogue when it is already warm.
A cold cache returns None so callers can load from disk. A storage rooted
somewhere else also returns None, so a temporary catalogue is not answered
from the process-wide cache.
"""
with _enabled_skills_lock:
cached = _enabled_skills_cache
root = _enabled_skills_cache_root
if cached is None or root is None:
return None
if storage is not None:
try:
current = str(Path(storage.get_skills_root_path()).resolve())
except Exception:
return None
if current != root:
return None
return list(cached)
def _invalidate_enabled_skills_cache() -> threading.Event:
global _enabled_skills_cache, _enabled_skills_refresh_active, _enabled_skills_refresh_version
global _enabled_skills_cache, _enabled_skills_cache_root, _enabled_skills_refresh_active, _enabled_skills_refresh_version
_get_cached_skills_prompt_section.cache_clear()
with _enabled_skills_lock:
_enabled_skills_cache = None
_enabled_skills_cache_root = None
_enabled_skills_refresh_version += 1
_enabled_skills_refresh_event.clear()
if _enabled_skills_refresh_active:
@@ -247,6 +282,81 @@ async def refresh_skills_system_prompt_cache_async() -> None:
await asyncio.to_thread(_invalidate_enabled_skills_cache().wait)
def _load_named_enabled_skill(name: str) -> Skill | None:
"""Parse ``public/<name>`` and ``custom/<name>`` only.
Custom overwrites public, matching ``load_skills``. A directory whose
frontmatter name differs is ignored here; the full reload still discovers
it. Disabled and archived skills are omitted from the prompt list.
"""
storage = get_or_new_skill_storage()
root = storage.get_skills_root_path()
from deerflow.config.extensions_config import ExtensionsConfig
from deerflow.skills.parser import parse_skill_file
found: Skill | None = None
for category in (SkillCategory.PUBLIC, SkillCategory.CUSTOM):
skill_file = root / category.value / name / "SKILL.md"
if not skill_file.is_file():
continue
skill = parse_skill_file(skill_file, category=category, relative_path=Path(name))
if skill is not None and skill.name == name:
found = skill
if found is None:
return None
try:
found.enabled = ExtensionsConfig.from_file().is_skill_enabled(found.name, found.category)
except Exception:
logger.warning("Failed to load extensions config for skill %r", name, exc_info=True)
return None
if not found.enabled:
return None
try:
from deerflow.skills.usage import STATE_ARCHIVED, get_entry
if get_entry(name).get("state") == STATE_ARCHIVED:
return None
except Exception:
logger.debug("Failed to read archive state for skill %r", name, exc_info=True)
return found
def update_enabled_skill_cache(name: str, *, removed: bool = False) -> bool:
"""Replace or drop one skill in a warm prompt cache.
Returns False when the cache is cold or a full reload is in flight, so the
caller can fall back to ``refresh_skills_system_prompt_cache_async``.
"""
global _enabled_skills_cache
with _enabled_skills_lock:
if _enabled_skills_cache is None or _enabled_skills_refresh_active:
return False
version = _enabled_skills_refresh_version
loaded = None if removed else _load_named_enabled_skill(name)
with _enabled_skills_lock:
if _enabled_skills_cache is None or _enabled_skills_refresh_active or _enabled_skills_refresh_version != version:
return False
previous = next((skill for skill in _enabled_skills_cache if skill.name == name), None)
if loaded is not None and previous is not None:
loaded.always_on = previous.always_on
updated = [skill for skill in _enabled_skills_cache if skill.name != name]
if loaded is not None:
updated.append(loaded)
updated.sort(key=lambda skill: skill.name)
_enabled_skills_cache = updated
_get_cached_skills_prompt_section.cache_clear()
return True
async def refresh_one_skill_prompt_cache(name: str, *, removed: bool = False) -> None:
"""Update one skill in the prompt catalogue, or reload everything if cold."""
updated = await asyncio.to_thread(update_enabled_skill_cache, name, removed=removed)
if not updated:
await refresh_skills_system_prompt_cache_async()
def _build_skill_evolution_section(skill_evolution_enabled: bool) -> str:
if not skill_evolution_enabled:
return ""
@@ -286,6 +396,19 @@ def _build_es_query_routing_section(
if available_skills is not None and "es_query" not in available_skills:
return ""
# An explicit operator takedown is authoritative even for the default
# agent, whose allowlist is represented by ``None``. Without this check
# the prompt would still instruct the model to invoke an offline skill.
try:
from deerflow.config.extensions_config import ExtensionsConfig
es_query_state = ExtensionsConfig.from_file().skills.get("es_query")
if es_query_state is not None and not es_query_state.enabled:
return ""
except Exception:
logger.warning("Failed to verify es_query availability; suppressing routing prompt", exc_info=True)
return ""
config = app_config
if config is None:
try:
@@ -487,28 +610,213 @@ task(description="Oracle Cloud analysis", prompt="...", subagent_type="general-p
</subagent_system>"""
_ORDINARY_QA_MARKDOWN_FORMAT_SECTION = """
<ordinary_qa_markdown_format>
当普通问答需要输出带章节结构的较长内容时,必须采用以下 Markdown 规范,以便下载为 Word 后得到正确的自动编号和公文标题格式:
- 文档主标题使用 `# 主标题`;主标题只写标题文字,不添加章节编号。
- 一级章节使用 `## 一、标题`,二级章节使用 `### (一) 标题`,三级章节使用 `#### 1. 标题`。二级编号必须使用半角括号 `(一)`。
- 不要在标题中使用 `2.1`、`2.1.1` 等多级阿拉伯数字编号;章节编号直接按上述三种形式书写。
- 默认禁止使用以 `-`、`*`、`+` 或 `•` 开头的无序圆点列表;并列内容优先改写为完整自然段,确需逐项表达时使用有序列表。只有用户明确要求无序列表时才使用。
- 简短问答不必为了套用格式而强行添加标题;本规范只约束实际使用的标题和列表。
</ordinary_qa_markdown_format>
"""
_ORDINARY_QA_HEADING_RULES = {
"hybrid_decimal": """- 一级章节使用 `## 一、标题`,二级章节使用 `### 1.1 标题`,三级章节使用 `#### 1.1.1 标题`。
- 二级章节按 `1.1`、`1.2`、`2.1` 的形式编号,三级及更深层级继续使用完整多级阿拉伯数字。
- 确需更深层级时,四级章节使用 `##### 1.1.1.1 标题`,五级章节使用 `###### 1.1.1.1.1 标题`。""",
"official_chinese": """- 一级章节使用 `## 一、标题`,二级章节使用 `### (一) 标题`,三级章节使用 `#### 1. 标题`。
- 确需更深层级时,四级章节使用 `##### (1) 标题`,五级章节使用 `###### 1) 标题`。""",
"decimal": """- 一级章节使用 `## 1 标题`,二级章节使用 `### 1.1 标题`,三级章节使用 `#### 1.1.1 标题`。
- 确需更深层级时,继续使用 `##### 1.1.1.1 标题`、`###### 1.1.1.1.1 标题`。""",
"chapter_section": """- 一级章节使用 `## 第一章 标题`,二级章节使用 `### 第一节 标题`,三级章节使用 `#### 一、标题`。
- 确需更深层级时,四级章节使用 `##### (一) 标题`,五级章节使用 `###### 1. 标题`。""",
"none": """- 各级章节只写标题文字,不手写编号:`## 一级标题`、`### 二级标题`、`#### 三级标题`。
- 确需更深层级时使用 `##### 四级标题`、`###### 五级标题`,仍不添加编号。""",
}
def _ordinary_qa_markdown_format_enabled() -> bool:
"""Return the admin-controlled formal Markdown prompt switch."""
def _word_heading_numbering_style() -> str:
"""Return the configured Word heading-numbering preset with a safe default."""
try:
return bool(load_system_settings().prompt_prefix.ordinary_qa_markdown_format_enabled)
return load_system_settings().prompt_prefix.word_heading_numbering_style
except Exception:
logger.debug("Failed to read the ordinary Q&A Markdown format switch; using disabled", exc_info=True)
return False
logger.debug("Failed to read the Word heading-numbering style; using default", exc_info=True)
return "hybrid_decimal"
SYSTEM_PROMPT_TEMPLATE = """
def _build_ordinary_qa_markdown_format_section() -> str:
rules = _ORDINARY_QA_HEADING_RULES.get(
_word_heading_numbering_style(),
_ORDINARY_QA_HEADING_RULES["hybrid_decimal"],
)
return f"""
<ordinary_qa_markdown_format>
当普通问答需要输出带章节结构的较长内容时,必须采用以下 Markdown 规范,以便下载为 Word 后得到正确的自动编号和公文标题格式:
- 文档主标题使用 `# 主标题`;主标题只写标题文字,不添加章节编号。
{rules}
- 默认禁止使用以 `-`、`*`、`+` 或 `•` 开头的无序圆点列表;并列内容优先改写为完整自然段,确需逐项表达时使用有序列表。只有用户明确要求无序列表时才使用。
- 简短问答不必为了套用格式而强行添加标题;本规范只约束实际使用的标题和列表。
</ordinary_qa_markdown_format>
"""
_ORDINARY_QA_VISUALIZATION_SECTION = """
<ordinary_qa_visualization>
以下输出分流规则优先级高于技能说明、绘图库说明和页面模板说明,必须先判断输出载体,再决定是否调用工具:
- 只有用户在本次请求中明确要求生成“HTML”“HTML 网页”“网页”“页面”“大屏”“看板”或 `.html` 文件,才属于 HTML 页面任务。
- “画流程图”“画图表”“画地图”“画思维导图”“做可视化”“画得好看”等说法本身都不代表用户要求 HTML,也不得据此推断为页面任务。
- 没有明确 HTML 页面意图时,禁止读取或调用 `page-report-generation`、`page_report_template` 等网页生成技能或工具,禁止创建、写入或交付 HTML 文件。
- 用户只要求画流程图时,必须直接在当前消息中输出 Mermaid,不创建文件;流程图分支、节点较多也不能改变这一规则。
- 用户只要求画图表时,必须沿用原有的消息内图表回答方式,不创建 HTML 文件。
- 如果是否需要 HTML 不明确,默认使用消息内展示,不要自行升级为 HTML 页面任务。
- 一旦用户明确要求 HTML 页面,任务就必须作为文件交付:读取并遵循 `page-report-generation` 技能,在沙箱中从空白文件生成 `.html`。此时禁止读取或执行 `web-app`、Vite、React 页面脚手架,即使其技能说明提到“多页面网站”;本任务的多页面是单一 HTML 制品中的锚点逻辑页。
- 默认禁止读取 `page-template-library` 或调用 `page_report_template(action="prepare")`,也不要套用任何现成页面模板。只有用户本次明确说“使用模板”“按某个模板生成”或指定模板名称时,才允许选择并准备模板。
- 在默认的从零生成流程中,第一项文件操作必须是用 `write_file` 创建一个与用户主题对应的最终文件,例如 `/mnt/user-data/outputs/美国服务网络大屏.html`。不要读取、打开、复制或复用已有的 `report-page.html`、旧 outputs 页面或任何工作副本;不要在最终文件写入前打开模板预览。
- 从零生成的 HTML 必须追求首写即正确:写入前在本轮思考中完成结构检查,首个 `write_file` 直接写完整成品,不能先写骨架、再读回、再整页重写。对多页面门户,写入前逐项确认本地 Bootstrap/Alpine 引用、`.pages`、每个 `.page` 的 `id`/`data-page`、全部真实导航锚点、图表 JSON、地图纯文本 description 和深色文字配置。默认只做一次 `validate`。写入和校验会自动补齐深色卡片/表格/弹窗和深色图表文字,不要为这些机械项反复改文件。若仍失败,`errors` 已是完整清单:必须在同一次回复里按 `repair_checklist` 全部修完,再用最少次数的 `str_replace` 打局部补丁(CSS、导航、单个 JSON 或单个 DOM 区块),然后只再 `validate` 一次。禁止修一个错误就立刻校验、再修下一个。除非文件不存在或用户明确要求重做,禁止第二次 `write_file` 覆盖整个 HTML,也禁止重新调用 catalog/prepare 或再次读取模板。
- 将最终 HTML 文件放到 `/mnt/user-data/outputs/`,并调用 `present_files` 打开制品预览。
- 明确要求 HTML 页面时,禁止在消息正文中直接输出完整 HTML 源码或使用 `html` 代码围栏代替文件;最终消息只能简要说明并指向已经打开的 HTML 制品。除非工具明确失败,否则不得退化为粘贴源码。
- HTML 页面默认必须是单页面:用户只说生成 HTML、网页、页面、看板或大屏时,`preferred_page_count` 必须传 `1`,所有内容在同一页面内通过纵向区块组织。
- 只有用户在本次请求中直接明确说“多页面”“多页”“多个页面”“分页门户”或指定页面数量时,才允许 `preferred_page_count > 1`、选择多页面模板或创建页面切换导航。内容很多、报告章节很多、已有 Markdown 很长,都不能作为生成多页面的理由。用户明确要求多页面但未指定数量时,默认规划 3 个有业务意义的页面,并传 `preferred_page_count=3`;同时在 `page_brief` 写明各页的目标和导航关系。每一条导航 `<a href="#page-...">` 必须精确指向一个真实 `.page` 的 `id`,每个逻辑页必须有导航入口;脚本切页也只能写同样的 `location.hash="#page-..."`,不能写 `#overview`、`#stations` 一类的 `data-page` 值,更不能仅在 CSS 注释中伪造锚点文本。
仅当用户明确要求在普通问答中展示地图时,才输出地图数据代码块;普通文字问答保持原有回答方式,不要主动插入地图或思维导图。
用户只说“画地图”“标注地点”“显示坐标”而没有明确要求生成 HTML、网页、看板、大屏或 `.html` 文件时,必须在消息列表中输出 `map-json`,不得为了展示地图创建或写入 HTML 文件。
用户仅在**本次请求明确要求**“思维导图”“脑图”“知识导图”,或明确点名 `analysis-mindmap` 技能时,才可在消息列表中输出 `mindmap-json`;普通分析、总结、提纲、结构化 JSON、流程图或图表都不得自行升级为思维导图。
思维导图必须基于当前可见的分析结构或用户提供的材料,只保留结论层级,不编造事实;先用一句极短说明引出,再立即输出一个严格 JSON 的 `mindmap-json` 代码块,让 JSON 写入过程可在消息中显示;代码块闭合后前端才会渲染导图。不创建文件、不输出 HTML、不要改用 Mermaid 或任何流程图数据围栏。每张图恰好一个根节点,`nodes` 为扁平数组,字段为 `id`、`parentId`(根为 `null`)、`label`、`kind`(仅可为 `topic/dimension/finding/evidence/risk/action`)、可选 `detail` 和 `sourceRefs`;可选 `title`、`summary`、`rootId`。节点 id 必须唯一、父节点必须存在、不能成环。导图是概要而不是报告逐条转录:目标 12–24 个节点,硬上限 36 个;中心主题保留 3–6 个一级维度,任一非根节点最多 3 个子节点,最多 4 层(含中心主题)。绝不按每个数据点、段落、引用、句子或项目符号各建一个节点;同类事实合并为一个结论节点,把必要解释合并到 `detail`,把少量依据标识放进 `sourceRefs`。材料过多时优先压缩与归类,而不是增加节点。格式示例:
`{"title":"形势分析","summary":"按关键维度归纳","rootId":"root","nodes":[{"id":"root","parentId":null,"label":"形势分析","kind":"topic"},{"id":"risk","parentId":"root","label":"主要风险","kind":"risk","detail":"简要说明"}]}`
流程图和图表沿用上述原有消息内能力。
用户明确要求 Markdown 报告文件(`.md` / md 报告 / 写入沙箱)时,不要只在消息里贴全文;必须按 `<markdown_file_deliverable>` 用 `write_file` 写入 `/mnt/user-data/outputs/*.md`,以便右侧沙箱打开。
- 地图使用 `map-json`,坐标一律按 `[经度,纬度]`,格式为:
`{"title":"地点分布","center":[116.4,39.9],"zoom":6,"markers":[{"name":"北京","coordinate":[116.4,39.9],"description":"可选"}],"lines":[],"polygons":[]}`
- 代码块必须是严格 JSON:双引号、无注释、无尾逗号;只输出地图数据,不输出 JavaScript、HTML 或回调函数。
- 禁止在地图数据中放入 URL、CDN、在线图片、在线图标、在线字体或在线绘图服务链接。标记只使用文字。
- 地图代码块前后可以有简短说明。
</ordinary_qa_visualization>
"""
_HTML_ARTIFACT_VISUALIZATION_SECTION = """
<html_artifact_visualization>
只有通过 `<ordinary_qa_visualization>` 中的 HTML 页面意图门禁后,才允许阅读和执行本节;否则必须完全忽略本节的绘图契约。
触发本节的前提是:用户在本次请求中明确要求生成 HTML、网页、看板、大屏页面或 `.html` 文件。
不得仅因为用户要求画地图、标注地点或显示坐标,就推断用户需要 HTML;这类普通地图请求必须在消息列表中使用 `map-json`。
通过门禁后,必须在沙箱中生成并通过 `present_files` 交付实际 `.html` 文件,以便右侧制品面板打开预览;不得只在聊天消息中粘贴 HTML 代码。
除非用户直接明确要求多页面或指定多个页面,生成的 HTML 必须是单页面,且质量校验时 `preferred_page_count` 必须传 `1`。不得因为报告较长、章节较多或模板自带导航而擅自生成多页面。
“单页面”表示一个可以自然纵向滚动的 HTML 文档,不等于把所有内容压进一个固定尺寸的单屏。
除非用户本次明确要求“大屏、驾驶舱、单屏或 1920×1080 固定画布”,普通 HTML 页面必须使用响应式文档布局:`body` 允许纵向滚动,主体使用 `width:min(100% - 32px, 1200px)` 一类的最大宽度,区块高度随内容增长,移动端改为单列。
普通报告页面禁止固定 1920×1080 舞台、禁止 `html/body { overflow:hidden }`、禁止用 JavaScript 按 1920×1080 对整个页面做 `scale()`。不要把长报告做成 KPI 驾驶舱,不要为了装饰虚构指标;优先保留原报告的标题、摘要、章节、结论和来源层级。
页面视觉应克制清晰:默认使用浅色低饱和配色、充足留白和稳定卡片层级;除非用户明确要求,禁止粒子背景、跑马灯、持续漂浮光斑、数字翻牌等循环动画,也不要用 emoji 充当功能图标。
满足 HTML 触发条件后,才使用下列平台内置绘图契约。生成的 HTML 源码必须直接引用 Gateway 提供的浏览器版 AntV G6、ECharts 和当前 HTML 地图引擎对应的地图资源,内网部署不依赖 CDN,也不依赖前端 React 构建产物。
- 用户上传了图片并要求把它作为页面背景时,必须把 `<uploaded_files>` 里该图片的 Public URL(`/api/public/html-images/...` 绝对地址)直接写成背景:单页面写成 `html, body` 的唯一背景;多页面只写到用户指定的 `.page` 选择器,未指定时写到首页 `.page`。两种情况均使用 `background-image: url('Public URL'); background-size: cover; background-position: center; background-repeat: no-repeat;`。禁止再叠 `linear-gradient`、`.overlay` 全屏蒙层、半透明遮罩或任何 rgba 滤镜;图片背景不得意外扩展到其他逻辑页面。禁止写 `/mnt/user-data/uploads/...`、相对路径、制品 API 路径,也禁止把图片转成 base64。理解图片内容仍只调用 `view_image`。没有 Public URL 时不要编造链接。禁止把 HTML 源码、Public URL 或 CSS 原文粘贴进聊天消息。
- 用户明确要求多页面 HTML 时,启用“轻量交互门户”模式:仍然只交付一个 `.html` 制品(预览器以 `blob:` 打开,不能可靠跳转相对的 `page2.html`),用 `<main class="pages">` 包住多个带唯一 `id` 与 `data-page` 的 `<section class="page">`。导航只使用 `href="#page-..."`;首页默认显示,其余页默认隐藏,页面切换由预览器已注入的锚点处理器完成。不要用相对 `.html` 链接、`window.location`、iframe 嵌套或前端构建流程。每个页面必须有明确业务职责,例如概览、地图/分析、站点/明细。
- “轻量交互门户”模式必须使用后端托管的 Bootstrap 与 Alpine:`<link rel="stylesheet" href="__DF_HTML_RUNTIME_BASE__/bootstrap.min.css">`、`<script defer src="__DF_HTML_RUNTIME_BASE__/alpine.min.js"></script>`、`<script defer src="__DF_HTML_RUNTIME_BASE__/bootstrap.bundle.min.js"></script>`。Bootstrap 负责响应式网格、导航、表格、按钮和标准 `modal`;Alpine 负责小范围状态、筛选、列表渲染与动态详情。可根据业务需要编写足量的局部 CSS/JavaScript,不限制代码行数;但禁止引入 jQuery、React、Vue、Babel、npm、CDN 或重复的组件库。详情弹窗优先使用 Bootstrap `data-bs-*` 或 `bootstrap.Modal`,地图标点/区域详情仍由 DeerFlow 地图运行时提供。
- 只能按需使用以下后台地址,必须写进 HTML 源码的 `<head>`,并保留这里给出的顺序;禁止使用 CDN、npm 网站或其他在线绘图服务:
- 流程图:`<script defer src="__DF_HTML_RUNTIME_BASE__/g6.min.js"></script>`
- 图表:`<script defer src="__DF_HTML_RUNTIME_BASE__/echarts.min.js"></script>`
__DF_HTML_MAP_CONTRACT__
- 只要页面使用上述任一种图形,都必须在所有绘图库引用之后添加:`<script defer src="__DF_HTML_RUNTIME_BASE__/deerflow-runtime.js"></script>`。
- 页面使用哪一种图形,就必须包含对应引用;同一页面使用多种图形时,同时包含对应引用。不要在 HTML 中省略这些引用,不要依赖前端预览器注入,也不要自行复制绘图库源码。
- 从已有 Markdown 报告生成页面时,必须先盘点报告中的 Mermaid 代码块以及流程图、图表、地图内容,并在 `page_report_template` 的 `required_features` 和 `page_brief` 中如实声明。
- Markdown 中的 Mermaid 流程图必须转换成下述 `data-df-flow` G6 契约,禁止原样复制 Mermaid,也禁止改画成手写 HTML/CSS 节点、箭头或步骤条。
- 调用 `page_report_template` 校验时必须继续传入相同的 `required_features`。校验返回 `ok: false` 时必须按错误修复并重新校验,不得忽略错误或直接交付。
- 流程图不要使用 Mermaid。写一个有明确高度的容器,例如 `<div id="process-flow" class="df-flow" style="height:420px"></div>`;紧随严格 JSON:
`<script type="application/json" data-df-flow="process-flow">{"title":"业务流程","direction":"LR","nodes":[{"id":"start","label":"需求受理","description":"接收并登记需求","type":"start"},{"id":"review","label":"方案评审","description":"确认范围与风险","type":"decision"},{"id":"finish","label":"交付上线","type":"end"}],"edges":[{"source":"start","target":"review","label":"提交"},{"source":"review","target":"finish","label":"通过"}]}</script>`
`direction` 只能是 `LR` 或 `TB`;节点 `type` 使用 `start/end/decision/risk/process/stage/task`。平台用 AntV G6 自动生成带卡片节点、状态色、箭头、标签和交互缩放的流程图,不要写 `new G6.Graph` 初始化代码。
多页面中流程图所在 `.page` 初始隐藏时,运行时会等容器可见后再初始化,并跟随容器尺寸变化自动 resize;不要为切页手写延迟初始化、`graph.render()` 或 `graph.resize()`。
单张流程图优先控制在 8 个节点以内;超过 8 个节点时应按阶段拆成多张图,确实不能拆时必须用 `TB` 并给容器至少 `600px` 高度。
每张流程图独占一行,不要把多个流程图塞进固定高度的两列网格。父级区块必须允许高度随内容增长,禁止依赖运行时修改容器高度。
- 图表:写一个有明确高度的容器,例如 `<div id="sales-chart" class="df-chart" style="height:360px"></div>`;紧随一个严格 JSON 数据块:
`<script type="application/json" data-df-chart="sales-chart">{"title":{"text":"销售趋势"},"tooltip":{},"xAxis":{"type":"category","data":["一月","二月"]},"yAxis":{"type":"value"},"series":[{"type":"line","data":[12,18]}]}</script>`
`data-df-chart` 的内容必须能被 `JSON.parse` 直接解析:禁止 `function (...)`、箭头函数、回调、注释、未加引号的键、尾逗号和任何 JavaScript 表达式。不要写 `color: function(p){...}`、`formatter: function...` 等回调;颜色使用字面量色值或每个数据项的 `itemStyle.color`,提示词使用 ECharts 字符串模板(例如 `"{b}: {c}"`)。不要写 `echarts.init`,平台自动初始化。声明式图表配置只保留 `data-df-chart` JSON;不得为同一图表另写未被使用的 `const option`,或用 `document.write` 生成隐藏占位容器。
深色页面必须在 `<html>` 声明 `data-df-theme="dark"`,正文、表格、输入和弹窗使用浅色前景。每张深色图表必须设置根 `textStyle.color`,有标题时设置 `title.textStyle.color`,有图例时设置 `legend.textStyle.color`;每个 x/y 轴设置 `axisLabel.color`,带轴名时设置 `nameTextStyle.color`;饼图、漏斗图和雷达图系列设置 `label.color`。禁止在深色背景留下 ECharts 默认黑字或 `#000` 一类深色文字。
若使用 Bootstrap 卡片、表格、弹窗或表单,不能依赖 `body { color: ... }` 的继承:Bootstrap 组件可能覆盖它。必须同时设置 `html[data-df-theme="dark"]` 的 `--bs-body-color`、`--bs-emphasis-color`、`--bs-secondary-color` 等 token,并显式给 `.card`、`.data-table`/`.data-table td`、`.modal-content`/`.modal-body`、`.form-control`/`.form-select` 设置浅色 `color`;表头、辅助文案可用较浅的次级文字色。深色页面应只用一个统一的语义色变量组,保证正文的对比度至少 4.5:1。
__DF_HTML_MAP_BODY__
- 每个流程图、图表或地图旁边都要有可读标题和一句文字结论;即使绘图失败,页面主体仍应能理解。容器必须设置高度,不能只依赖百分比高度。
- 默认直接用 `write_file` 在 `/mnt/user-data/outputs/` 创建最终 `.html` 文件,以便生成过程中自动打开右侧沙箱预览;不要先写 workspace 后再用 `cp`/bash 复制。整个过程只能使用这个最终路径:不得先 `present_files` 一个模板/占位页,也不得把完成版换到另一个文件名。
完成后对同一路径调用 `page_report_template(action="validate")`,同时传入 `preferred_page_count`、完整的 `required_features` 和 `page_brief`;通过后再 `present_files`。若校验发现图表 JSON、地图或流程图契约错误,必须修复后重新校验,不能交付带“图形数据格式错误”的页面。
- 只有用户明确要求使用模板时,才调用 `page_report_template(action="prepare", template_id="...")`。此时其 `working_copy` 同时也是 `final_output`,直接编辑、校验并交付即可。
</html_artifact_visualization>
"""
_MARKDOWN_FILE_DELIVERABLE_SECTION = """
<markdown_file_deliverable>
本节只在用户本次明确要求 Markdown 报告文件时生效。普通短问答、解释、对比和口头总结继续只在消息里回答,不要主动打开沙箱。
触发条件(满足任一即可):
- 用户明确要求生成 `.md`、Markdown 文件、md 报告或 markdown 报告
- 用户明确说「写 md 报告」「保存为 md」「输出 markdown 文件」「报告文件」
- 用户明确要求把报告写入沙箱或打开沙箱预览
未触发时:不要因为回答较长或带了 `#` 标题就写入文件。
用户明确要求 HTML / 网页 / 大屏时走 HTML 文件交付,不要改写成 Markdown 文件。
触发后必须:
- 用 `write_file` 把完整 Markdown 直接写入 `/mnt/user-data/outputs/` 下的 `.md` 文件,例如 `/mnt/user-data/outputs/形势分析报告.md`
- 这样右侧沙箱会在写入过程中自动打开;不要只在聊天消息里粘贴全文代替文件
- 不要先写 `/mnt/user-data/workspace/` 再复制
- 写入后可以 `present_files` 同一路径;最终聊天回复只做简短说明并指向制品
</markdown_file_deliverable>
"""
_HTML_ECHARTS_MAP_SCRIPT = """ - 地图:`<script defer src="__DF_HTML_RUNTIME_BASE__/echarts.min.js"></script>`。地图与普通图表共用同一个 ECharts 浏览器包;不要引入 Leaflet 或任何地图瓦片库。"""
_HTML_LEAFLET_MAP_SCRIPT = """ - 地图:当前选择的是「地图网页」。写入 `<link rel="stylesheet" href="__DF_HTML_RUNTIME_BASE__/leaflet.css">` 和 `<script defer src="__DF_HTML_RUNTIME_BASE__/leaflet.js"></script>`。不要改用 ECharts 地图、`data-df-geo` 或本地 GeoJSON。普通图表仍使用 ECharts。"""
_HTML_ECHARTS_MAP_BODY = """- HTML 网页中的地图一律使用本地 GeoJSON + ECharts Canvas 契约,禁止 Leaflet、`data-df-map`、
地图瓦片 URL、CDN、外部地图服务,以及页面内的 `echarts.init` / `echarts.registerMap`。
普通问答消息列表的 `map-json` 保持原有前端瓦片渲染,不受本条影响。
写一个有明确高度的容器,例如 `<div id="area-map" class="df-geo-map" style="height:560px"></div>`;紧随严格 JSON:
`<script type="application/json" data-df-geo="area-map">`
`{"title":"全国服务网络","map":"china-provinces","mode":"background","roam":true,"showLabels":false,`
`"regions":[{"name":"北京市","value":86,"description":"华北服务中心","color":"#2c78b7"}],`
`"markers":[{"name":"北京","coordinate":[116.4,39.9],"description":"华北服务中心"}],"lines":[]}</script>`
内置地图目录如下,坐标统一为 `[经度,纬度]`:中国省级 `china-provinces`、美国州级 `us-states`、日本都道府县 `japan-prefectures`、台湾地区县市 `taiwan-counties`。根据用户指定国家或城市自动选择对应地图;若没有给出国家,默认使用 `china-provinces`。不要猜测或引用未内置的国家、行政区或在线地图。
平台自动加载本地 GeoJSON、注册地图、绘制区域/标记/连线,并支持拖拽缩放与点击。多页面中地图所在 `.page` 初始隐藏时,运行时会等容器可见后再初始化,并跟随容器尺寸变化自动 resize;不要调用不存在的 `deerflowMapReady`,也不要为切页手写延迟初始化、`echarts.init` 或 `chart.resize()`。`regions` 与 `markers` 中的 `description` 会在用户点击区域或标点时自动显示为可关闭的详情浮层;`description` 必须是纯文本,不能包含 `<a>`、`<span>`、`onclick` 或其他 HTML/事件属性,因为运行时会转义它。不要自己写地图弹窗。`us-states`、`japan-prefectures` 和 `taiwan-counties` 的区域名应使用地图中的标准英文名称(例如 `California`、`Osaka Prefecture`、`Taipei City`)。
如需把点击结果联动到页面内已有的信息卡、筛选站点或切换明细页,只能监听 `window` 的 `deerflow:geo-map-click` 事件,并读取 `event.detail.name`、`event.detail.description` 或 `event.detail.data` 更新文字;需要切页时在事件回调内设置一个真实导航锚点,例如 `window.location.hash="#page-stations"`,再执行筛选。禁止在地图 `description` 中伪造“查看全部”链接,也禁止为此自行初始化 ECharts。
用户明确要求“地图网页、地图看板或地图大屏”时,默认采用“深蓝三栏态势数据大屏”风格,而不是通用报告卡片或整页背景地图。桌面宽度(至少 1180px)使用 `min-height:100dvh` 的三栏网格:左列约 24%–27%,中列约 46%–52%,右列约 24%–27%,间距 12px–16px;窄屏时改为单列纵向布局,地图优先显示,禁止通过 `min-width` 强行产生横向滚动。
顶部使用 72px–84px 的细标题带:左侧放日期、资料范围或状态,中央放中文主标题和一行大写英文副标题,右侧只放数据更新时间等已知信息;可用低透明斜线和一条青色发光分隔线增强层次,但没有真实时间数据时不要虚构实时时钟。主内容左列优先放 2 个紧凑 KPI 和一张趋势图;中列放一张占满列高的 `.df-geo-map`;右列放横向排名图和占比环图或与用户任务同等重要的两张分析图。所有图表必须对应用户给出的主题,缺少真实数据时清晰标注“示意数据”。
面板使用深蓝半透明渐变、细蓝色边框、青色标题竖条、左上/右下的小角标和克制内发光;主色为深蓝和青色,金色只用于用户关注的枢纽、告警或最高优先级数据。标题可以有中英双层信息,但正文和交互控件最小字号为 16px;不要使用 emoji、厚重不透明白卡、夸张霓虹、无意义动画或外部字体/CDN。所有可点击控件须保留悬停、按下和键盘焦点状态,并尊重 `prefers-reduced-motion`。
中列地图必须始终是视觉主角,作为面板主体背景而非 `body` 背景。这种三栏结构中的中列就是“中间地图舞台”,中间至少 65% 的地图画面保持无遮挡。地图容器高度至少 560px,使用 `mode:"background"`、`showLabels:false`,地图头部另放标题和小图例;用户提到的城市必须写入 `markers`,提到的行政区必须同时写入 `regions` 并高亮,每个标点/区域提供 `description`,由运行时弹出详情浮层。需要联动页面内摘要时只监听 `deerflow:geo-map-click`;不要手写地图弹窗、`echarts.init`、`echarts.registerMap`、视觉映射或函数式 ECharts 配置。
地图面板层级必须保持可点击:地图容器在最底层,装饰网格、角标和渐变遮罩都使用 `pointer-events:none`,信息卡仅存在于左右列,不得覆盖中列地图的主体画面;卡片之外的透明区域不得拦截鼠标事件,使地图标点和区域始终可点击。"""
_HTML_LEAFLET_MAP_BODY = """- HTML 网页中的地图一律使用「地图网页」契约:Leaflet 瓦片底图 + `data-df-map`。禁止 `data-df-geo`、`.df-geo-map`、本地 GeoJSON 目录、`echarts.registerMap`,以及页面内的 `L.map` / `L.tileLayer`。
瓦片地址由后台 `config.yaml` 的 `html_runtime.map_tile_url` 注入运行时,禁止在 HTML 里书写瓦片 URL、CDN 或外部地图脚本。
普通问答消息列表的 `map-json` 保持原有前端瓦片渲染,不受本条影响。
写一个有明确高度的容器,例如 `<div id="area-map" class="df-map" style="height:560px"></div>`;紧随严格 JSON:
`<script type="application/json" data-df-map="area-map">`
`{"title":"全国服务网络","center":[116.4,39.9],"zoom":5,`
`"markers":[{"name":"北京","coordinate":[116.4,39.9],"description":"华北服务中心"}],`
`"lines":[{"name":"联络","coordinates":[[116.4,39.9],[121.47,31.23]]}],"polygons":[]}</script>`
坐标统一为 `[经度,纬度]`。平台自动加载配置的地图瓦片,并绘制标点、连线和多边形,支持拖拽缩放。多页面中地图所在 `.page` 初始隐藏时,运行时会等容器可见后再初始化;不要手写 `L.map` 或延迟初始化。`description` 必须是纯文本,不能包含 `<a>`、`<span>`、`onclick` 或其他 HTML/事件属性。不要自己写地图弹窗。
用户明确要求“地图网页、地图看板或地图大屏”时,默认采用“深蓝三栏态势数据大屏”风格,而不是通用报告卡片或整页背景地图。桌面宽度(至少 1180px)使用 `min-height:100dvh` 的三栏网格:左列约 24%–27%,中列约 46%–52%,右列约 24%–27%,间距 12px–16px;窄屏时改为单列纵向布局,地图优先显示,禁止通过 `min-width` 强行产生横向滚动。
顶部使用 72px–84px 的细标题带:左侧放日期、资料范围或状态,中央放中文主标题和一行大写英文副标题,右侧只放数据更新时间等已知信息;可用低透明斜线和一条青色发光分隔线增强层次,但没有真实时间数据时不要虚构实时时钟。主内容左列优先放 2 个紧凑 KPI 和一张趋势图;中列放一张占满列高的 `.df-map`;右列放横向排名图和占比环图或与用户任务同等重要的两张分析图。所有图表必须对应用户给出的主题,缺少真实数据时清晰标注“示意数据”。
面板使用深蓝半透明渐变、细蓝色边框、青色标题竖条、左上/右下的小角标和克制内发光;主色为深蓝和青色,金色只用于用户关注的枢纽、告警或最高优先级数据。标题可以有中英双层信息,但正文和交互控件最小字号为 16px;不要使用 emoji、厚重不透明白卡、夸张霓虹、无意义动画或外部字体/CDN。所有可点击控件须保留悬停、按下和键盘焦点状态,并尊重 `prefers-reduced-motion`。
中列地图必须始终是视觉主角,作为面板主体背景而非 `body` 背景。这种三栏结构中的中列就是“中间地图舞台”,中间至少 65% 的地图画面保持无遮挡。地图容器高度至少 560px;用户提到的城市必须写入 `markers`,需要画出的范围写入 `polygons`,每个标点提供 `description`,由运行时弹出说明。不要手写 `L.map`、`L.tileLayer` 或瓦片地址。
地图面板层级必须保持可点击:地图容器在最底层,装饰网格、角标和渐变遮罩都使用 `pointer-events:none`,信息卡仅存在于左右列,不得覆盖中列地图的主体画面;卡片之外的透明区域不得拦截鼠标事件,使地图标点和区域始终可点击。"""
def _build_html_artifact_visualization_section(app_config: AppConfig) -> str:
"""Render browser-reachable backend runtime URLs into the HTML contract."""
from deerflow.html_runtime.map_engine import html_map_engine
base_url = app_config.html_runtime.base_url.rstrip("/")
leaflet = html_map_engine() == "leaflet"
section = (
_HTML_ARTIFACT_VISUALIZATION_SECTION.replace(
"__DF_HTML_MAP_CONTRACT__",
_HTML_LEAFLET_MAP_SCRIPT if leaflet else _HTML_ECHARTS_MAP_SCRIPT,
).replace(
"__DF_HTML_MAP_BODY__",
_HTML_LEAFLET_MAP_BODY if leaflet else _HTML_ECHARTS_MAP_BODY,
)
)
return section.replace("__DF_HTML_RUNTIME_BASE__", base_url)
def _ordinary_qa_markdown_format_enabled() -> bool:
"""Return the admin-controlled formal Markdown prompt switch."""
try:
return bool(load_system_settings().prompt_prefix.ordinary_qa_markdown_format_enabled)
except Exception:
logger.debug("Failed to read the ordinary Q&A Markdown format switch; using disabled", exc_info=True)
return False
SYSTEM_PROMPT_TEMPLATE = """
<role>
You are {agent_name}, an internal super agent.
</role>
@@ -642,6 +950,12 @@ You: "Deploying to staging..." [proceed]
{ordinary_qa_format_section}
{ordinary_qa_visualization_section}
{html_artifact_visualization_section}
{markdown_file_deliverable_section}
<citations>
**CRITICAL: Always include citations when using web search results**
@@ -860,11 +1174,19 @@ RAG/reference display mode is enabled.
acp_section=acp_and_mounts_section,
)
if not writing_mode:
prompt += _MARKDOWN_FILE_DELIVERABLE_SECTION
prompt = prompt + rag_mode_section + _current_time_context()
return prompt
def _get_memory_context(agent_name: str | None = None, *, app_config: AppConfig | None = None, injection_enabled: bool = True) -> str:
def _get_memory_context(
agent_name: str | None = None,
*,
app_config: AppConfig | None = None,
injection_enabled: bool = True,
include_legacy_knowledge_routing: bool = True,
) -> str:
"""组装注入系统提示词的记忆上下文 (Memory V2)。
通过 :class:`MemoryManager` 收集各 provider 的记忆块。P1 期只有 builtin
@@ -875,6 +1197,10 @@ def _get_memory_context(agent_name: str | None = None, *, app_config: AppConfig
agent_name: agent 标识;``None`` 时按 "default" 处理。
app_config: 显式应用配置 (本函数实际按 per-user 覆盖解析生效配置)。
injection_enabled: 运行时开关;``False`` 时跳过注入直接返回空串。
include_legacy_knowledge_routing: 是否注入 ``/mnt/knowledge/routing.md``。
智能普通知识库检索已有数据库授权范围和专用检索工具时必须关闭,
避免旧文件路由把“这个库”错误引向沙箱目录;其它记忆 provider
仍按原配置保留。
Returns:
包在 ``<memory>`` 标签里的记忆上下文;未启用或为空时返回空串。
@@ -888,6 +1214,8 @@ def _get_memory_context(agent_name: str | None = None, *, app_config: AppConfig
user_id = get_effective_user_id()
config = get_effective_memory_config(user_id)
if not config.enabled:
return ""
manager = build_memory_manager(
user_id=user_id,
@@ -897,7 +1225,11 @@ def _get_memory_context(agent_name: str | None = None, *, app_config: AppConfig
)
# 只取静态块 (builtin 的 frozen snapshot + Hindsight 的模式说明)。
# Hindsight 的动态召回需要当前 query,走 MemoryMiddleware.before_model。
context_content = manager.build_system_prompt()
context_content = manager.build_system_prompt(
excluded_provider_names=(
None if include_legacy_knowledge_routing else {"knowledge"}
)
)
if not context_content.strip():
return ""
@@ -1415,6 +1747,44 @@ def build_report_structure_setup_prompt(
"""
def build_gongwen_template_setup_prompt(*, quick_mode: bool = False) -> str:
"""Minimal, confirmation-gated assistant for personal Gongwen templates.
It deliberately reuses ``setup_report_structure`` as the transport-only
approval tool: the frontend maps title/name/content into its own template
form and is the only layer that persists a template.
"""
clarification_rule = (
"不要追问,直接根据用户描述给出合理的公文模板结构。"
if quick_mode
else "关键信息缺失时可调用 ask_clarification,但最多两轮;每次提问后立即结束本轮。"
)
tools_rule = (
"你只有一个工具:setup_report_structure。"
if quick_mode
else "你只有两个工具:ask_clarification 和 setup_report_structure。"
)
return f"""你是「公文模板中心」的模板结构助手。你的工作不是起草具体公文,而是帮助用户创建一套可复用的**公文模板结构**。
【严格边界】
- 只讨论模板名称、适用场景、正文结构和固定的落款/要素;绝不撰写任何具体公文正文,不虚构单位、日期、事项或数据。
- {tools_rule} 不可检索、不可调用技能、不可写文件、不可调用其它工具。
- {clarification_rule}
【对话流程】
1. 用户描述用途后,先用 Markdown 给出完整模板骨架:`#` 为模板标题,`##` 为正文主要章节;必要时可用 `###` 表示固定子项。每个标题应体现该文种真实需要交代的内容,避免所有模板都套用“工作目标/工作要求”。
2. 询问用户是否确认;用户要求调整时,重新给出完整骨架。
3. **只有用户明确确认结构后**,调用 `setup_report_structure` 提交建议。调用前用一句话概括;调用后不再输出其它内容。
【提交字段映射】
- `title`:模板名称,例如“重点工作部署通知”。
- `name`:一句话说明适用场景。
- `content`:刚与用户确认的完整 Markdown 模板骨架;只含标题层级/结构说明,不含具体正文。
- `structure_mode`:固定结构用 `fixed`,可按具体事项增减小节用 `adaptive`;未说明时为 `adaptive`。
- `retrieval_directions` 和 `retrieval_skills` 一律留空。
"""
def apply_prompt_template(
subagent_enabled: bool = False,
max_concurrent_subagents: int = 3,
@@ -1427,6 +1797,7 @@ def apply_prompt_template(
is_bootstrap: bool = False,
app_config: AppConfig | None = None,
memory_injection_enabled: bool = True,
include_legacy_knowledge_routing: bool = True,
rag_mode_enabled: bool = False,
is_notebook_mode: bool = False,
notebook_source_ids: list[int] | None = None,
@@ -1435,7 +1806,12 @@ def apply_prompt_template(
storage_agent_id = agent_id if agent_id is not None else agent_name
# Get memory context
memory_context = _get_memory_context(storage_agent_id, app_config=app_config, injection_enabled=memory_injection_enabled)
memory_context = _get_memory_context(
storage_agent_id,
app_config=app_config,
injection_enabled=memory_injection_enabled,
include_legacy_knowledge_routing=include_legacy_knowledge_routing,
)
# Include subagent section only if enabled (from runtime parameter)
n = max_concurrent_subagents
@@ -1548,12 +1924,36 @@ When a search, knowledge, skill, or MCP tool returns a result list:
else ""
)
ordinary_qa_format_section = (
_ORDINARY_QA_MARKDOWN_FORMAT_SECTION
if _ordinary_qa_markdown_format_enabled()
and not is_bootstrap
and not writing_mode
and not is_notebook_mode
and not is_scheduled_run
_build_ordinary_qa_markdown_format_section()
if _ordinary_qa_markdown_format_enabled()
and not is_bootstrap
and not writing_mode
and not is_notebook_mode
and not is_scheduled_run
else ""
)
ordinary_qa_visualization_section = (
_ORDINARY_QA_VISUALIZATION_SECTION
if not is_bootstrap
and not writing_mode
and not is_notebook_mode
and not is_scheduled_run
else ""
)
html_artifact_visualization_section = (
_build_html_artifact_visualization_section(app_config)
if not is_bootstrap
and not writing_mode
and not is_notebook_mode
and not is_scheduled_run
else ""
)
markdown_file_deliverable_section = (
_MARKDOWN_FILE_DELIVERABLE_SECTION
if not is_bootstrap
and not writing_mode
and not is_notebook_mode
and not is_scheduled_run
else ""
)
@@ -1573,6 +1973,9 @@ When a search, knowledge, skill, or MCP tool returns a result list:
subagent_thinking=subagent_thinking,
acp_section=acp_and_mounts_section,
ordinary_qa_format_section=ordinary_qa_format_section,
ordinary_qa_visualization_section=ordinary_qa_visualization_section,
html_artifact_visualization_section=html_artifact_visualization_section,
markdown_file_deliverable_section=markdown_file_deliverable_section,
)
prompt = prompt + rag_mode_section + _current_time_context()