skills_tool_plugin.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. """Plugin-provided skill serving for ``skill_view`` (``plugin:skill`` names) plus the JSON /
  2. file-serving helpers shared with the local-skill path. Helpers tests patch on the origin module
  3. (``_is_skill_disabled``, ``_parse_frontmatter``, ``skill_matches_platform``) resolve lazily."""
  4. import json
  5. import logging
  6. from contextlib import suppress
  7. from pathlib import Path
  8. from typing import Any, Dict, List
  9. from tools.skills_tool_setup import SkillReadinessStatus
  10. logger = logging.getLogger("tools.skills_tool")
  11. MAX_NAME_LENGTH = 64 # Anthropic-recommended progressive-disclosure limits
  12. MAX_DESCRIPTION_LENGTH = 1024
  13. _INJECTION_PATTERNS: list = [ # shared by local-skill and plugin-skill paths
  14. "ignore previous instructions", "ignore all previous", "you are now",
  15. "disregard your", "forget your instructions", "new instructions:",
  16. "system prompt:", "<system>", "]]>"]
  17. _SUPPORT_DIRS = ("references", "templates", "assets", "scripts")
  18. _SKILL_FILE_EXTS = {".md", ".py", ".yaml", ".yml", ".json", ".tex", ".sh"}
  19. def _json(payload: dict) -> str:
  20. return json.dumps(payload, ensure_ascii=False)
  21. def _fail(error: str, **extra) -> str:
  22. return _json({"success": False, "error": error, **extra})
  23. def _read_skill_text(path: Path) -> str:
  24. """utf-8-sig + errors="replace": user-authored SKILL.md may carry a Notepad BOM or stray
  25. bytes; pinning UTF-8 keeps skill_view deterministic across host locales."""
  26. return path.read_text(encoding="utf-8-sig", errors="replace")
  27. def _truncate_description(description: str) -> str:
  28. if len(description) <= MAX_DESCRIPTION_LENGTH:
  29. return description
  30. return description[: MAX_DESCRIPTION_LENGTH - 3] + "..."
  31. def _safe_frontmatter(path: Path | None = None, *, content: str | None = None) -> dict[str, Any]:
  32. """Frontmatter of *path* (or of *content*), ``{}`` on any read/parse failure.
  33. Parses via ``tools.skills_tool._parse_frontmatter`` so test patches are honored."""
  34. from tools import skills_tool as _st
  35. with suppress(Exception):
  36. return _st._parse_frontmatter(_read_skill_text(path) if content is None else content)[0]
  37. return {}
  38. def _available_skill_files(skill_dir: Path) -> dict[str, list[str]]:
  39. """Non-SKILL.md files grouped by support dir (+ "other" for known source extensions
  40. elsewhere); empty groups dropped."""
  41. groups: dict[str, list[str]] = {}
  42. for f in skill_dir.rglob("*"):
  43. if not f.is_file() or f.name == "SKILL.md":
  44. continue
  45. rel = f.relative_to(skill_dir).as_posix()
  46. top = rel.split("/", 1)[0] if "/" in rel else None
  47. if top in _SUPPORT_DIRS or f.suffix in _SKILL_FILE_EXTS:
  48. groups.setdefault(top if top in _SUPPORT_DIRS else "other", []).append(rel)
  49. return {k: groups[k] for k in (*_SUPPORT_DIRS, "other") if k in groups}
  50. def _serve_skill_file(
  51. skill_root: Path, file_path: str, label: str, *, hint: str | None = None,
  52. list_available: bool = False, read_error_prefix: bool = False, mark_read: bool = False) -> str:
  53. """Serve one linked file from a skill directory as a skill_view JSON result. ``hint``
  54. decorates traversal/containment errors; ``list_available`` adds the available-files listing
  55. on not-found (local); ``read_error_prefix`` wraps non-decode read errors (plugin) instead
  56. of propagating to the caller's handler."""
  57. from tools.path_security import has_traversal_component, validate_within_dir
  58. extra = {"hint": hint} if hint else {}
  59. if has_traversal_component(file_path):
  60. return _fail("Path traversal ('..') is not allowed.", **extra)
  61. target = skill_root / file_path
  62. if path_error := validate_within_dir(target, skill_root):
  63. return _fail(path_error, **extra)
  64. # is_file(), not exists(): a bare directory must take the not-found branch.
  65. if not target.is_file():
  66. listing = {} if not list_available else {
  67. "available_files": _available_skill_files(skill_root),
  68. "hint": "Use one of the available file paths listed above"}
  69. return _fail(f"File '{file_path}' not found in skill '{label}'.", **listing)
  70. try:
  71. content = _read_skill_text(target)
  72. except UnicodeDecodeError:
  73. return _json({
  74. "success": True, "name": label, "file": file_path, "is_binary": True,
  75. "content": f"[Binary file: {target.name}, size: {target.stat().st_size} bytes]"})
  76. except Exception as exc:
  77. if not read_error_prefix:
  78. raise
  79. return _fail(f"Failed to read '{file_path}': {exc}")
  80. if mark_read:
  81. _mark_background_review_read(target)
  82. return _json({
  83. "success": True, "name": label, "file": file_path, "content": content,
  84. "file_type": target.suffix})
  85. def _mark_background_review_read(path: Path) -> None:
  86. try:
  87. from tools.skill_manager_guards import mark_background_review_skill_read
  88. mark_background_review_skill_read(path)
  89. except Exception:
  90. logger.debug("Could not record background-review skill read for %s", path, exc_info=True)
  91. def _preprocess_skill(content: str, skill_dir, session_id, debug_msg: str, *args) -> str:
  92. """Apply the configured SKILL.md preprocessing; on failure log and serve raw."""
  93. try:
  94. from agent.skill_preprocessing import preprocess_skill_content
  95. return preprocess_skill_content(content, skill_dir, session_id=session_id)
  96. except Exception:
  97. logger.debug(debug_msg, *args, exc_info=True)
  98. return content
  99. def _serve_plugin_skill(
  100. skill_md: Path, namespace: str, bare: str, file_path: str | None = None, *,
  101. preprocess: bool = True, session_id: str | None = None) -> str:
  102. """Read a plugin-provided skill, apply guards, return JSON."""
  103. from hermes_cli.plugins import _get_disabled_plugins, get_plugin_manager
  104. from hermes_cli.plugins_content import plugin_skill_owners
  105. from tools import skills_tool as _st
  106. qualified_name = f"{namespace}:{bare}"
  107. if disabled := sorted(plugin_skill_owners(get_plugin_manager(), qualified_name) & _get_disabled_plugins()):
  108. return _fail(f"Plugin '{disabled[0]}' is disabled. Re-enable with: hermes plugins enable {disabled[0]}")
  109. try:
  110. content = _read_skill_text(skill_md)
  111. except Exception as e:
  112. return _fail(f"Failed to read skill '{qualified_name}': {e}")
  113. parsed_frontmatter = _safe_frontmatter(content=content)
  114. if _st._is_skill_disabled(qualified_name):
  115. return _fail(f"Skill '{qualified_name}' is disabled.")
  116. if not _st.skill_matches_platform(parsed_frontmatter):
  117. return _fail(f"Skill '{qualified_name}' is not supported on this platform.",
  118. readiness_status=SkillReadinessStatus.UNSUPPORTED.value)
  119. if file_path:
  120. return _serve_skill_file(skill_md.parent, file_path, qualified_name, read_error_prefix=True)
  121. if any(p in content.lower() for p in _INJECTION_PATTERNS):
  122. logger.warning(
  123. "Plugin skill '%s:%s' contains patterns that may indicate prompt injection", namespace, bare)
  124. banner = ""
  125. with suppress(Exception): # bundle-context banner: sibling skills of the same plugin
  126. siblings = [s for s in get_plugin_manager().list_plugin_skills(namespace) if s != bare]
  127. banner = f"[Bundle context: This skill is part of the '{namespace}' plugin." + (
  128. f"\nSibling skills: {', '.join(siblings)}.\nUse qualified form to invoke siblings "
  129. f"(e.g. {namespace}:{siblings[0]})." if siblings else "") + "]\n\n"
  130. rendered_content = content if not preprocess else _preprocess_skill(
  131. content, skill_md.parent, session_id, "Could not preprocess plugin skill %s:%s",
  132. namespace, bare)
  133. return _json({
  134. "success": True, "name": qualified_name, "content": banner + rendered_content,
  135. "description": _truncate_description(str(parsed_frontmatter.get("description", ""))),
  136. "linked_files": _plugin_skill_linked_files(skill_md.parent),
  137. "readiness_status": SkillReadinessStatus.AVAILABLE.value,
  138. "skill_dir": str(skill_md.parent)})
  139. def _plugin_skill_linked_files(skill_root: Path) -> dict[str, list[str]] | None:
  140. from tools.path_security import validate_within_dir
  141. linked: dict[str, list[str]] = {}
  142. for category in _SUPPORT_DIRS:
  143. files = [
  144. str(path.relative_to(skill_root)) for path in sorted((skill_root / category).rglob("*"))
  145. if path.is_file() and validate_within_dir(path, skill_root) is None]
  146. if files:
  147. linked[category] = files
  148. return linked or None