The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(skills): skills.auto_load pins skills into every new session's prompt
ArcherQAQ1976869c0103
diff --git a/agent/skill_commands.py b/agent/skill_commands.pyindex 253b47e5dee..038b066b053 100644--- a/agent/skill_commands.py+++ b/agent/skill_commands.py@@ -546,11 +546,14 @@ def _disabled_skill_names(platform: str | None = None) -> set: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,+ already_loaded: set | None = None,) -> 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*, memberswhose canonical (LOADED — identifiers may be paths) name or identifier is- disabled go to ``disabled`` (or ``missing`` when *disabled_as_missing*)."""+ disabled go to ``disabled`` (or ``missing`` when *disabled_as_missing*).+ Canonical names in *already_loaded* (e.g. skills.auto_load) count as resolved+ but render no block, so one skill never lands in the prompt twice."""loaded_names: list[str] = []missing: list[str] = []disabled: list[str] = []@@ -571,16 +574,23 @@ def _load_skill_blocks(else:disabled.append(skill_name or identifier)continue+ if already_loaded and skill_name in already_loaded:+ loaded_names.append(skill_name)+ continueblocks.append(_render_skill_block(loaded, activation_note(skill_name), task_id))loaded_names.append(skill_name)return loaded_names, missing, disabled, blocks-def build_preloaded_skills_prompt(skill_identifiers: list[str], task_id: str | None = None) -> tuple[str, list[str], list[str]]:+def build_preloaded_skills_prompt(+ skill_identifiers: list[str], task_id: str | None = None, excluded_loaded_names: set[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 filter, and ``hermes -s <skill>`` must not- force-load an operator-disabled skill.+ force-load an operator-disabled skill. *excluded_loaded_names* are canonical+ names the session already carries (skills.auto_load): they resolve as loaded+ but are not rendered again.Disabled skills are treated the same as missing ones: this loads via a raw identifier straight into``_load_skill_payload``, bypassing ``get_skill_commands()``'s scan-time disabled filter — mirrors the@@ -593,5 +603,41 @@ def build_preloaded_skills_prompt(skill_identifiers: list[str], task_id: str | N"preloaded. Treat its instructions as active guidance for the duration of this ""session unless the user overrides them.]"),task_id, disabled_names=_disabled_skill_names(), disabled_as_missing=True,+ already_loaded=excluded_loaded_names,+ )+ return "\n\n".join(prompt_parts), loaded_names, missing+++def resolve_auto_load_skills(user_config: dict | None = None) -> list[str]:+ """``skills.auto_load`` from *user_config* (else the active profile config), deduplicated;+ empty when unset, malformed, or the config is unreadable."""+ if user_config is None:+ try:+ from hermes_cli.config import load_config_readonly+ user_config = load_config_readonly()+ except Exception:+ return []+ skills_block = user_config.get("skills") if isinstance(user_config, dict) else None+ auto_load = skills_block.get("auto_load") if isinstance(skills_block, dict) else None+ if not isinstance(auto_load, list):+ return []+ names = [entry.strip() for entry in auto_load if isinstance(entry, str) and entry.strip()]+ return list(dict.fromkeys(names))+++def build_auto_load_prompt(task_id: str | None = None, user_config: dict | None = None) -> tuple[str, list[str], list[str]]:+ """Render ``skills.auto_load`` as fully loaded skill blocks for a new session; returns+ ``(prompt_text, loaded_names, missing)``. Missing and operator-disabled names are reported,+ never raised: a typo in config must not block session start on any surface."""+ auto_skills = resolve_auto_load_skills(user_config)+ if not auto_skills:+ return "", [], []+ loaded_names, missing, _disabled, prompt_parts = _load_skill_blocks(+ auto_skills,+ lambda identifier: _load_skill_payload(identifier, task_id=task_id),+ lambda name: (f'[IMPORTANT: The "{name}" skill is auto-loaded via config (skills.auto_load). '+ "Treat its instructions as active guidance for the duration of this session unless "+ "the user overrides them.]"),+ task_id, disabled_names=_disabled_skill_names(), disabled_as_missing=True,)return "\n\n".join(prompt_parts), loaded_names, missingdiff --git a/agent/system_prompt.py b/agent/system_prompt.pyindex 37785159241..96c4096b19e 100644--- a/agent/system_prompt.py+++ b/agent/system_prompt.py@@ -312,6 +312,26 @@ def _skills_prompt(agent: Any) -> str:compact_categories=_compact_cats or None, skills_dir_override=_agent_skills_dir(agent))+def _auto_load_parts(agent: Any) -> List[str]:+ """``skills.auto_load`` blocks, resolved once per agent lifecycle (config, skill files and+ HERMES_IGNORE_RULES are read on the first build only) so the prompt stays byte-stable+ across model switches, compression and static-prefix restoration."""+ if not getattr(agent, "_auto_load_skills_resolved", False):+ result: Tuple[str, List[str], List[str]] = ("", [], [])+ try:+ if not is_truthy_value(os.environ.get("HERMES_IGNORE_RULES")):+ from agent.skill_commands import build_auto_load_prompt+ result = build_auto_load_prompt(task_id=getattr(agent, "session_id", None))+ if result[2]:+ logger.warning("skills.auto_load: skill(s) not found or disabled, skipped: %s", ", ".join(result[2]))+ except Exception:+ logger.debug("skills.auto_load: injection skipped", exc_info=True) # config errors never block session start+ agent._auto_load_skills_result = result+ agent._auto_load_skills_resolved = True+ prompt = agent._auto_load_skills_result[0]+ return [prompt] if prompt else []++def _bot_mode_parts(agent: Any) -> List[str]:"""Bot Mode teammate protocol — only in a bot's canonical "Bot Chat" session.Marks the prompt timeless (the volatile date line is dropped) since a birth@@ -627,6 +647,8 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None)if "skill_view" in (agent.valid_tool_names or set()) and "- hermes-agent:" in skills_prompt:stable_parts[_help_guidance_slot] = HERMES_AGENT_HELP_GUIDANCEstable_parts.extend(_alibaba_identity_part(agent))+ # Pinned skills are per-agent constants (resolved once), so they live in the stable prefix.+ stable_parts.extend(_auto_load_parts(agent))# Coding posture: the operating brief stays in the stable prefix. The# environment block contains the current cwd/backend and belongs after# project context, not ahead of a large shared AGENTS.md block.diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex a20e963ad08..22a09277caf 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -1355,6 +1355,10 @@ DEFAULT_CONFIG = {"project_discovery": True,# Trusted project roots; managed by `hermes skills trust` / `untrust`."trusted_project_dirs": [],+ # Skill names pinned as fully loaded in every new session (CLI, TUI, gateway, cron, API).+ # Resolved once when the agent's prompt is first built; missing/disabled names warn and+ # skip; HERMES_IGNORE_RULES suppresses the list like the other auto-injected context.+ "auto_load": [],# Substitute ${HERMES_SKILL_DIR} / ${HERMES_SESSION_ID} in SKILL.md content."template_vars": True,# Pre-execute !`cmd` snippets in SKILL.md, inlining stdout (dates, git state...). Off:diff --git a/tests/agent/test_skills_auto_load.py b/tests/agent/test_skills_auto_load.pynew file mode 100644index 00000000000..8b81d598cd4--- /dev/null+++ b/tests/agent/test_skills_auto_load.py@@ -0,0 +1,93 @@+"""skills.auto_load: pinned skills land in every new session's prompt, resolved once per agent."""++from __future__ import annotations++from unittest.mock import patch+++def _write_skill(root, name, body):+ skill_dir = root / name+ skill_dir.mkdir(parents=True, exist_ok=True)+ (skill_dir / "SKILL.md").write_text(f"---\nname: {name}\ndescription: Test.\n---\n\n{body}\n")+ return skill_dir / "SKILL.md"+++def _bare_agent(session_id="auto-load-test"):+ from run_agent import AIAgent++ agent = AIAgent.__new__(AIAgent)+ agent.valid_tool_names = {"skills_list", "skill_view", "skill_manage"}+ agent.model = "test-model"+ agent.provider = "test"+ agent.pass_session_id = False+ agent.skip_context_files = True+ agent.load_soul_identity = False+ agent._memory_enabled = False+ agent._user_profile_enabled = False+ agent._memory_manager = None+ agent._memory_store = None+ agent.session_id = session_id+ agent.platform = "telegram"+ agent._tool_use_enforcement = False+ agent.ephemeral_system_prompt = None+ agent._cached_system_prompt = None+ agent._auto_load_skills_resolved = False+ agent._auto_load_skills_result = ("", [], [])+ return agent+++class TestBuildAutoLoadPrompt:+ def test_loads_configured_skills_and_reports_missing(self, tmp_path):+ from agent.skill_commands import build_auto_load_prompt++ _write_skill(tmp_path, "pinned-skill", "PINNED CONTENT")+ cfg = {"skills": {"auto_load": ["pinned-skill", " pinned-skill ", "no-such-skill", 7]}}+ with patch("tools.skills_tool.SKILLS_DIR", tmp_path):+ prompt, loaded, missing = build_auto_load_prompt(task_id="s1", user_config=cfg)+ assert loaded == ["pinned-skill"]+ assert missing == ["no-such-skill"]+ assert "PINNED CONTENT" in prompt+ assert prompt.count("auto-loaded via config (skills.auto_load)") == 1++ def test_explicit_preload_dedupes_against_auto_loaded_names(self, tmp_path):+ from agent.skill_commands import build_preloaded_skills_prompt++ _write_skill(tmp_path, "pinned-skill", "PINNED CONTENT")+ _write_skill(tmp_path, "extra-skill", "EXTRA CONTENT")+ with patch("tools.skills_tool.SKILLS_DIR", tmp_path):+ prompt, loaded, missing = build_preloaded_skills_prompt(+ ["pinned-skill", "extra-skill"], task_id="s1", excluded_loaded_names={"pinned-skill"},+ )+ # Still counted as resolved (so a typo elsewhere degrades gracefully), but not rendered twice.+ assert loaded == ["pinned-skill", "extra-skill"] and missing == []+ assert "PINNED CONTENT" not in prompt and "EXTRA CONTENT" in prompt+++class TestSharedPromptPath:+ def test_prompt_is_byte_stable_after_config_and_skill_mutation(self, tmp_path, monkeypatch):+ """The whole point: rebuilds (model switch, compression) reuse the first resolution."""+ monkeypatch.delenv("HERMES_IGNORE_RULES", raising=False)+ skill_file = _write_skill(tmp_path, "stable-skill", "ORIGINAL SKILL BYTES")+ cfg = {"skills": {"auto_load": ["stable-skill"]}}+ agent = _bare_agent()+ with patch("tools.skills_tool.SKILLS_DIR", tmp_path), \+ patch("hermes_cli.config.load_config_readonly", return_value=cfg):+ first = agent._build_system_prompt()+ assert "ORIGINAL SKILL BYTES" in first and agent._auto_load_skills_result[1] == ["stable-skill"]+ skill_file.write_text("---\nname: stable-skill\ndescription: Test.\n---\n\nMUTATED BYTES\n")+ cfg["skills"]["auto_load"] = []+ agent.model = "after-switch"+ agent._cached_system_prompt = None+ rebuilt = agent._build_system_prompt()+ assert "ORIGINAL SKILL BYTES" in rebuilt and "MUTATED BYTES" not in rebuilt++ def test_ignore_rules_suppresses_auto_load(self, tmp_path, monkeypatch):+ _write_skill(tmp_path, "stable-skill", "ORIGINAL SKILL BYTES")+ cfg = {"skills": {"auto_load": ["stable-skill"]}}+ monkeypatch.setenv("HERMES_IGNORE_RULES", "1")+ agent = _bare_agent()+ with patch("tools.skills_tool.SKILLS_DIR", tmp_path), \+ patch("hermes_cli.config.load_config_readonly", return_value=cfg):+ prompt = agent._build_system_prompt()+ assert "ORIGINAL SKILL BYTES" not in prompt+ assert agent._auto_load_skills_resolved is True and agent._auto_load_skills_result == ("", [], [])