Files

158 lines
6.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Seed the built-in public-document agent, orchestration skill and engine.
三组种子资产(全部随仓库跟踪,启动时按版本同步到运行目录):
- ``_gongwen_seed_assets/gongwen-document-assistant/{config.yaml, SOUL.md}`` →
``{DEER_FLOW_HOME}/agents/gongwen-document-assistant/``(目录内其他运行时
文件不动)。
- ``_gongwen_seed_assets/skills/gongwen-workflow/``(对话编排技能)→
``skills/public/gongwen-workflow/``。
- ``_gongwen_seed_assets/skills/gongwen-assistant/``(完整 DOCX 引擎技能,
含 vendored python-docx 1.2.0)→ ``skills/public/gongwen-assistant/``。
运行时 ``skills/`` 树被 .gitignore 排除,全新部署由本 seeder 落盘,
沙箱内即 ``/mnt/skills/public/gongwen-assistant``(SKILL.md 的默认路径)。
同步语义(版本感知,区别于 agentfx 的「存在即跳过」):每个落盘副本携带
``.gongwen-seed-version``,低于 ``_SEED_VERSION`` 时整体原子替换(先拷到
同级临时目录再换名),等于或高于时跳过以尊重现场修改。要发布对种子内容
的修改:改资产 + bump ``_SEED_VERSION``,已有部署下次启动自动刷新。
技能解析顺序为 public → custom 且按名去重(后者胜出),现场在
``skills/custom/`` 放同名技能可整体覆盖内置版。
必须在 ``_sync_legacy_agents`` 之前调用。
"""
from __future__ import annotations
import logging
import shutil
from pathlib import Path
from deerflow.config.paths import get_paths
logger = logging.getLogger(__name__)
GONGWEN_AGENT_ID = "gongwen-document-assistant"
GONGWEN_WORKFLOW_SKILL = "gongwen-workflow"
GONGWEN_ENGINE_SKILL = "gongwen-assistant"
_ASSETS_DIR = Path(__file__).parent / "_gongwen_seed_assets"
_SEED_FILES: tuple[str, ...] = ("config.yaml", "SOUL.md")
# Bump when tracked seed assets change and existing deployments must pick the
# change up on the next gateway start. Deployed copies at the same version
# are left untouched so on-site edits survive restarts.
_SEED_VERSION = 3
_VERSION_FILE = ".gongwen-seed-version"
_IGNORE_PATTERNS = ("__pycache__", "*.pyc", ".pytest_cache")
def _skills_public_dir() -> Path:
from deerflow.skills.storage import get_or_new_skill_storage
return Path(get_or_new_skill_storage().get_skills_root_path()) / "public"
def _deployed_version(directory: Path) -> int:
try:
return int((directory / _VERSION_FILE).read_text(encoding="utf-8").strip() or 0)
except (OSError, ValueError):
return 0
def _copy_seed_tree(source: Path, destination: Path, label: str) -> bool:
"""Copy a seed tree when missing or older than the shipped seed version.
The copy is staged in a sibling temp directory and swapped in with one
rename so an interrupted boot never leaves a half-written skill behind.
"""
if destination.exists() and _deployed_version(destination) >= _SEED_VERSION:
return False
destination.parent.mkdir(parents=True, exist_ok=True)
staging = destination.with_name(f".{destination.name}.seed-staging")
if staging.exists():
shutil.rmtree(staging)
shutil.copytree(source, staging, ignore=shutil.ignore_patterns(*_IGNORE_PATTERNS))
(staging / _VERSION_FILE).write_text(f"{_SEED_VERSION}\n", encoding="utf-8")
if destination.exists():
logger.warning(
"Refreshing built-in %s '%s' to seed v%s (any local edits are replaced)",
label,
destination.name,
_SEED_VERSION,
)
shutil.rmtree(destination)
staging.rename(destination)
logger.info("Seeded built-in %s '%s' (v%s)", label, destination.name, _SEED_VERSION)
return True
def _seed_agent() -> bool:
"""Create or refresh the built-in agent files, never touching others."""
agent_dir = get_paths().agent_dir(GONGWEN_AGENT_ID)
if agent_dir.exists() and _deployed_version(agent_dir) >= _SEED_VERSION:
return False
source = _ASSETS_DIR / GONGWEN_AGENT_ID
if not source.is_dir():
logger.error("Missing public-document agent seed assets at %s", source)
return False
agent_dir.mkdir(parents=True, exist_ok=True)
for filename in _SEED_FILES:
asset = source / filename
if asset.is_file():
(agent_dir / filename).write_bytes(asset.read_bytes())
(agent_dir / _VERSION_FILE).write_text(f"{_SEED_VERSION}\n", encoding="utf-8")
return True
def _seed_workflow_skill() -> bool:
source = _ASSETS_DIR / "skills" / GONGWEN_WORKFLOW_SKILL
if not (source / "SKILL.md").is_file():
logger.error("Missing public-document workflow skill seed asset at %s", source)
return False
return _copy_seed_tree(
source, _skills_public_dir() / GONGWEN_WORKFLOW_SKILL, "public-document workflow skill"
)
def _seed_engine_skill() -> bool:
source = _ASSETS_DIR / "skills" / GONGWEN_ENGINE_SKILL
if not (source / "SKILL.md").is_file() or not (source / "scripts" / "run_gongwen.py").is_file():
logger.error("Missing public-document engine skill seed asset at %s", source)
return False
return _copy_seed_tree(
source, _skills_public_dir() / GONGWEN_ENGINE_SKILL, "public-document engine skill"
)
def ensure_gongwen_agent() -> bool:
"""Sync built-in public-document assets (version-aware, non-fatal).
Returns True if the agent directory was created or refreshed to a newer
seed version.
"""
created_agent = False
try:
created_agent = _seed_agent()
if created_agent:
logger.info("Seeded built-in public-document agent '%s'", GONGWEN_AGENT_ID)
except Exception:
logger.exception("Failed to seed built-in public-document agent")
for seeder, label in (
(_seed_workflow_skill, "workflow skill"),
(_seed_engine_skill, "engine skill"),
):
try:
if seeder():
logger.info("Seeded built-in public-document %s", label)
except Exception:
logger.exception("Failed to seed built-in public-document %s", label)
return created_agent
__all__ = [
"GONGWEN_AGENT_ID",
"GONGWEN_WORKFLOW_SKILL",
"GONGWEN_ENGINE_SKILL",
"ensure_gongwen_agent",
]