deerflow-code/offline-backend-20260512/backend/packages/harness/deerflow/tools/skill_manage_tool.py
2026-09-07 18:24:55 +08:00

451 lines
21 KiB
Python

"""Tool for creating and evolving custom skills."""
from __future__ import annotations
import asyncio
import logging
from typing import Any
from weakref import WeakValueDictionary
from langchain.tools import ToolRuntime, tool
from langgraph.typing import ContextT
from deerflow.agents.lead_agent.prompt import refresh_skills_system_prompt_cache_async
from deerflow.agents.thread_state import ThreadState
from deerflow.mcp.tools import _make_sync_tool_wrapper
from deerflow.persistence.skills import SkillStore
from deerflow.runtime.user_context import get_effective_user_id
from deerflow.skills.security_scanner import scan_skill_content
from deerflow.skills.storage import get_or_new_skill_storage
from deerflow.skills.storage.skill_storage import SkillStorage
from deerflow.skills.types import SKILL_MD_FILE
logger = logging.getLogger(__name__)
_skill_locks: WeakValueDictionary[str, asyncio.Lock] = WeakValueDictionary()
def _get_lock(name: str) -> asyncio.Lock:
lock = _skill_locks.get(name)
if lock is None:
lock = asyncio.Lock()
_skill_locks[name] = lock
return lock
def _get_thread_id(runtime: ToolRuntime[ContextT, ThreadState] | None) -> str | None:
if runtime is None:
return None
if runtime.context and runtime.context.get("thread_id"):
return runtime.context.get("thread_id")
return runtime.config.get("configurable", {}).get("thread_id")
def _history_record(*, action: str, file_path: str, prev_content: str | None, new_content: str | None, thread_id: str | None, scanner: dict[str, Any]) -> dict[str, Any]:
return {
"action": action,
"author": "agent",
"thread_id": thread_id,
"file_path": file_path,
"prev_content": prev_content,
"new_content": new_content,
"scanner": scanner,
}
async def _scan_or_raise(content: str, *, executable: bool, location: str) -> dict[str, str]:
result = await scan_skill_content(content, executable=executable, location=location)
if result.decision == "block":
raise ValueError(f"Security scan blocked the write: {result.reason}")
if executable and result.decision != "allow":
raise ValueError(f"Security scan rejected executable content: {result.reason}")
return {"decision": result.decision, "reason": result.reason}
async def _to_thread(func, /, *args, **kwargs):
return await asyncio.to_thread(func, *args, **kwargs)
async def _bump_patch_best_effort(name: str) -> None:
"""记一次技能维护活动(patch / edit)。
刷新 ``.usage.json`` 的 ``patch_count`` 与 ``last_patched_at``,让 curator 的
年龄流转把"Agent 正在主动维护的技能"算作活跃,而不是误判为闲置后归档。
best-effort:埋点失败只记 DEBUG 日志,绝不影响技能写入主流程。
"""
try:
from deerflow.skills.usage import bump_patch
await _to_thread(bump_patch, name)
except Exception:
logger.debug("Failed to bump patch count for %r", name, exc_info=True)
async def _ensure_skill_db_registered(store: SkillStore, name: str, user_id: str) -> None:
"""Idempotently record an agent-created skill's ownership in the DB.
Mirrors the ``/api/skills/install-upload`` path so agent-created skills
show up in the Web UI listing (which filters custom skills by DB
ownership). ``ensure_legacy`` is idempotent — it never overwrites an
existing owner — so re-running the create flow on an already-owned skill
is a no-op. Failures are swallowed so DB outages can never break the
agent's create flow itself.
"""
try:
await store.ensure_legacy(
{"name": name, "owner_user_id": user_id, "published": False}
)
except Exception:
logger.debug("Failed to register skill ownership for %r", name, exc_info=True)
def _default_skill_store() -> SkillStore | None:
"""Build a ``SkillStore`` backed by the global session factory.
Returns ``None`` if no DB session factory is configured (e.g. ephemeral
test environments), letting the caller skip the registration step
silently.
"""
try:
from deerflow.persistence.engine import get_session_factory
from deerflow.persistence.skills import make_skill_store
factory = get_session_factory()
if factory is None:
return None
return make_skill_store(factory)
except Exception:
logger.debug("Failed to build default skill store", exc_info=True)
return None
def _default_agent_store() -> Any | None:
"""Build an ``AgentStore`` backed by the global session factory."""
try:
from deerflow.persistence.agents import make_agent_store
from deerflow.persistence.engine import get_session_factory
factory = get_session_factory()
if factory is None:
return None
return make_agent_store(factory)
except Exception:
logger.debug("Failed to build default agent store", exc_info=True)
return None
async def _assert_skill_is_agent_authored(name: str) -> None:
"""Refuse to modify skills authored by a human (UI upload / adopt / legacy).
Even when ownership lines up, we draw a hard line at content the *human*
curated through the Web UI: uploads, adopted orphan skills, and legacy
skills with no usage entry (which default to ``source='upload'``).
Those represent reviewed content the user has explicitly endorsed —
letting the agent rewrite them risks silent drift away from what was
approved. Only skills marked ``source='agent'`` (set by
``mark_agent_created`` in the ``create`` flow) remain editable so the
evolution loop can keep refining them.
Raises ``ValueError`` (mapped to a tool error visible to the LLM) on
refusal.
"""
from deerflow.skills.usage import get_entry
entry = await _to_thread(get_entry, name)
if entry.get("source") != "agent":
raise ValueError(
f"Refused: skill '{name}' was authored by a human via the Web UI "
f"and cannot be modified by an agent. Ask the owner to edit it "
f"through the Web UI, or have the user duplicate it to a new "
f"agent-owned skill first."
)
async def _assert_agent_may_modify(store: SkillStore, name: str, user_id: str) -> dict[str, Any]:
"""Pre-flight ownership check before an agent-driven write touches a custom skill.
LocalSkillStorage operates by name only — patch/edit/write_file/remove_file
and delete all resolve a name to a directory without knowing who owns it.
Without this guard a malicious or hallucinating agent could overwrite or
destroy another user's skill (including UI-uploaded skills) just by
knowing the name. We refuse unless the DB confirms ``user_id`` owns the
skill outright.
Returns the DB record so callers that need owner info (e.g. delete
cascade) can reuse it. Raises ``ValueError`` (mapped to a tool error
visible to the LLM) on refusal.
"""
record = await store.get_any(name)
if record is None:
# No DB row — could be a legacy/orphan skill. Refuse rather than
# touch blindly; users should adopt it via /api/skills/reconcile-custom
# or an admin can clean it up via the Web UI.
raise ValueError(
f"Refused: skill '{name}' has no ownership record. Ask a human to adopt or manage it via the Web UI."
)
owner = record.get("owner_user_id")
if owner is None:
raise ValueError(f"Refused: skill '{name}' is built-in and cannot be modified by an agent.")
if owner != user_id:
raise ValueError(f"Refused: skill '{name}' is owned by another user.")
return record
async def _skill_manage_impl(
runtime: ToolRuntime[ContextT, ThreadState],
action: str,
name: str,
content: str | None = None,
path: str | None = None,
find: str | None = None,
replace: str | None = None,
expected_count: int | None = None,
) -> str:
"""Manage custom skills under skills/custom/.
Args:
action: One of create, patch, edit, delete, write_file, remove_file.
For listing or viewing skills, prefer the dedicated
``skill_list`` / ``skill_view`` tools — but ``action='list'``
and ``action='view'`` are accepted here as convenience
aliases that delegate to those tools.
name: Skill name in hyphen-case.
content: New file content for create, edit, or write_file.
path: Supporting file path for write_file or remove_file.
find: Existing text to replace for patch.
replace: Replacement text for patch.
expected_count: Optional expected number of replacements for patch.
"""
# Read-only aliases — delegate to the dedicated tools so a model that
# over-uses skill_manage doesn't trip on Unsupported action errors.
# Pass the active agent_id through so a custom agent's skill whitelist
# is enforced on these aliases just like on skill_list/skill_view.
if action == "list":
from deerflow.tools.builtins.skill_tools import _resolve_active_agent_id, skill_list_impl
return await _to_thread(skill_list_impl, _resolve_active_agent_id(runtime))
if action == "view":
from deerflow.tools.builtins.skill_tools import _resolve_active_agent_id, skill_view_impl
return await _to_thread(skill_view_impl, name, _resolve_active_agent_id(runtime))
name = SkillStorage.validate_skill_name(name)
lock = _get_lock(name)
thread_id = _get_thread_id(runtime)
skill_storage = get_or_new_skill_storage()
# Resolved up-front so ownership checks in the write-action branches stay
# one-liners. Cheap when the DB is unconfigured (returns None).
user_id = get_effective_user_id()
skill_store = _default_skill_store()
async with lock:
if action == "create":
if await _to_thread(skill_storage.custom_skill_exists, name):
raise ValueError(f"Custom skill '{name}' already exists.")
if content is None:
raise ValueError("content is required for create.")
await _to_thread(skill_storage.validate_skill_markdown_content, name, content)
scan = await _scan_or_raise(content, executable=False, location=f"{name}/{SKILL_MD_FILE}")
await _to_thread(skill_storage.write_custom_skill, name, SKILL_MD_FILE, content)
await _to_thread(
skill_storage.append_history,
name,
_history_record(action="create", file_path=SKILL_MD_FILE, prev_content=None, new_content=content, thread_id=thread_id, scanner=scan),
)
try:
from deerflow.skills.usage import mark_agent_created
await _to_thread(mark_agent_created, name)
except Exception:
pass
# Register the new skill in the DB so the web UI listing actually
# surfaces it (custom skills without a DB row are filtered out by
# ``GET /api/skills``). Resolve the user_id *here* on the main
# async stack — contextvars don't propagate into ``to_thread``.
if skill_store is not None:
await _ensure_skill_db_registered(skill_store, name, user_id)
await refresh_skills_system_prompt_cache_async()
return f"Created custom skill '{name}'."
if action == "edit":
await _to_thread(skill_storage.ensure_custom_skill_is_editable, name)
if skill_store is not None:
await _assert_agent_may_modify(skill_store, name, user_id)
await _assert_skill_is_agent_authored(name)
if content is None:
raise ValueError("content is required for edit.")
await _to_thread(skill_storage.validate_skill_markdown_content, name, content)
scan = await _scan_or_raise(content, executable=False, location=f"{name}/{SKILL_MD_FILE}")
skill_file = skill_storage.get_custom_skill_file(name)
prev_content = await _to_thread(skill_file.read_text, encoding="utf-8")
await _to_thread(skill_storage.write_custom_skill, name, SKILL_MD_FILE, content)
await _to_thread(
skill_storage.append_history,
name,
_history_record(action="edit", file_path=SKILL_MD_FILE, prev_content=prev_content, new_content=content, thread_id=thread_id, scanner=scan),
)
await _bump_patch_best_effort(name)
await refresh_skills_system_prompt_cache_async()
return f"Updated custom skill '{name}'."
if action == "patch":
await _to_thread(skill_storage.ensure_custom_skill_is_editable, name)
if skill_store is not None:
await _assert_agent_may_modify(skill_store, name, user_id)
await _assert_skill_is_agent_authored(name)
if find is None or replace is None:
raise ValueError("find and replace are required for patch.")
skill_file = skill_storage.get_custom_skill_file(name)
prev_content = await _to_thread(skill_file.read_text, encoding="utf-8")
occurrences = prev_content.count(find)
if occurrences == 0:
raise ValueError("Patch target not found in SKILL.md.")
if expected_count is not None and occurrences != expected_count:
raise ValueError(f"Expected {expected_count} replacements but found {occurrences}.")
replacement_count = expected_count if expected_count is not None else 1
new_content = prev_content.replace(find, replace, replacement_count)
await _to_thread(skill_storage.validate_skill_markdown_content, name, new_content)
scan = await _scan_or_raise(new_content, executable=False, location=f"{name}/{SKILL_MD_FILE}")
await _to_thread(skill_storage.write_custom_skill, name, SKILL_MD_FILE, new_content)
await _to_thread(
skill_storage.append_history,
name,
_history_record(action="patch", file_path=SKILL_MD_FILE, prev_content=prev_content, new_content=new_content, thread_id=thread_id, scanner=scan),
)
await _bump_patch_best_effort(name)
await refresh_skills_system_prompt_cache_async()
return f"Patched custom skill '{name}' ({replacement_count} replacement(s) applied, {occurrences} match(es) found)."
if action == "delete":
# Ownership pre-check: LocalSkillStorage deletes purely by name,
# so without this an agent could blow away another user's skill
# just by knowing the name. Raise BEFORE touching the filesystem.
record: dict[str, Any] | None = None
if skill_store is not None:
record = await _assert_agent_may_modify(skill_store, name, user_id)
await _assert_skill_is_agent_authored(name)
await _to_thread(
skill_storage.delete_custom_skill,
name,
history_meta=_history_record(
action="delete",
file_path=SKILL_MD_FILE,
prev_content=None,
new_content=None,
thread_id=thread_id,
scanner={"decision": "allow", "reason": "Deletion requested."},
),
)
# Mirror what ``DELETE /api/skills/custom/{name}`` does: drop the
# ``.usage.json`` entry and the DB ownership row, then cascade
# the removal to every agent that referenced this skill so
# ``config.yaml`` doesn't end up with a dangling reference.
# Failures are best-effort — the on-disk delete already happened
# and is authoritative.
try:
from deerflow.skills.usage import forget
await _to_thread(forget, name)
except Exception:
logger.debug("Failed to forget usage entry for %r", name, exc_info=True)
if skill_store is not None:
try:
await skill_store.delete(name, user_id)
except Exception:
logger.debug("Failed to delete DB row for %r", name, exc_info=True)
agent_store = _default_agent_store()
if agent_store is not None:
try:
from deerflow.skills.cascade import cascade_skill_unpublished_or_deleted
await cascade_skill_unpublished_or_deleted(
name,
actor_user_id=user_id,
operation="delete",
skill_owner_user_id=(record.get("owner_user_id") if record else user_id),
agent_store=agent_store,
)
except Exception:
logger.debug("Cascade failed for deleted skill %r", name, exc_info=True)
await refresh_skills_system_prompt_cache_async()
return f"Deleted custom skill '{name}'."
if action == "write_file":
await _to_thread(skill_storage.ensure_custom_skill_is_editable, name)
if skill_store is not None:
await _assert_agent_may_modify(skill_store, name, user_id)
await _assert_skill_is_agent_authored(name)
if path is None or content is None:
raise ValueError("path and content are required for write_file.")
target = await _to_thread(skill_storage.ensure_safe_support_path, name, path)
exists = await _to_thread(target.exists)
prev_content = await _to_thread(target.read_text, encoding="utf-8") if exists else None
executable = "scripts/" in path or path.startswith("scripts/")
scan = await _scan_or_raise(content, executable=executable, location=f"{name}/{path}")
await _to_thread(skill_storage.write_custom_skill, name, path, content)
await _to_thread(
skill_storage.append_history,
name,
_history_record(action="write_file", file_path=path, prev_content=prev_content, new_content=content, thread_id=thread_id, scanner=scan),
)
return f"Wrote '{path}' for custom skill '{name}'."
if action == "remove_file":
await _to_thread(skill_storage.ensure_custom_skill_is_editable, name)
if skill_store is not None:
await _assert_agent_may_modify(skill_store, name, user_id)
await _assert_skill_is_agent_authored(name)
if path is None:
raise ValueError("path is required for remove_file.")
target = await _to_thread(skill_storage.ensure_safe_support_path, name, path)
if not await _to_thread(target.exists):
raise FileNotFoundError(f"Supporting file '{path}' not found for skill '{name}'.")
prev_content = await _to_thread(target.read_text, encoding="utf-8")
await _to_thread(target.unlink)
await _to_thread(
skill_storage.append_history,
name,
_history_record(action="remove_file", file_path=path, prev_content=prev_content, new_content=None, thread_id=thread_id, scanner={"decision": "allow", "reason": "Deletion requested."}),
)
return f"Removed '{path}' from custom skill '{name}'."
if await _to_thread(skill_storage.public_skill_exists, name):
raise ValueError(f"'{name}' is a built-in skill. To customise it, create a new skill with the same name under skills/custom/.")
raise ValueError(f"Unsupported action '{action}'.")
@tool("skill_manage", parse_docstring=True)
async def skill_manage_tool(
runtime: ToolRuntime[ContextT, ThreadState],
action: str,
name: str,
content: str | None = None,
path: str | None = None,
find: str | None = None,
replace: str | None = None,
expected_count: int | None = None,
) -> str:
"""Manage custom skills under skills/custom/.
Args:
action: One of create, patch, edit, delete, write_file, remove_file.
name: Skill name in hyphen-case.
content: New file content for create, edit, or write_file.
path: Supporting file path for write_file or remove_file.
find: Existing text to replace for patch.
replace: Replacement text for patch.
expected_count: Optional expected number of replacements for patch.
"""
return await _skill_manage_impl(
runtime=runtime,
action=action,
name=name,
content=content,
path=path,
find=find,
replace=replace,
expected_count=expected_count,
)
skill_manage_tool.func = _make_sync_tool_wrapper(_skill_manage_impl, "skill_manage")