skill_commands.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. """Shared slash command helpers for skills (CLI and gateway both invoke /skill-name)."""
  2. import json
  3. import logging
  4. import os
  5. import re
  6. import threading
  7. from pathlib import Path
  8. from typing import Any, Dict, Mapping, Optional
  9. from hermes_constants import display_hermes_home
  10. from agent.prompt_cache_boundary import register_stable_prefix
  11. from agent.skill_preprocessing import load_skills_config as _load_skills_config, preprocess_skill_content
  12. from agent.skill_utils import AMBIGUOUS_SKILL_PREFIX
  13. logger = logging.getLogger(__name__)
  14. # Multi-slot skill-command cache keyed by the full resolved identity
  15. # (_resolve_skill_commands_platform(), _resolve_skill_commands_home(),
  16. # _resolve_skill_commands_project()). The previous single-slot memo held ONE
  17. # (platform, home, project) triple; a Desktop serve process whose identity
  18. # flaps across requests (profile-home overrides, per-session project roots)
  19. # missed on every poll and rescanned the whole skills dir ~3x/5s, re-logging
  20. # the collision warnings each time (#104849). Each distinct identity is
  21. # scanned once and memoized; reload_skills() clears every slot. Guards
  22. # publication and the freshness lookup so a reader always sees a consistent
  23. # (key, map) pair. Scanning stays outside the lock (#14536, #74574).
  24. _skill_commands_by_key: dict[tuple, dict[str, dict[str, Any]]] = {}
  25. # Keep the last map callers could actually see, even when plugin lifecycle
  26. # invalidation drops the projection cache before /reload-skills can diff it.
  27. _last_interactive_skill_commands_by_key: dict[tuple, dict[str, dict[str, Any]]] = {}
  28. # The on-disk signature each published map was scanned at (same key). The one gateway serves every
  29. # local session for its whole lifetime, so a skill installed or removed from another terminal must
  30. # move this signature and rescan on the next lookup instead of waiting for /reload-skills (CFG-8).
  31. _skill_commands_sig_by_key: dict[tuple, tuple] = {}
  32. _publish_lock = threading.Lock()
  33. # ``\w`` keeps Unicode letters (CJK, Cyrillic) so a ``name: 小说拆条`` skill registers ``/小说拆条``
  34. # instead of slugging to "" and being dropped (#12351); Telegram's ``[a-z0-9_]`` menu limit is
  35. # applied by hermes_cli/commands_platforms.py, not here.
  36. _SKILL_INVALID_CHARS = re.compile(r"[^\w-]")
  37. _SKILL_MULTI_HYPHEN = re.compile(r"-{2,}")
  38. # Skill-scaffolding markers. A /skill (or /bundle) turn is expanded into a
  39. # model-facing message embedding the full skill body; memory providers storing
  40. # the raw user turn would capture the body instead of what the user asked, so
  41. # ``extract_user_instruction_from_skill_message`` recovers just the instruction.
  42. # The markers MUST stay byte-identical to the builders (``_build_skill_message``,
  43. # ``_scaffold_header``).
  44. _SKILL_INVOCATION_PREFIX = "[IMPORTANT: The user has invoked the "
  45. _SINGLE_SKILL_MARKER = "The full skill content is loaded below.]"
  46. _SINGLE_SKILL_INSTRUCTION = "The user has provided the following instruction alongside the skill invocation: "
  47. _RUNTIME_NOTE = "\n\n[Runtime note:"
  48. _BUNDLE_MARKER = " skill bundle,"
  49. _BUNDLE_USER_INSTRUCTION = "\nUser instruction: "
  50. _BUNDLE_FIRST_SKILL_BLOCK = "\n\n[Loaded as part of the "
  51. # The skill name sits in the first quoted span of the activation note, for both
  52. # the single-skill and the bundle header ("work" / "/clean /work").
  53. _SKILL_NAME_RE = re.compile(re.escape(_SKILL_INVOCATION_PREFIX) + r'"([^"]*)"')
  54. # Gateway auto-load scaffold (gateway/run_turn.py ``_hmwa_auto_load_skills``): a channel-bound
  55. # skill prepended to the user's text on a NEW session. Unlike the invocation scaffolds above it
  56. # carries no instruction marker — the user's text simply follows the payload blocks — so the
  57. # describer strips the header + body and renders the typed request (session previews, titles).
  58. _AUTO_LOAD_PREFIX = '[IMPORTANT: The "'
  59. _AUTO_LOAD_SUFFIX_RE = re.compile(r'" skill is auto-loaded\. Follow its instructions for this session\.\]')
  60. # Closing sentence of the skill-directory footer note (see _SKILL_DIR_NOTE in this module):
  61. # the last thing in every built payload, so it marks where an auto-load payload ends and the
  62. # next payload or the user's typed text begins.
  63. _SKILL_DIR_NOTE_END = "then run them with the terminal tool using the absolute path."
  64. # SQL LIKE pattern for listing queries that recognize scaffolding before the row
  65. # reaches Python (no LIKE wildcards in the prefix, so no ESCAPE clause needed).
  66. SKILL_SCAFFOLD_SQL_LIKE = _SKILL_INVOCATION_PREFIX + "%"
  67. # Gateway auto-load scaffold (see _AUTO_LOAD_PREFIX): recognized by listing queries so
  68. # long auto-load rows get the same head+tail excerpt window and describe shaping.
  69. AUTO_LOAD_SCAFFOLD_SQL_LIKE = _AUTO_LOAD_PREFIX + "%"
  70. # Marks where a preview query joined the head and tail of a long scaffolded
  71. # message; ``describe_skill_invocation`` cuts there rather than show the body.
  72. SKILL_EXCERPT_JOINT = "\x1e"
  73. def slugify_skill_name(name: str) -> str:
  74. """Normalize a skill/bundle name to a ``/command`` slug (``Foo Bar`` -> ``foo-bar``);
  75. strips chars (``+``, ``/``) that would make invalid Telegram command names."""
  76. cmd = _SKILL_INVALID_CHARS.sub("", name.lower().replace(" ", "-").replace("_", "-"))
  77. return _SKILL_MULTI_HYPHEN.sub("-", cmd).strip("-")
  78. def append_user_instruction(parts: list, instruction: str) -> str:
  79. """Append the instruction line to ``parts``; return the stable prefix, which
  80. ends exactly at the instruction marker so (registered with
  81. ``agent.prompt_cache_boundary``) the cache planner can break on the scaffold.
  82. Single construction site guarantees the prefix is a byte-prefix of the message.
  83. Shared by every builder that ends a static skill scaffold with the caller-supplied volatile instruction
  84. (single-skill invocations, cron job prompts). Keeping construction in one place guarantees the
  85. registered prefix stays a byte-prefix of the built message — the invariant the request-time split
  86. depends on. See #81867.
  87. """
  88. stable_prefix = "\n".join(parts) + "\n" + _SINGLE_SKILL_INSTRUCTION
  89. parts.append(f"{_SINGLE_SKILL_INSTRUCTION}{instruction}")
  90. return stable_prefix
  91. def extract_user_instruction_from_skill_message(content: Any) -> Optional[str]:
  92. """Recover the user's instruction from a slash-skill-expanded turn: the
  93. string unchanged when it is NOT scaffolding, the extracted instruction when
  94. the scaffolding carried one, or ``None`` for a bare ``/skill`` invocation."""
  95. if not isinstance(content, str):
  96. return None
  97. if not content.startswith(_SKILL_INVOCATION_PREFIX):
  98. return content
  99. if _BUNDLE_MARKER in content:
  100. # Bundles put the instruction before the loaded skills: FIRST marker is the user's.
  101. return _cut_after(content, _BUNDLE_USER_INSTRUCTION, _BUNDLE_FIRST_SKILL_BLOCK, content.find)
  102. if _SINGLE_SKILL_MARKER in content:
  103. # The instruction follows the skill body (which may quote the marker): LAST marker is the user's.
  104. return _cut_after(content, _SINGLE_SKILL_INSTRUCTION, _RUNTIME_NOTE, content.rfind)
  105. return None
  106. def _describe_auto_loaded_skill_turn(content: str) -> Optional[str]:
  107. """``[IMPORTANT: The "X" skill is auto-loaded. …]`` + payload(s) + typed text
  108. -> the typed text.
  109. ``_hmwa_auto_load_skills`` builds each payload with ``_build_skill_message``
  110. (activation header, body, then the skill-directory footer note) and appends the
  111. user's text as the final block. The footer's closing sentence is the reliable
  112. payload-end marker: the user's text is what follows the LAST footer. A header
  113. quoted inside a body (a skill embedding the scaffold in an example) carries no
  114. footer, so it cannot end the payload early. ``/<skill>`` renders when no user
  115. text follows, matching the single-skill describer's bare-invocation shape."""
  116. if not content.startswith(_AUTO_LOAD_PREFIX):
  117. return None
  118. name_match = re.match(re.escape(_AUTO_LOAD_PREFIX) + r'([^"]*)"', content)
  119. name = name_match.group(1) if name_match else ""
  120. # The payload footer ends with this exact sentence (_build_skill_message); the
  121. # user's text is the last thing after the FINAL footer in the message.
  122. footer_end = content.rfind(_SKILL_DIR_NOTE_END)
  123. if footer_end == -1:
  124. return f"/{name}" if name else None
  125. tail = content[footer_end + len(_SKILL_DIR_NOTE_END):].lstrip()
  126. while block_end := next((end for start, end in _TRAILING_BLOCK_ENDS if tail.startswith(start)), None):
  127. cut = tail.find(block_end)
  128. tail = tail[cut + len(block_end):].lstrip() if cut >= 0 else ""
  129. if not tail.strip():
  130. return f"/{name}" if name else None
  131. return " ".join(tail.split()) or None
  132. def describe_skill_invocation(content: Any, separator: str = " — ") -> Optional[str]:
  133. """Render a slash-skill-expanded turn the way the user typed it:
  134. ``"/work — fix the title leak"``, ``"/work"`` for a bare invocation, or
  135. ``None`` when *content* is not scaffolding. ``separator=" "`` gives the
  136. literal invocation as typed (chat transcripts).
  137. A gateway auto-load scaffold (channel-bound skill on a new session) is also
  138. scaffolding: the typed request follows the skill payload, so it renders as
  139. that request — the header/body never reaches a preview or a title (#48359).
  140. """
  141. if not isinstance(content, str):
  142. return None
  143. if content.startswith(_AUTO_LOAD_PREFIX):
  144. return _describe_auto_loaded_skill_turn(content)
  145. if not content.startswith(_SKILL_INVOCATION_PREFIX):
  146. return None
  147. match = _SKILL_NAME_RE.match(content)
  148. name = (match.group(1) if match else "").strip()
  149. # Bundle headers already carry their typed "/a /b" keys; a single skill is a bare name.
  150. label = name if name.startswith("/") else f"/{name}"
  151. instruction = extract_user_instruction_from_skill_message(content)
  152. if instruction and instruction is not content:
  153. # An excerpt (head + tail joined by SKILL_EXCERPT_JOINT) can put the
  154. # joint inside the span — keep only the side the marker was found on.
  155. instruction = " ".join(instruction.split(SKILL_EXCERPT_JOINT)[0].split())
  156. if instruction:
  157. return f"{label}{separator}{instruction}" if name else instruction
  158. return label if name else None
  159. _AUTO_LOAD_HEADER_RE = re.compile(re.escape(_AUTO_LOAD_PREFIX) + r'([^"]*)' + _AUTO_LOAD_SUFFIX_RE.pattern)
  160. _BUNDLE_LOADED_RE = re.compile(r"^Skills loaded: (.+)$", re.MULTILINE)
  161. def skills_loaded_by_scaffold(content: Any) -> list[str]:
  162. """Skill names a slash-skill, bundle/stacked or gateway auto-load turn carries inline; ``[]`` for any
  163. other text. Only a complete activation header counts, so typed text that merely starts like one
  164. (``[IMPORTANT: The "config" file is broken]``) is not mistaken for a skill load."""
  165. if not isinstance(content, str):
  166. return []
  167. if content.startswith(_AUTO_LOAD_PREFIX):
  168. return [m.group(1) for m in _AUTO_LOAD_HEADER_RE.finditer(content)] if _AUTO_LOAD_HEADER_RE.match(content) else []
  169. if not content.startswith(_SKILL_INVOCATION_PREFIX):
  170. return []
  171. header = content.split("\n", 1)[0]
  172. if _BUNDLE_MARKER in header:
  173. loaded = _BUNDLE_LOADED_RE.search(content)
  174. return [n.strip() for n in loaded.group(1).split(",") if n.strip()] if loaded else []
  175. match = _SKILL_NAME_RE.match(content)
  176. return [match.group(1)] if header.endswith(_SINGLE_SKILL_MARKER) and match and match.group(1) else []
  177. def _cut_after(message: str, marker: str, stop_marker: str, find) -> Optional[str]:
  178. """Text between *marker* (located with ``find``) and *stop_marker*, stripped; None if absent/empty."""
  179. marker_idx = find(marker)
  180. if marker_idx < 0:
  181. return None
  182. return message[marker_idx + len(marker):].split(stop_marker, 1)[0].strip() or None
  183. def _resolve_skill_commands_platform() -> Optional[str]:
  184. """Current platform scope for disabled-skill filtering, or None (CLI, RL,
  185. scripts). A change invalidates the scan cache so each platform sees its
  186. own ``skills.platform_disabled`` view.
  187. Used to detect when the active platform has shifted so :func:`get_skill_commands` can drop a stale cache
  188. that was populated for a different platform's ``skills.platform_disabled`` view (#14536).
  189. """
  190. try:
  191. from gateway.session_context import get_session_env
  192. resolved_platform = os.getenv("HERMES_PLATFORM") or get_session_env("HERMES_SESSION_PLATFORM")
  193. except Exception:
  194. resolved_platform = os.getenv("HERMES_PLATFORM")
  195. return resolved_platform or None
  196. def _resolve_skill_commands_home() -> str:
  197. """Effective Hermes home the scan is scoped to (profiles carry their own
  198. ``skills.external_dirs``, so a profile switch must invalidate the cache).
  199. A gateway session can switch between profiles that each carry their own ``skills.external_dirs`` (via
  200. ``set_hermes_home_override``), but the module-level scan only tracked
  201. ``_resolve_skill_commands_platform()``. Switching profiles without a platform change left the previous
  202. profile's skill list cached, so ``get_skill_commands()`` reported a cache miss for skills that only
  203. exist under the new profile (#88023).
  204. """
  205. from hermes_constants import get_hermes_home
  206. return str(get_hermes_home())
  207. def _resolve_skill_commands_project() -> Optional[str]:
  208. """The project root the scan's project skills resolve from (None outside a repo). One multi-session
  209. host serves sessions in different repos; without this tag the first session's project skills stayed
  210. published for every other session's ``get_skill_commands`` lookup (#114359)."""
  211. from agent.skill_utils import find_project_root
  212. root = find_project_root()
  213. return str(root) if root is not None else None
  214. def _load_skill_payload(skill_identifier: str, task_id: str | None = None) -> tuple[dict[str, Any], Path | None, str] | None:
  215. """Load a skill by name/path and return (loaded_payload, skill_dir, display_name)."""
  216. from agent.safe_worker_policy import safe_worker_enabled
  217. if safe_worker_enabled():
  218. return None
  219. raw_identifier = (skill_identifier or "").strip()
  220. if not raw_identifier:
  221. return None
  222. try:
  223. from tools.skills_tool import _skills_dir, skill_view
  224. from agent.skill_utils import normalize_skill_lookup_name
  225. normalized = normalize_skill_lookup_name(raw_identifier)
  226. loaded_skill = json.loads(skill_view(normalized, task_id=task_id, preprocess=False))
  227. except Exception:
  228. return None
  229. if not loaded_skill.get("success"):
  230. return None
  231. skill_path = str(loaded_skill.get("path") or "")
  232. skill_dir = None
  233. # Prefer the absolute skill_dir from skill_view() (correct for external
  234. # skills too); fall back to SKILLS_DIR-relative reconstruction for legacy responses.
  235. if loaded_skill.get("skill_dir"):
  236. skill_dir = Path(loaded_skill["skill_dir"])
  237. elif skill_path:
  238. try:
  239. skill_dir = _skills_dir() / Path(skill_path).parent
  240. except Exception:
  241. skill_dir = None
  242. return loaded_skill, skill_dir, str(loaded_skill.get("name") or normalized)
  243. def ambiguous_skill_label(identifier: str, payload: dict) -> Optional[str]:
  244. """``Ambiguous skill name X: use one of <paths>`` when a failed skill_view *payload* is a same-tier
  245. name collision, else None — so preload/cron say why instead of "Unknown"/"not found"."""
  246. load_names = payload.get("load_names") if isinstance(payload, dict) else None
  247. return f"{AMBIGUOUS_SKILL_PREFIX}{identifier}: use one of {', '.join(load_names)}" if load_names else None
  248. def _missing_skill_label(identifier: str) -> str:
  249. """Display form of an identifier that failed to load (failure path only: re-asks skill_view)."""
  250. try:
  251. from tools.skills_tool import skill_view
  252. from agent.skill_utils import normalize_skill_lookup_name
  253. payload = json.loads(skill_view(normalize_skill_lookup_name(identifier), preprocess=False))
  254. except Exception:
  255. return identifier
  256. return ambiguous_skill_label(identifier, payload) or identifier
  257. def format_missing_skills(missing: list[str]) -> str:
  258. """One error line for unresolved preload identifiers: ambiguous ones keep their own wording,
  259. the rest are reported as ``Unknown skill(s): ...``."""
  260. ambiguous = [m for m in missing if m.startswith(AMBIGUOUS_SKILL_PREFIX)]
  261. unknown = [m for m in missing if m not in ambiguous]
  262. return "; ".join(ambiguous + ([f"Unknown skill(s): {', '.join(unknown)}"] if unknown else []))
  263. def _inject_skill_config(loaded_skill: dict[str, Any], parts: list[str]) -> None:
  264. """Append a ``[Skill config: ...]`` block with resolved ``metadata.hermes.config``
  265. values so the agent needn't read config.yaml. Any failure leaves the message without it."""
  266. try:
  267. from agent.skill_utils import extract_skill_config_vars, parse_frontmatter, resolve_skill_config_values
  268. raw_content = str(loaded_skill.get("raw_content") or loaded_skill.get("content") or "")
  269. frontmatter, _ = parse_frontmatter(raw_content)
  270. resolved = resolve_skill_config_values(extract_skill_config_vars(frontmatter))
  271. if not resolved:
  272. return
  273. parts.append("")
  274. parts.append(f"[Skill config (from {display_hermes_home()}/config.yaml):")
  275. parts.extend(f" {key} = {str(value) if value else '(not set)'}" for key, value in resolved.items())
  276. parts.append("]")
  277. except Exception:
  278. pass
  279. _SKILL_DIR_NOTE = (
  280. "Resolve any relative paths in this skill (e.g. `scripts/foo.js`, "
  281. "`templates/config.yaml`) against that directory, then run them "
  282. "with the terminal tool using the absolute path."
  283. )
  284. # Closing text of the optional blocks _build_skill_message appends after the directory note; the
  285. # auto-load describer skips them so they are never read as the user's typed request.
  286. _SUPPORTING_FILES_END = "/scripts/foo.js`)."
  287. _TRAILING_BLOCK_ENDS = (("[Skill config (", "\n]"), ("[Skill setup note: ", "]\n\n"),
  288. ("[This skill has supporting files", _SUPPORTING_FILES_END))
  289. _SETUP_SKIPPED_NOTE = (
  290. "Required environment setup was skipped. Continue loading the skill "
  291. "and explain any reduced functionality if it matters."
  292. )
  293. def _setup_note(loaded_skill: dict[str, Any]) -> Optional[str]:
  294. if loaded_skill.get("setup_skipped"):
  295. return _SETUP_SKIPPED_NOTE
  296. return loaded_skill.get("gateway_setup_hint") or (
  297. loaded_skill.get("setup_note") if loaded_skill.get("setup_needed") else None
  298. ) or None
  299. def _supporting_files(loaded_skill: dict[str, Any], skill_dir: Path | None) -> list[str]:
  300. """Skill-relative support file paths: from ``linked_files`` or a disk walk."""
  301. linked = (loaded_skill.get("linked_files") or {}).values()
  302. supporting = [Path(entry).as_posix() for entries in linked if isinstance(entries, list) for entry in entries]
  303. if not supporting and skill_dir:
  304. for subdir in ("references", "templates", "scripts", "assets"):
  305. files = sorted((skill_dir / subdir).rglob("*"))
  306. # as_posix so listed paths match the footer's examples (scripts/foo.js)
  307. # on every OS — str(relative_to) emits backslashes on Windows.
  308. supporting += [f.relative_to(skill_dir).as_posix() for f in files if f.is_file() and not f.is_symlink()]
  309. return supporting
  310. def _build_skill_message(
  311. loaded_skill: dict[str, Any],
  312. skill_dir: Path | None,
  313. activation_note: str,
  314. user_instruction: str = "",
  315. runtime_note: str = "",
  316. session_id: str | None = None,
  317. ) -> str:
  318. """Format a loaded skill into a user/system message payload."""
  319. from tools.skills_tool import _skills_dir
  320. # Preprocess first so downstream blocks see the expanded content.
  321. content = preprocess_skill_content(
  322. str(loaded_skill.get("content") or ""), skill_dir, session_id, skills_cfg=_load_skills_config(),
  323. )
  324. parts = [activation_note, "", content.strip()]
  325. # Absolute skill dir lets the agent run bundled scripts without a skill_view() round-trip.
  326. if skill_dir:
  327. parts += ["", f"[Skill directory: {skill_dir}]", _SKILL_DIR_NOTE]
  328. _inject_skill_config(loaded_skill, parts)
  329. setup_note = _setup_note(loaded_skill)
  330. if setup_note:
  331. parts += ["", f"[Skill setup note: {setup_note}]"]
  332. supporting = _supporting_files(loaded_skill, skill_dir)
  333. if supporting and skill_dir:
  334. try:
  335. skill_view_target = str(skill_dir.relative_to(_skills_dir()))
  336. except ValueError:
  337. skill_view_target = str(loaded_skill.get("name") or skill_dir.name)
  338. parts += ["", "[This skill has supporting files (paths relative to the skill directory above):]"]
  339. parts += [f"- {sf}" for sf in supporting]
  340. parts.append(
  341. f'\nLoad any of these with skill_view(name="{skill_view_target}", '
  342. f'file_path="<path>"), or run scripts directly by absolute path '
  343. f"(e.g. `node {skill_dir}{_SUPPORTING_FILES_END}"
  344. )
  345. stable_prefix = None
  346. if user_instruction:
  347. parts.append("")
  348. # Everything before the volatile instruction is a stable scaffold; the
  349. # registered boundary lets the cache planner break there (see append_user_instruction).
  350. # Everything before the caller-supplied instruction is a stable scaffold; declare the exact boundary
  351. # so the Anthropic cache planner can put a breakpoint on it instead of caching the whole message as
  352. # one atomic block (#81867). The static instruction prose stays on the stable side; the volatile
  353. # instruction (webhook payload, ticket IDs, timestamps) and any runtime note ride in the tail.
  354. stable_prefix = append_user_instruction(parts, user_instruction)
  355. if runtime_note:
  356. parts += ["", f"[Runtime note: {runtime_note}]"]
  357. message = "\n".join(parts)
  358. if stable_prefix is not None and message.startswith(stable_prefix) and len(message) > len(stable_prefix):
  359. register_stable_prefix(stable_prefix)
  360. return message
  361. def _render_skill_block(
  362. loaded: tuple[dict[str, Any], Path | None, str], activation_note: str, task_id: str | None, **message_kwargs: str,
  363. ) -> str:
  364. """Bump Curator usage tracking (never fatal) and build the message block for one loaded skill."""
  365. loaded_skill, skill_dir, skill_name = loaded
  366. try:
  367. # Track active usage for Curator lifecycle management (#17782)
  368. # Track active usage for Curator lifecycle management (#17782)
  369. # Track active usage for Curator lifecycle management (#17782)
  370. from tools.skill_usage import bump_use
  371. bump_use(skill_name, task_id=task_id)
  372. except Exception:
  373. pass
  374. return _build_skill_message(loaded_skill, skill_dir, activation_note, session_id=task_id, **message_kwargs)
  375. def _scaffold_header(
  376. subject: str, loaded_names: list[str], *, lead_lines: list[str] | None = None,
  377. missing: list[str] | None = None, disabled: list[str] | None = None,
  378. extra_instruction: str = "", user_instruction: str = "",
  379. ) -> str:
  380. """Header for multi-skill messages (bundles and stacked invocations).
  381. ``subject`` must end in " skill bundle" so the bundle-format extractor applies."""
  382. lines = [
  383. f"[IMPORTANT: The user has invoked the {subject}, "
  384. f"loading {len(loaded_names)} skills together. Treat every skill below "
  385. "as active guidance for this turn.]",
  386. "",
  387. *(lead_lines or []),
  388. f"Skills loaded: {', '.join(loaded_names)}",
  389. ]
  390. if missing:
  391. lines.append(f"Skills missing (skipped): {', '.join(missing)}")
  392. if disabled:
  393. lines.append(f"Skills disabled for this platform (skipped): {', '.join(disabled)}")
  394. if extra_instruction:
  395. lines += ["", f"Bundle instruction: {extra_instruction}"]
  396. if user_instruction:
  397. lines += ["", f"User instruction: {user_instruction}"]
  398. return "\n".join(lines)
  399. _SCAN_SKIP_PARTS = {'.git', '.github', '.hub', '.archive', '.locks'}
  400. def skill_command_collision_note(name: str) -> Optional[str]:
  401. """User-facing note when *name*'s slash slug is a core command (name or alias), else None.
  402. The single source of the collision predicate: ``scan_skill_commands`` uses it to skip
  403. auto-registration (the shadowing guard from 370ebf2d3 — the skill map is consulted before
  404. built-in handlers), and the ``/skills`` listing plus the command palette render the note so
  405. the skipped skill is explained where the user looks, not only in the log.
  406. """
  407. from hermes_cli.commands import resolve_command
  408. cmd_name = slugify_skill_name(name)
  409. if not cmd_name or resolve_command(cmd_name) is None:
  410. return None
  411. return f"slash command /{cmd_name} unavailable — name taken by built-in; use /skill {name}"
  412. def _scan_skill_md(skill_md: Path, disabled: set, seen_names: set, commands: dict[str, dict[str, Any]]) -> None:
  413. """Register one SKILL.md in *commands* (no-op when filtered or colliding)."""
  414. from tools.skills_tool import _parse_frontmatter, skill_matches_apps, skill_matches_platform, skill_matches_environment
  415. if any(part in _SCAN_SKIP_PARTS for part in skill_md.parts):
  416. return
  417. frontmatter, body = _parse_frontmatter(skill_md.read_text(encoding='utf-8-sig'))
  418. # OS gate is hard; environment gate (kanban/docker/s6) is offer-time only.
  419. if not skill_matches_platform(frontmatter) or not skill_matches_environment(frontmatter) or not skill_matches_apps(frontmatter):
  420. return
  421. name = frontmatter.get('name', skill_md.parent.name)
  422. if name in seen_names or name in disabled:
  423. return
  424. description = frontmatter.get('description', '') or next(
  425. (line.strip()[:80] for line in body.strip().split('\n') if line.strip() and not line.strip().startswith('#')),
  426. '',
  427. )
  428. seen_names.add(name)
  429. cmd_name = slugify_skill_name(name)
  430. if not cmd_name:
  431. return
  432. # A collision with a core command (name or alias) skips auto-registration; the skill stays
  433. # loadable via /skill <name>. The same predicate feeds the /skills + palette notes.
  434. if skill_command_collision_note(name) is not None:
  435. logger.warning("Skill %r generates slash command '/%s' which collides with a core Hermes command; "
  436. "skipping auto-registration. Use '/skill %s' instead.", name, cmd_name, name)
  437. return
  438. # Dedup on the slug too: "git_helper" and "git-helper" normalize the same.
  439. # First-wins preserves project > local > external precedence.
  440. cmd_key = f"/{cmd_name}"
  441. if cmd_key in commands:
  442. logger.warning("Skill %r maps to slash command %s already claimed by %r; keeping the first and skipping this one.",
  443. name, cmd_key, commands[cmd_key]["name"])
  444. return
  445. commands[cmd_key] = {"name": name, "description": description or f"Invoke the {name} skill",
  446. "skill_md_path": str(skill_md), "skill_dir": str(skill_md.parent)}
  447. def scan_skill_commands() -> dict[str, dict[str, Any]]:
  448. """Scan skill dirs and return {"/skill-name": {name, description, skill_md_path, skill_dir}}.
  449. Builds a local map and publishes once at the end: writing straight into the
  450. global exposed partial results to overlapping scans, which then logged
  451. bogus "already claimed" collisions against their own incumbents."""
  452. from agent.safe_worker_policy import safe_worker_enabled
  453. if safe_worker_enabled():
  454. return {}
  455. key = (_resolve_skill_commands_platform(), _resolve_skill_commands_home(), _resolve_skill_commands_project())
  456. # Build into a local map and publish once, at the end. Writing straight into the global made a scan's
  457. # partial results visible to everything else in the process: a second, overlapping scan deduped against
  458. # its own (empty) ``seen_names`` but collided against the first scan's already- published slugs, logging
  459. # one bogus "already claimed" warning per skill — each naming the same skill as its own incumbent
  460. # (#74574).
  461. # Taken BEFORE the scan: an install racing the scan moves it, so the next lookup rescans.
  462. signature = _skill_dirs_signature()
  463. commands: dict[str, dict[str, Any]] = {}
  464. try:
  465. from tools.skills_tool import _get_disabled_skill_names, _skill_catalog
  466. disabled = _get_disabled_skill_names()
  467. seen_names: set = set()
  468. # Only names skill_view resolves to exactly this file get a /command: the shared catalog applies
  469. # project > local > create_dir > external precedence (live profile dir, #67277) and leaves
  470. # same-tier duplicates to their exact paths (`/skill a/one`), so a bare slug never guesses.
  471. for entry in _skill_catalog():
  472. if entry["status"] == "unique":
  473. try:
  474. _scan_skill_md(Path(entry["path"]), disabled, seen_names, commands)
  475. except Exception:
  476. continue
  477. except Exception:
  478. logger.debug("Skill command scan failed", exc_info=True)
  479. # Publish the scanned map atomically: a reader must see a consistent
  480. # (key, map) pair. Only the publish/lookup pair is locked; the scan above
  481. # (file I/O, deferred imports) stays outside it (#14536, #74574).
  482. with _publish_lock:
  483. # Publishing under the lock keeps the (key, map) pair consistent for any
  484. # reader between the lookup and this store (#14536, #74574); the scan above
  485. # (file I/O, deferred imports) stays outside it.
  486. _skill_commands_sig_by_key[key] = signature
  487. _publish_scope(_skill_commands_by_key, key, commands)
  488. return commands
  489. # The most scopes the change watcher signs per pass (each is one ~1 ms stat walk).
  490. _MAX_WATCHED_SCOPES = 32
  491. # Scopes kept resident (LRU). Each distinct (platform, profile, project) keeps a whole command map; a
  492. # long-lived gateway visiting many repos would otherwise keep one per repo forever. An evicted scope
  493. # rescans on its next lookup, exactly as after /reload-skills.
  494. _MAX_CACHED_SCOPES = 2 * _MAX_WATCHED_SCOPES
  495. # One recency order for every per-scope table: separate orders let a scope used recently in one table be
  496. # the oldest in another, so evicting by either dropped a live scope's /reload-skills baseline.
  497. _scope_recency: dict[tuple, None] = {}
  498. def _publish_scope(table: Optional[dict], key: tuple, value: Any = None) -> None:
  499. """Mark ``key`` most recently used (storing ``value`` in ``table`` unless it is None); past the cap,
  500. the least recently used scope leaves every per-scope table together. Caller holds ``_publish_lock``."""
  501. if table is not None:
  502. table[key] = value
  503. _scope_recency.pop(key, None)
  504. _scope_recency[key] = None
  505. while len(_scope_recency) > _MAX_CACHED_SCOPES:
  506. stale = next(iter(_scope_recency))
  507. for scoped in (_scope_recency, _skill_commands_by_key, _skill_commands_sig_by_key, _last_interactive_skill_commands_by_key):
  508. scoped.pop(stale, None)
  509. def published_scopes_signature() -> tuple:
  510. """Signature of every skill scope a session has resolved commands for, plus the ambient one.
  511. One gateway serves sessions in several profiles and repos; each published ``(platform, home,
  512. project)`` key names a scope whose roots (that profile's skills/external dirs, that repo's trusted
  513. project skills) a viewer is looking at. The change watcher (``skills.changed``) compares this, so
  514. an install in a session's repo B notifies viewers even when the gateway was launched in repo A.
  515. Only command maps/catalogs refetch; a conversation's stored system prompt is never rebuilt.
  516. """
  517. from agent.runtime_cwd import reset_session_cwd, set_session_cwd
  518. from hermes_constants import reset_hermes_home_override, set_hermes_home_override
  519. with _publish_lock:
  520. keys = list(_skill_commands_by_key)
  521. scopes = sorted({(home, project) for _platform, home, project in keys if home})[:_MAX_WATCHED_SCOPES]
  522. rows = [("", None, _skill_dirs_signature())]
  523. for home, project in scopes:
  524. home_token = set_hermes_home_override(home)
  525. # No project: an empty session cwd would fall back to the process cwd; "/" resolves no repo.
  526. cwd_token = set_session_cwd(project or os.path.sep)
  527. try:
  528. rows.append((home, project, _skill_dirs_signature()))
  529. finally:
  530. reset_session_cwd(cwd_token)
  531. reset_hermes_home_override(home_token)
  532. return tuple(rows)
  533. def _skill_dirs_signature() -> Optional[tuple]:
  534. """Stat-cheap change signature of every skill root (the catalog's own: the mtime and child names of
  535. every directory the catalog walks, depth-bounded, plus the disabled set and the platform). None when
  536. it cannot be computed (a root that cannot be stat'ed), which keeps the published map rather than
  537. rescanning on every lookup. Any other error raises: the catalog scan itself takes the same signature
  538. unguarded (``tools.skills_tool._skill_catalog``), and a swallowed bug would pin a stale map silently."""
  539. from tools.skills_tool import _get_disabled_skill_names, skill_search_dirs, _skills_scan_signature
  540. try:
  541. roots, _active = skill_search_dirs()
  542. return _skills_scan_signature([d for _tier, d in roots], _get_disabled_skill_names())
  543. except OSError:
  544. logger.debug("Skill dir signature failed", exc_info=True)
  545. return None
  546. def get_skill_commands() -> dict[str, dict[str, Any]]:
  547. """Return the current skill commands mapping (scan first if empty). Rescans
  548. when the platform scope (one gateway serving Telegram and Discord) or the
  549. active profile's home (Desktop profile switch) or the session's project root (two sessions in two
  550. repos) changes, so each sees its own ``platform_disabled`` / ``external_dirs`` / project-skill view.
  551. See #14536, #88023, #114359, #104849.
  552. """
  553. from agent.safe_worker_policy import safe_worker_enabled
  554. if safe_worker_enabled():
  555. return {}
  556. key = (_resolve_skill_commands_platform(), _resolve_skill_commands_home(), _resolve_skill_commands_project())
  557. with _publish_lock:
  558. cached = _skill_commands_by_key.get(key)
  559. scanned_at = _skill_commands_sig_by_key.get(key)
  560. if cached is not None:
  561. _publish_scope(None, key)
  562. if cached is not None:
  563. # A skill installed or removed from another terminal moves the dir signature: rescan, so the
  564. # long-lived gateway's palette and dispatch see it without /reload-skills (CFG-8).
  565. current = _skill_dirs_signature()
  566. if current is None or scanned_at is None or current == scanned_at:
  567. return cached
  568. # Scan outside the lock — file I/O and deferred imports; concurrent scans
  569. # are safe since each builds its own map.
  570. return scan_skill_commands()
  571. # Plugin projection cache. The projection re-parses every plugin SKILL.md and sits on the
  572. # per-keystroke completion path (94 ms per Tab measured with 60 plugin skills), so it is reused
  573. # while its tag holds: the resolved Hermes home (plugin managers are home-keyed, so profiles never
  574. # share a registry) plus the registered qualified names (a plugin enable/disable/install changes
  575. # them). ``reload_skills()`` drops it explicitly to pick up edited SKILL.md files.
  576. _plugin_skill_commands: dict[str, dict[str, Any]] = {}
  577. _plugin_skill_commands_tag: Optional[tuple] = None
  578. def invalidate_plugin_skill_commands() -> None:
  579. """Drop the cached plugin skill projection."""
  580. global _plugin_skill_commands, _plugin_skill_commands_tag
  581. with _publish_lock:
  582. _plugin_skill_commands = {}
  583. _plugin_skill_commands_tag = None
  584. def get_plugin_skill_commands() -> dict[str, dict[str, Any]]:
  585. """Project enabled plugin skills into the interactive-only slash namespace (``/plugin:skill``).
  586. Config disable lists (``skills.disabled``, ``plugins.disabled``) are applied on EVERY call, so a
  587. config-only disable takes effect without a rescan.
  588. """
  589. from agent.skill_utils import get_disabled_skill_names
  590. from hermes_cli.plugins import discover_plugins, get_plugin_manager
  591. from hermes_cli.plugins_content import plugin_skill_owners
  592. from hermes_cli.plugins_discovery import _get_disabled_plugins
  593. from hermes_constants import get_hermes_home
  594. discover_plugins() # no-op once this home is discovered
  595. manager = get_plugin_manager()
  596. metadata = manager.list_plugin_skill_metadata()
  597. tag = (str(get_hermes_home()), tuple(str(m.get("name") or "") for m in metadata))
  598. with _publish_lock:
  599. cached, is_fresh = _plugin_skill_commands, _plugin_skill_commands_tag == tag
  600. if not is_fresh:
  601. cached = _scan_plugin_skill_commands(manager, metadata, tag)
  602. disabled = get_disabled_skill_names()
  603. disabled_plugins = _get_disabled_plugins()
  604. if not disabled and not disabled_plugins:
  605. return cached
  606. return {
  607. key: info for key, info in cached.items()
  608. if not (info["name"] in disabled or info["name"].split(":", 1)[1] in disabled
  609. or plugin_skill_owners(manager, info["name"]) & disabled_plugins)
  610. }
  611. def _scan_plugin_skill_commands(manager, metadata: list, tag: tuple) -> dict[str, dict[str, Any]]:
  612. """Build the plugin skill projection and publish it with its tag atomically."""
  613. global _plugin_skill_commands, _plugin_skill_commands_tag
  614. from tools.skills_tool import (
  615. _parse_frontmatter, skill_matches_apps, skill_matches_environment,
  616. skill_matches_platform,
  617. )
  618. commands: dict[str, dict[str, Any]] = {}
  619. for entry in metadata:
  620. qualified = str(entry.get("name") or "").strip()
  621. if ":" not in qualified:
  622. continue
  623. skill_md = manager.find_plugin_skill(qualified)
  624. if skill_md is None or not skill_md.is_file():
  625. continue
  626. try:
  627. parsed, _ = _parse_frontmatter(skill_md.read_text(encoding="utf-8-sig", errors="replace"))
  628. except OSError:
  629. continue
  630. # Offer from the file we will actually load, not registration-time hints.
  631. if not (skill_matches_platform(parsed) and skill_matches_environment(parsed) and skill_matches_apps(parsed)):
  632. continue
  633. key = f"/{qualified.lower()}"
  634. if skill_command_collision_note(qualified) is not None or key in commands:
  635. logger.warning("Plugin skill %r collides with an existing slash command; skipping", qualified)
  636. continue
  637. commands[key] = {
  638. "name": qualified, "description": str(parsed.get("description") or entry.get("description")
  639. or f"Invoke the {qualified} plugin skill").strip(),
  640. "skill_identifier": qualified, "skill_md_path": str(skill_md),
  641. "skill_dir": str(skill_md.parent), "source": "plugin",
  642. }
  643. with _publish_lock:
  644. _plugin_skill_commands, _plugin_skill_commands_tag = commands, tag
  645. return commands
  646. def _merge_interactive_skill_commands(
  647. filesystem_commands: dict[str, dict[str, Any]], plugin_commands: dict[str, dict[str, Any]],
  648. ) -> dict[str, dict[str, Any]]:
  649. """Merge interactive sources with filesystem commands winning collisions."""
  650. commands = dict(filesystem_commands)
  651. for command, info in plugin_commands.items():
  652. if command in commands:
  653. logger.warning("Plugin skill %r collides with %r; keeping the first", command, commands[command]["name"])
  654. else:
  655. commands[command] = info
  656. return commands
  657. def get_interactive_skill_commands() -> dict[str, dict[str, Any]]:
  658. """Filesystem skills plus profile-scoped plugin skills; never use for
  659. messaging/native command menus (plugin skills are CLI/TUI/desktop only)."""
  660. identity = (_resolve_skill_commands_platform(), _resolve_skill_commands_home(), _resolve_skill_commands_project())
  661. commands = _merge_interactive_skill_commands(get_skill_commands(), get_plugin_skill_commands())
  662. with _publish_lock:
  663. _publish_scope(_last_interactive_skill_commands_by_key, identity, dict(commands))
  664. return commands
  665. def diff_command_snapshots(before: dict[str, str], after: dict[str, str]) -> dict[str, Any]:
  666. """Diff two {name: description} snapshots into added/removed/unchanged/total.
  667. Removed entries carry the pre-rescan description (the file may be gone)."""
  668. return {
  669. "added": [{"name": n, "description": after[n]} for n in sorted(set(after) - set(before))],
  670. "removed": [{"name": n, "description": before[n]} for n in sorted(set(before) - set(after))],
  671. "unchanged": sorted(set(after) & set(before)),
  672. "total": len(after),
  673. }
  674. def command_snapshot(cmds: dict[str, dict[str, Any]]) -> dict[str, str]:
  675. """``{"/slug": info}`` -> ``{"slug": description}`` for diff_command_snapshots."""
  676. return {key.lstrip("/"): (info or {}).get("description") or "" for key, info in cmds.items()}
  677. def reload_skills() -> dict[str, Any]:
  678. """Re-scan skill dirs and return a diff of the slash-command map (``added``
  679. / ``removed`` / ``unchanged`` / ``total`` / ``commands``; descriptions are the
  680. full frontmatter field). Does NOT invalidate the skills system-prompt cache:
  681. skills are called by name, so ``/reload-skills`` costs no cache reset. The
  682. plugin projection is rebuilt too, so a plugin enabled/disabled/installed
  683. since the last scan shows up without a restart."""
  684. key = (_resolve_skill_commands_platform(), _resolve_skill_commands_home(), _resolve_skill_commands_project())
  685. with _publish_lock:
  686. before_commands = _last_interactive_skill_commands_by_key.get(key)
  687. _publish_scope(None, key)
  688. if before_commands is None:
  689. # Preserve only a previously published view. A first-ever reload has
  690. # no before-state, so discoveries correctly appear as additions.
  691. with _publish_lock:
  692. before_commands = dict(_skill_commands_by_key.get(key, {}))
  693. if _plugin_skill_commands_tag and _plugin_skill_commands_tag[0] == key[1]:
  694. for command, info in _plugin_skill_commands.items():
  695. if command not in before_commands:
  696. before_commands[command] = info
  697. before = command_snapshot(before_commands)
  698. with _publish_lock:
  699. # Clear the entire multi-slot cache: a skill edit could affect any
  700. # platform/profile combination, so every cached identity must rescan.
  701. _skill_commands_by_key.clear()
  702. _skill_commands_sig_by_key.clear()
  703. from tools.skills_tool import clear_skills_cache
  704. clear_skills_cache() # the scan reads the shared catalog; an explicit reload must not hit its TTL
  705. invalidate_plugin_skill_commands()
  706. new_commands = scan_skill_commands()
  707. effective_commands = _merge_interactive_skill_commands(new_commands, get_plugin_skill_commands())
  708. after = command_snapshot(effective_commands)
  709. result = diff_command_snapshots(before, after)
  710. with _publish_lock:
  711. _publish_scope(_last_interactive_skill_commands_by_key, key, effective_commands)
  712. result["commands"] = len(effective_commands)
  713. return result
  714. def resolve_skill_command_key(command: str, *, interactive: bool = False) -> Optional[str]:
  715. """Resolve a user-typed slash command, or return None.
  716. Try the exact qualified spelling before the filesystem skill slug fallback,
  717. where underscores and hyphens are interchangeable for Telegram. Native
  718. callers retain the filesystem-only lookup; plugin skills are interactive.
  719. """
  720. return resolve_slash_key(command, get_interactive_skill_commands() if interactive else get_skill_commands())
  721. def resolve_slash_key(command: str, table: Mapping[str, Any]) -> Optional[str]:
  722. """``command`` -> ``"/slug"`` when present in *table* (``_`` normalized to ``-``), else None."""
  723. if not command:
  724. return None
  725. exact_key = f"/{command.lower()}"
  726. if exact_key in table:
  727. return exact_key
  728. cmd_key = f"/{command.replace('_', '-').lower()}"
  729. return cmd_key if cmd_key in table else None
  730. def build_skill_invocation_message(
  731. cmd_key: str, user_instruction: str = "", task_id: str | None = None, runtime_note: str = "",
  732. ) -> Optional[str]:
  733. """Build the user message for a skill slash command, or None if not found."""
  734. skill_info = get_interactive_skill_commands().get(cmd_key)
  735. loaded = _load_skill_payload(skill_info.get("skill_identifier") or skill_info["skill_dir"], task_id=task_id) if skill_info else None
  736. if not loaded:
  737. return None
  738. note = (f'[IMPORTANT: The user has invoked the "{loaded[2]}" skill, indicating they want '
  739. "you to follow its instructions. The full skill content is loaded below.]")
  740. return _render_skill_block(loaded, note, task_id, user_instruction=user_instruction, runtime_note=runtime_note)
  741. # Stacked slash-skill invocations — `/skill-a /skill-b do XYZ` loads every
  742. # leading skill (up to _MAX_STACKED_SKILLS). The message reuses the BUNDLE
  743. # scaffolding markers so the memory extractor needs no new plumbing.
  744. _MAX_STACKED_SKILLS = 5
  745. def split_stacked_skill_commands(rest: str, *, interactive: bool = False) -> tuple[list[str], str]:
  746. """Consume further leading ``/skill`` tokens from *rest* (text after the first
  747. matched command); stops at the first non-skill (or repeated) token, which
  748. starts the user instruction. Returns ``(extra_cmd_keys, remaining_instruction)``.
  749. Native callers (messaging gateway) must pass ``interactive=False``: plugin
  750. skills are interactive-only and must not resolve here."""
  751. keys: list[str] = []
  752. remaining = rest or ""
  753. while len(keys) < _MAX_STACKED_SKILLS - 1:
  754. stripped = remaining.lstrip()
  755. if not stripped.startswith("/"):
  756. break
  757. token, tail = (stripped.split(None, 1) + [""])[:2]
  758. cmd_key = resolve_skill_command_key(token.lstrip("/"), interactive=interactive)
  759. if cmd_key is None or cmd_key in keys:
  760. break
  761. keys.append(cmd_key)
  762. remaining = tail
  763. return keys, remaining.strip()
  764. def build_stacked_skill_invocation_message(
  765. cmd_keys: list[str], user_instruction: str = "", task_id: str | None = None,
  766. ) -> Optional[tuple[str, list[str], list[str]]]:
  767. """Build the user message for a stacked multi-skill slash invocation:
  768. ``(message, loaded_skill_names, missing_skill_names)``, or ``None`` when no skill loaded.
  769. Keys come from ``split_stacked_skill_commands``; native callers only ever pass filesystem keys."""
  770. commands = get_interactive_skill_commands()
  771. keys = [k for k in cmd_keys if k]
  772. loaded_names, missing, _disabled, skill_blocks = _load_skill_blocks(
  773. keys,
  774. lambda cmd_key: _load_skill_payload(commands[cmd_key].get("skill_identifier") or commands[cmd_key]["skill_dir"], task_id=task_id) if cmd_key in commands else None,
  775. lambda name: f'[Loaded as part of the stacked skill invocation "{name}".]', # bundle block marker
  776. task_id, missing_label=lambda k: k.lstrip("/"),
  777. )
  778. if not skill_blocks:
  779. return None
  780. typed = " ".join(keys)
  781. header = _scaffold_header(f'"{typed}" stacked skill bundle', loaded_names, missing=missing, user_instruction=user_instruction)
  782. return ("\n\n".join([header, *skill_blocks]), loaded_names, missing)
  783. def _disabled_skill_names(platform: str | None = None) -> set:
  784. """Operator-disabled skill names (empty set when config is unreadable)."""
  785. try:
  786. from agent.skill_utils import get_disabled_skill_names
  787. return get_disabled_skill_names(platform=platform)
  788. except Exception:
  789. return set()
  790. def _load_skill_blocks(
  791. identifiers: list[str], load, activation_note, task_id: str | None, *,
  792. missing_label=lambda ident: ident, disabled_names: set | None = None, disabled_as_missing: bool = False,
  793. already_loaded: set | None = None,
  794. ) -> tuple[list[str], list[str], list[str], list[str]]:
  795. """Load each distinct identifier via *load* and render its block; returns
  796. ``(loaded_names, missing, disabled, blocks)``. With *disabled_names*, members
  797. whose canonical (LOADED — identifiers may be paths) name or identifier is
  798. disabled go to ``disabled`` (or ``missing`` when *disabled_as_missing*).
  799. Canonical names in *already_loaded* (e.g. skills.auto_load) count as resolved
  800. but render no block, so one skill never lands in the prompt twice."""
  801. loaded_names: list[str] = []
  802. missing: list[str] = []
  803. disabled: list[str] = []
  804. blocks: list[str] = []
  805. seen: set[str] = set()
  806. for identifier in identifiers:
  807. if not identifier or identifier in seen:
  808. continue
  809. seen.add(identifier)
  810. loaded = load(identifier)
  811. if not loaded:
  812. missing.append(missing_label(identifier))
  813. continue
  814. skill_name = loaded[2]
  815. if disabled_names and (skill_name in disabled_names or identifier in disabled_names
  816. or (":" in skill_name and skill_name.split(":", 1)[1] in disabled_names)):
  817. if disabled_as_missing:
  818. missing.append(identifier)
  819. else:
  820. disabled.append(skill_name or identifier)
  821. continue
  822. if already_loaded and skill_name in already_loaded:
  823. loaded_names.append(skill_name)
  824. continue
  825. blocks.append(_render_skill_block(loaded, activation_note(skill_name), task_id))
  826. loaded_names.append(skill_name)
  827. return loaded_names, missing, disabled, blocks
  828. def build_preloaded_skills_prompt(
  829. skill_identifiers: list[str], task_id: str | None = None, excluded_loaded_names: set[str] | None = None,
  830. ) -> tuple[str, list[str], list[str]]:
  831. """Load skills for session-wide CLI/TUI preloading; returns (prompt_text,
  832. loaded_skill_names, missing_identifiers). Disabled skills count as missing:
  833. this path bypasses the scan-time filter, and ``hermes -s <skill>`` must not
  834. force-load an operator-disabled skill. *excluded_loaded_names* are canonical
  835. names the session already carries (skills.auto_load): they resolve as loaded
  836. but are not rendered again.
  837. Disabled skills are treated the same as missing ones: this loads via a raw identifier straight into
  838. ``_load_skill_payload``, bypassing ``get_skill_commands()``'s scan-time disabled filter — mirrors the
  839. bundle-invocation gate (#59156).
  840. """
  841. from agent.safe_worker_policy import safe_worker_enabled
  842. if safe_worker_enabled():
  843. return "", [], list(skill_identifiers)
  844. loaded_names, missing, _disabled, prompt_parts = _load_skill_blocks(
  845. [(raw or "").strip() for raw in skill_identifiers],
  846. lambda identifier: _load_skill_payload(identifier, task_id=task_id),
  847. lambda name: (f'[IMPORTANT: The user launched this CLI session with the "{name}" skill '
  848. "preloaded. Treat its instructions as active guidance for the duration of this "
  849. "session unless the user overrides them.]"),
  850. task_id, missing_label=_missing_skill_label, disabled_names=_disabled_skill_names(),
  851. disabled_as_missing=True, already_loaded=excluded_loaded_names,
  852. )
  853. return "\n\n".join(prompt_parts), loaded_names, missing
  854. def resolve_auto_load_skills(user_config: dict | None = None) -> list[str]:
  855. """``skills.auto_load`` from *user_config* (else the active profile config), deduplicated;
  856. empty when unset, malformed, or the config is unreadable."""
  857. if user_config is None:
  858. try:
  859. from hermes_cli.config import load_config_readonly
  860. user_config = load_config_readonly()
  861. except Exception:
  862. return []
  863. skills_block = user_config.get("skills") if isinstance(user_config, dict) else None
  864. auto_load = skills_block.get("auto_load") if isinstance(skills_block, dict) else None
  865. if not isinstance(auto_load, list):
  866. return []
  867. names = [entry.strip() for entry in auto_load if isinstance(entry, str) and entry.strip()]
  868. return list(dict.fromkeys(names))
  869. def build_auto_load_prompt(
  870. task_id: str | None = None, user_config: dict | None = None, home_override: Path | None = None,
  871. ) -> tuple[str, list[str], list[str]]:
  872. """Render ``skills.auto_load`` as fully loaded skill blocks for a new session; returns
  873. ``(prompt_text, loaded_names, missing)``. Missing and operator-disabled names are reported,
  874. never raised: a typo in config must not block session start on any surface.
  875. *home_override* makes home resolution EXPLICIT (same seam as ``build_skills_system_prompt``): the config,
  876. the disabled list and the ``<home>/skills`` lookup all resolve under that home, so a gateway build thread
  877. that lost the HERMES_HOME ContextVar cannot pin the launch profile's skills into another profile's prompt.
  878. """
  879. from hermes_constants import reset_hermes_home_override, set_hermes_home_override
  880. home_token = set_hermes_home_override(str(home_override)) if home_override is not None else None
  881. try:
  882. auto_skills = resolve_auto_load_skills(user_config)
  883. if not auto_skills:
  884. return "", [], []
  885. loaded_names, missing, _disabled, prompt_parts = _load_skill_blocks(
  886. auto_skills,
  887. lambda identifier: _load_skill_payload(identifier, task_id=task_id),
  888. lambda name: (f'[IMPORTANT: The "{name}" skill is auto-loaded via config (skills.auto_load). '
  889. "Treat its instructions as active guidance for the duration of this session unless "
  890. "the user overrides them.]"),
  891. task_id, disabled_names=_disabled_skill_names(), disabled_as_missing=True,
  892. )
  893. return "\n\n".join(prompt_parts), loaded_names, missing
  894. finally:
  895. if home_token is not None:
  896. reset_hermes_home_override(home_token)