diff --git a/agent/skill_bundles.py b/agent/skill_bundles.py index 500e5634d2..6fdf8d1c87 100644 --- a/agent/skill_bundles.py +++ b/agent/skill_bundles.py @@ -1,10 +1,9 @@ """Skill bundles — aliases that load multiple skills under one slash command. -Bundles are YAML files in ``/skill-bundles/`` (``name``, -``description``, ``skills: [...]``, optional ``instruction``; the file stem is -the fallback name). ``/`` loads every member skill into one user -message. If a bundle and a skill share a slug, the bundle wins — slash dispatch -checks bundles first, on purpose. +YAML files in ``/skill-bundles/`` (``name``, ``description``, +``skills: [...]``, optional ``instruction``; file stem = fallback name). +``/`` loads every member skill into one user message. If a bundle and a +skill share a slug, the bundle wins — slash dispatch checks bundles first, on purpose. """ from __future__ import annotations @@ -141,14 +140,11 @@ def build_bundle_invocation_message( task_id: str | None = None, platform: str | None = None, ) -> Optional[Tuple[str, List[str], List[str]]]: - """Build the user message for a bundle invocation. - - Returns ``(message, loaded_skill_names, missing_skill_names)`` or ``None`` - if the bundle wasn't found. Uninstalled members are skipped with a note. - Disabled members are skipped too: bundles load via ``_load_skill_payload``, - bypassing the scan-time disabled filter, so the list is re-applied here. - ``platform`` scopes that check (gateway passes it; None resolves from env). - """ + """Build the user message for a bundle invocation: ``(message, + loaded_skill_names, missing_skill_names)`` or ``None`` if the bundle wasn't + found. Uninstalled members are skipped with a note; disabled ones too, since + ``_load_skill_payload`` bypasses the scan-time filter (``platform`` scopes + that check — gateway passes it, None resolves from env).""" info = get_skill_bundles().get(cmd_key) if not info: return None @@ -197,11 +193,8 @@ def save_bundle( instruction: str = "", overwrite: bool = False, ) -> Path: - """Write a bundle to disk and refresh the cache. - - Raises ``FileExistsError`` if the target exists and not ``overwrite``; - ``ValueError`` for unusable inputs. - """ + """Write a bundle to disk and refresh the cache. Raises ``FileExistsError`` + if the target exists and not ``overwrite``; ``ValueError`` for unusable inputs.""" name = (name or "").strip() if not name: raise ValueError("Bundle name is required") diff --git a/agent/skill_commands.py b/agent/skill_commands.py index 28f0454051..df3d96c7b9 100644 --- a/agent/skill_commands.py +++ b/agent/skill_commands.py @@ -62,13 +62,10 @@ def slugify_skill_name(name: str) -> str: def append_user_instruction(parts: list, instruction: str) -> str: - """Append the instruction line to ``parts``; return the stable prefix. - - The prefix ends exactly at the instruction marker so, registered with - ``agent.prompt_cache_boundary``, the cache planner can break on the scaffold - instead of caching the whole message as one atomic block. Single - construction site guarantees the prefix is a byte-prefix of the message. - """ + """Append the instruction line to ``parts``; return the stable prefix, which + ends exactly at the instruction marker so (registered with + ``agent.prompt_cache_boundary``) the cache planner can break on the scaffold. + Single construction site guarantees the prefix is a byte-prefix of the message.""" stable_prefix = "\n".join(parts) + "\n" + _SINGLE_SKILL_INSTRUCTION parts.append(f"{_SINGLE_SKILL_INSTRUCTION}{instruction}") return stable_prefix @@ -94,9 +91,8 @@ def extract_user_instruction_from_skill_message(content: Any) -> Optional[str]: def describe_skill_invocation(content: Any, separator: str = " — ") -> Optional[str]: """Render a slash-skill-expanded turn the way the user typed it: ``"/work — fix the title leak"``, ``"/work"`` for a bare invocation, or - ``None`` when *content* is not scaffolding. Pass ``separator=" "`` for the - literal invocation as typed (chat transcripts). - """ + ``None`` when *content* is not scaffolding. ``separator=" "`` gives the + literal invocation as typed (chat transcripts).""" if not isinstance(content, str) or not content.startswith(_SKILL_INVOCATION_PREFIX): return None match = _SKILL_NAME_RE.match(content) @@ -149,7 +145,6 @@ def _load_skill_payload(skill_identifier: str, task_id: str | None = None) -> tu raw_identifier = (skill_identifier or "").strip() if not raw_identifier: return None - try: from tools.skills_tool import _skills_dir, skill_view from agent.skill_utils import normalize_skill_lookup_name @@ -160,8 +155,6 @@ def _load_skill_payload(skill_identifier: str, task_id: str | None = None) -> tu return None if not loaded_skill.get("success"): return None - - skill_name = str(loaded_skill.get("name") or normalized) skill_path = str(loaded_skill.get("path") or "") skill_dir = None # Prefer the absolute skill_dir from skill_view() (correct for external @@ -173,7 +166,7 @@ def _load_skill_payload(skill_identifier: str, task_id: str | None = None) -> tu skill_dir = _skills_dir() / Path(skill_path).parent except Exception: skill_dir = None - return loaded_skill, skill_dir, skill_name + return loaded_skill, skill_dir, str(loaded_skill.get("name") or normalized) def _inject_skill_config(loaded_skill: dict[str, Any], parts: list[str]) -> None: @@ -374,11 +367,9 @@ def _scan_skill_md(skill_md: Path, disabled: set, seen_names: set, commands: Dic def scan_skill_commands() -> Dict[str, Dict[str, Any]]: """Scan skill dirs and return {"/skill-name": {name, description, skill_md_path, skill_dir}}. - - Builds into a local map and publishes once at the end: writing straight into - the global exposed partial results to overlapping scans, which then logged - bogus "already claimed" collisions against their own incumbents. - """ + Builds a local map and publishes once at the end: writing straight into the + global exposed partial results to overlapping scans, which then logged + bogus "already claimed" collisions against their own incumbents.""" global _skill_commands, _skill_commands_platform, _skill_commands_home platform = _resolve_skill_commands_platform() home = _resolve_skill_commands_home() @@ -420,12 +411,10 @@ def scan_skill_commands() -> Dict[str, Dict[str, Any]]: def get_skill_commands() -> Dict[str, Dict[str, Any]]: - """Return the current skill commands mapping (scan first if empty). - - Rescans when the platform scope changes (one gateway serving Telegram and - Discord) or the active profile's home changes (Desktop profile switch), so - each sees its own ``platform_disabled`` / ``external_dirs`` view. - """ + """Return the current skill commands mapping (scan first if empty). Rescans + when the platform scope (one gateway serving Telegram and Discord) or the + active profile's home (Desktop profile switch) changes, so each sees its + own ``platform_disabled`` / ``external_dirs`` view.""" current_platform = _resolve_skill_commands_platform() current_home = _resolve_skill_commands_home() with _publish_lock: @@ -453,13 +442,10 @@ def command_snapshot(cmds: Dict[str, Dict[str, Any]]) -> Dict[str, str]: def reload_skills() -> Dict[str, Any]: - """Re-scan skill dirs and return a diff of the slash-command map. - - Does NOT invalidate the skills system-prompt cache: skills are called by - name, so ``/reload-skills`` costs no cache reset. Returns ``{"added": - [{name, description}], "removed": [...], "unchanged": [names], "total": - int, "commands": int}``; ``description`` is the full frontmatter field. - """ + """Re-scan skill dirs and return a diff of the slash-command map (``added`` + / ``removed`` / ``unchanged`` / ``total`` / ``commands``; descriptions are the + full frontmatter field). Does NOT invalidate the skills system-prompt cache: + skills are called by name, so ``/reload-skills`` costs no cache reset.""" before = command_snapshot(_skill_commands) new_commands = scan_skill_commands() result = diff_command_snapshots(before, command_snapshot(new_commands)) @@ -559,13 +545,10 @@ def _load_skill_blocks( identifiers: list[str], load, activation_note, task_id: str | None, *, missing_label=lambda ident: ident, disabled_names: set | None = None, disabled_as_missing: bool = False, ) -> tuple[list[str], list[str], list[str], list[str]]: - """Load each distinct identifier via *load* and render its block. - - Returns ``(loaded_names, missing, disabled, blocks)``. With *disabled_names*, - members whose canonical (LOADED — identifiers may be paths) name or - identifier is disabled are skipped into ``disabled`` (or ``missing`` when - *disabled_as_missing*). - """ + """Load each distinct identifier via *load* and render its block; returns + ``(loaded_names, missing, disabled, blocks)``. With *disabled_names*, members + whose canonical (LOADED — identifiers may be paths) name or identifier is + disabled go to ``disabled`` (or ``missing`` when *disabled_as_missing*).""" loaded_names: list[str] = [] missing: list[str] = [] disabled: list[str] = [] @@ -592,12 +575,10 @@ def _load_skill_blocks( def build_preloaded_skills_prompt(skill_identifiers: list[str], task_id: str | None = None) -> tuple[str, list[str], list[str]]: - """Load skills for session-wide CLI/TUI preloading. - - Returns (prompt_text, loaded_skill_names, missing_identifiers). Disabled - skills count as missing: this path bypasses the scan-time disabled filter, - so ``hermes -s `` must not force-load an operator-disabled skill. - """ + """Load skills for session-wide CLI/TUI preloading; returns (prompt_text, + loaded_skill_names, missing_identifiers). Disabled skills count as missing: + this path bypasses the scan-time filter, and ``hermes -s `` must not + force-load an operator-disabled skill.""" loaded_names, missing, _disabled, prompt_parts = _load_skill_blocks( [(raw or "").strip() for raw in skill_identifiers], lambda identifier: _load_skill_payload(identifier, task_id=task_id), diff --git a/agent/skill_utils.py b/agent/skill_utils.py index c27ce7476e..0a5c4e868c 100644 --- a/agent/skill_utils.py +++ b/agent/skill_utils.py @@ -1,7 +1,5 @@ """Lightweight skill metadata utilities shared by prompt_builder and skills_tool. - -Import-light by design: no tool registry, CLI config, or provider resolution. -""" +Import-light by design: no tool registry, CLI config, or provider resolution.""" import ast import logging @@ -73,11 +71,8 @@ def is_excluded_skill_path(path, *, root: Optional[Path] = None) -> bool: def is_skill_support_path(path, *, root: Optional[Path] = None) -> bool: - """True if *path* is under a support dir sitting directly inside a skill root. - - ``skills/scripts/foo`` stays discoverable: its ``scripts`` component is not - directly under a directory containing ``SKILL.md``. - """ + """True if *path* is under a support dir sitting directly inside a skill root + (``skills/scripts/foo`` stays discoverable: no ``SKILL.md`` above ``scripts``).""" path_obj = path if isinstance(path, Path) else Path(str(path)) parts = path_obj.parts base = root if root is not None and not path_obj.is_absolute() else Path() @@ -105,11 +100,8 @@ def yaml_load(content: str): def parse_frontmatter(content: str) -> Tuple[Dict[str, Any], str]: """Parse YAML frontmatter from markdown; returns (frontmatter_dict, body). - Malformed YAML falls back to key:value line splitting. A leading UTF-8 BOM - (Windows editors) is stripped first or it would defeat the ``---`` fence - check and silently drop the frontmatter. - """ + (Windows editors) is stripped first or it would defeat the ``---`` fence check.""" content = content.removeprefix("\ufeff") end_match = re.search(r"\n---\s*\n", content[3:]) if content.startswith("---") else None if not end_match: @@ -168,9 +160,10 @@ def _detect_kanban() -> bool: try: from agent.delegation_context import is_dispatcher_owned_worker_context - if is_dispatcher_owned_worker_context(): - return True + owned = is_dispatcher_owned_worker_context() except Exception: + owned = True + if owned: return True try: from tools.kanban_tools import _profile_has_kanban_toolset @@ -199,11 +192,9 @@ _ENV_DETECTORS: Dict[str, Callable[[], bool]] = { def _detect_environment(env: str) -> bool: """True when the named runtime environment is active (unknown => True). - Cached per process EXCEPT ``kanban``: that verdict is context-dependent (delegate children / in-process cron see the worker's vars), so a - process-wide cache would leak the first asker's answer to the others. - """ + process-wide cache would leak the first asker's answer to the others.""" if env != "kanban" and env in _ENV_DETECT_CACHE: return _ENV_DETECT_CACHE[env] detector = _ENV_DETECTORS.get(env) @@ -293,10 +284,8 @@ ESSENTIAL_SKILLS: frozenset = frozenset({"hermes-agent"}) def get_disabled_skill_names(platform: str | None = None) -> Set[str]: - """Disabled skill names from config.yaml: global list ∪ platform list. - - *platform* defaults to ``HERMES_PLATFORM`` / ``HERMES_SESSION_PLATFORM``. - """ + """Disabled skill names from config.yaml: global list ∪ platform list + (*platform* defaults to ``HERMES_PLATFORM`` / ``HERMES_SESSION_PLATFORM``).""" skills_cfg = _skills_cfg() if skills_cfg is None: return set() @@ -312,11 +301,9 @@ def get_disabled_skill_names(platform: str | None = None) -> Set[str]: def parse_config_string_list(value) -> List[str]: """Normalize a config value that may hold a JSON-array string into a list. - ``hermes config set`` stores lists as quoted JSON/Python-literal strings; treating one as a single name would silently filter nothing. A scalar - string still means one name. - """ + string still means one name.""" if isinstance(value, str): if value.strip().startswith("["): try: @@ -354,11 +341,8 @@ def _config_str_list(raw) -> List[str]: def get_external_skills_dirs() -> List[Path]: - """Validated, deduplicated ``skills.external_dirs`` (existing dirs only). - - Entries are expanded (``~``, ``${VAR}``); relative paths resolve against - HERMES_HOME; the local ``~/.hermes/skills/`` is skipped. - """ + """Validated, deduplicated ``skills.external_dirs`` (existing dirs only). Entries + are ``~``/``${VAR}`` expanded, relative to HERMES_HOME; the local skills dir is skipped.""" config_path = get_config_path() if not config_path.exists(): return [] @@ -387,11 +371,8 @@ def get_external_skills_dirs() -> List[Path]: def get_skill_create_dir() -> Optional[Path]: - """Configured ``skills.create_dir`` (need not exist yet), or None when unset. - - Relative paths resolve against HERMES_HOME; a value equal to the local - skills dir counts as unset. - """ + """Configured ``skills.create_dir`` (need not exist yet), or None when unset; + relative to HERMES_HOME; a value equal to the local skills dir counts as unset.""" raw = _skills_cfg_get("create_dir") entry = str(raw).strip() if raw and isinstance(raw, (str, os.PathLike)) else "" if not entry: @@ -434,13 +415,11 @@ def get_all_skills_dirs() -> List[Path]: return dirs -# Project-local skills live at /.hermes/skills/ or /.agents/skills/ -# (root = nearest ancestor with .git). TRUST GATE: skills are procedure docs an -# agent will follow, so auto-sourcing them from any cloned repo is a prompt- -# injection vector — they load only when the root is in -# ``skills.trusted_project_dirs``, and then override same-named profile/bundled -# skills. cwd and the trust list are session-fixed so the skills index stays -# byte-stable. +# Project-local skills (/.hermes/skills, /.agents/skills; root = nearest +# .git ancestor) are a prompt-injection vector if auto-sourced from any clone, so +# they load only when the root is in ``skills.trusted_project_dirs``; then they +# override same-named profile/bundled skills. cwd + trust list are session-fixed +# so the skills index stays byte-stable. PROJECT_SKILLS_SUBDIRS = (os.path.join(".hermes", "skills"), os.path.join(".agents", "skills")) @@ -449,11 +428,8 @@ _PROJECT_ROOT_MAX_DEPTH = 64 # walk-up bound for pathological cwds def find_project_root(start: Optional[Path] = None) -> Optional[Path]: """Nearest ancestor containing ``.git`` (dir or worktree file), or None. - Without *start*, the surface's ``TERMINAL_CWD`` wins over process cwd so - cron/API surfaces inherit an interactive trust decision by project identity; - a surface with no workdir resolves no project. - """ + cron/API surfaces inherit an interactive trust decision by project identity.""" try: if start is None: from agent.runtime_cwd import scope_terminal_cwd @@ -464,17 +440,17 @@ def find_project_root(start: Optional[Path] = None) -> Optional[Path]: except OSError: return None home = Path.home().resolve() - for _ in range(_PROJECT_ROOT_MAX_DEPTH): - try: + try: + for _ in range(_PROJECT_ROOT_MAX_DEPTH): if (cur / ".git").exists(): # A dotfiles checkout AT home would make every session # project-scoped; treat home itself as non-project. return None if cur == home else cur - except OSError: - return None - if cur.parent == cur: - return None - cur = cur.parent + if cur.parent == cur: + return None + cur = cur.parent + except OSError: + pass return None @@ -768,12 +744,10 @@ def is_skill_description_truncated_for_prompt(frontmatter: Dict[str, Any]) -> bo def iter_skill_index_files(skills_dir: Path, filename: str): - """Walk skills_dir yielding sorted paths matching *filename*. - - Prunes EXCLUDED_SKILL_DIRS and support dirs of skill roots. Org mirrors - (``_org/``) are TOKEN-GATED: only the active org's subdir is walked, so - leaving an org stops its skills resolving without manual cleanup. - """ + """Walk skills_dir yielding sorted paths matching *filename*; prunes + EXCLUDED_SKILL_DIRS and support dirs of skill roots. Org mirrors are + TOKEN-GATED: only the active org's subdir is walked, so leaving an org + stops its skills resolving without manual cleanup.""" skills_dir_str = str(skills_dir) active_org = read_active_org_id(skills_dir) org_root = os.path.join(skills_dir_str, ORG_MIRROR_DIR_NAME) diff --git a/agent/subdirectory_hints.py b/agent/subdirectory_hints.py index e4b805cefe..d953320440 100644 --- a/agent/subdirectory_hints.py +++ b/agent/subdirectory_hints.py @@ -1,11 +1,8 @@ -"""Progressive subdirectory hint discovery. - -As the agent navigates into subdirectories via tool calls, load project -context files (AGENTS.md, CLAUDE.md, .cursorrules) from those directories and -append them to the tool result — context arrives without touching the system -prompt (preserving prompt caching). Complements the startup CWD-only loading -in ``prompt_builder.py``. -""" +"""Progressive subdirectory hint discovery: as the agent navigates into +subdirectories via tool calls, load project context files (AGENTS.md, CLAUDE.md, +.cursorrules) from them and append to the tool result — context arrives without +touching the system prompt (prompt caching preserved). Complements the startup +CWD-only loading in ``prompt_builder.py``.""" import hashlib import logging diff --git a/agent/system_prompt.py b/agent/system_prompt.py index 1238203787..91dbdfc1c4 100644 --- a/agent/system_prompt.py +++ b/agent/system_prompt.py @@ -191,14 +191,12 @@ def _plugin_section_blocks(sections: tuple, position: str) -> List[str]: def _session_start_like(agent: Any, now: Any) -> Any: """Best-known conversation start time, or ``now`` as a fallback. - ``Conversation started:`` must be byte-stable across rebuilds (compression, resume, fresh gateway turns), so prefer immutable sources in order: the lineage-root session id's embedded stamp (compaction rotates ids, each with its own mint time), the current session id's stamp, ``agent.session_start``, then ``now``. Stamps are box-local wall-clock: attach that zone first, then - convert to ``now``'s zone so the date matches the per-turn clock. - """ + convert to ``now``'s zone so the date matches the per-turn clock.""" from datetime import datetime def _to_display_tz(dt: Any) -> Any: @@ -579,14 +577,11 @@ def _post_workspace_parts(agent: Any) -> List[str]: def _context_files_part(agent: Any, _r: Any, ctx_len: Optional[int], soul_loaded: bool) -> List[str]: - """Project context files (AGENTS.md etc.) for the context tier. - - TERMINAL_CWD when set (gateway); None lets discovery fall back to the - launch dir. The install-tree fallback is only legitimate for cli/tui where - the launch dir IS the user's shell cwd; desktop-pinned launch dirs are - treated as the fallback they really are so the guard can reject Hermes's - bundled contributor AGENTS.md. - """ + """Project context files (AGENTS.md etc.) for the context tier. TERMINAL_CWD + when set (gateway); None lets discovery fall back to the launch dir. The + install-tree fallback is only legitimate for cli/tui where the launch dir + IS the user's shell cwd; desktop-pinned launch dirs are treated as the + fallback they really are so the guard can reject Hermes's bundled AGENTS.md.""" if agent.skip_context_files: return [] launch_artifact = getattr(agent, "_context_cwd_is_launch_artifact", False) @@ -651,9 +646,8 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) context_parts.extend(_context_files_part(agent, _r, _ctx_len, _soul_loaded)) # ── Volatile tier (most likely to differ on a rebuild; kept last so the stable prefix stays reusable) ── - # Skills are runtime-mutable, so the index leads the volatile band: on a - # longest-prefix backend an unchanged index still falls inside the reused - # prefix and a changed one only re-prefills from here on. + # Skills are runtime-mutable, so the index leads the volatile band: on a longest-prefix + # backend an unchanged index stays inside the reused prefix; a changed one re-prefills from here. volatile_parts: List[str] = [skills_prompt] if skills_prompt else [] volatile_parts.extend(_memory_parts(agent)) # Plugin sections are confined to one coarse anchor in the volatile tail so @@ -682,9 +676,9 @@ def build_system_prompt(agent: Any, system_message: Optional[str] = None) -> str def invalidate_system_prompt(agent: Any) -> None: - """Force a rebuild on the next turn (after compression). Reloads memory - from disk and clears the frozen plugin snapshot so plugins re-render at the - same boundary; the previous bytes are stashed as the fail-open fallback.""" + """Force a rebuild on the next turn (after compression): reload memory from + disk and clear the frozen plugin snapshot (previous bytes stashed as the + fail-open fallback) so plugins re-render at the same boundary.""" agent._cached_system_prompt = None agent._cached_system_prompt_static = None if hasattr(agent, "_plugin_system_prompt_sections_snapshot"): @@ -696,14 +690,12 @@ def invalidate_system_prompt(agent: Any) -> None: def reconstruct_static_prefix(agent: Any, system_message: Optional[str] = None, *, log_label: str = "restore") -> None: """Reconstruct ``_cached_system_prompt_static`` for a stored prompt. - Only the full prompt is persisted, so restore / keep-prompt compression / mid-turn failover to a cache-on provider must rebuild the stable tier to regain the ``[static, volatile]`` layout. The rebuilt tier is used ONLY when the stored prompt literally starts with it; otherwise static stays None and the stored bytes are sent untouched. A failed rebuild is memoized - per stored prompt so the retry-loop hot path doesn't redo the file I/O. - """ + per stored prompt so the retry-loop hot path doesn't redo the file I/O.""" stored = getattr(agent, "_cached_system_prompt", None) existing = getattr(agent, "_cached_system_prompt_static", None) if (