Skip to content

The agent that grows with you

refactor(agent/skills): compact multi-line literals, log calls and call sites

Teknium76f136b82cbd
diff --git a/agent/skill_bundles.py b/agent/skill_bundles.py
index 00eeea1fbe1..401468d6b6f 100644
--- a/agent/skill_bundles.py
+++ b/agent/skill_bundles.py
@@ -16,12 +16,7 @@ from typing import Any, Dict, List, Optional, Tuple
import yaml
from hermes_constants import get_hermes_home
-from agent.skill_commands import (
- command_snapshot,
- diff_command_snapshots,
- resolve_slash_key,
- slugify_skill_name as _slugify,
-)
+from agent.skill_commands import command_snapshot, diff_command_snapshots, resolve_slash_key, slugify_skill_name as _slugify
logger = logging.getLogger(__name__)
@@ -78,12 +73,9 @@ def _load_bundle_file(path: Path) -> Optional[Dict[str, Any]]:
if not slug:
return _skip("yielded empty slug")
return {
- "name": name,
- "slug": slug,
+ "name": name, "slug": slug, "skills": skills, "path": str(path),
"description": str(data.get("description") or "").strip() or f"Load {len(skills)} skills as a bundle",
- "skills": skills,
"instruction": str(data.get("instruction") or "").strip(),
- "path": str(path),
}
@@ -154,13 +146,8 @@ def build_bundle_invocation_message(
if not skill_blocks:
return None
header = _scaffold_header(
- f'"{bundle_name}" skill bundle',
- loaded_names,
- lead_lines=[f"Bundle: {bundle_name}"],
- missing=missing,
- disabled=disabled,
- extra_instruction=info.get("instruction") or "",
- user_instruction=user_instruction,
+ f'"{bundle_name}" skill bundle', loaded_names, lead_lines=[f"Bundle: {bundle_name}"], missing=missing,
+ disabled=disabled, extra_instruction=info.get("instruction") or "", user_instruction=user_instruction,
)
return ("\n\n".join([header, *skill_blocks]), loaded_names, missing)
diff --git a/agent/skill_commands.py b/agent/skill_commands.py
index f4704f82359..893f2fd451a 100644
--- a/agent/skill_commands.py
+++ b/agent/skill_commands.py
@@ -10,10 +10,7 @@ from typing import Any, Dict, Optional
from hermes_constants import display_hermes_home
from agent.prompt_cache_boundary import register_stable_prefix
-from agent.skill_preprocessing import (
- load_skills_config as _load_skills_config,
- preprocess_skill_content,
-)
+from agent.skill_preprocessing import load_skills_config as _load_skills_config, preprocess_skill_content
logger = logging.getLogger(__name__)
@@ -181,6 +178,11 @@ def _inject_skill_config(loaded_skill: dict[str, Any], parts: list[str]) -> None
pass
+_SKILL_DIR_NOTE = (
+ "Resolve any relative paths in this skill (e.g. `scripts/foo.js`, "
+ "`templates/config.yaml`) against that directory, then run them "
+ "with the terminal tool using the absolute path."
+)
_SETUP_SKIPPED_NOTE = (
"Required environment setup was skipped. Continue loading the skill "
"and explain any reduced functionality if it matters."
@@ -197,19 +199,12 @@ def _setup_note(loaded_skill: dict[str, Any]) -> Optional[str]:
def _supporting_files(loaded_skill: dict[str, Any], skill_dir: Path | None) -> list[str]:
"""Skill-relative support file paths: from ``linked_files`` or a disk walk."""
- supporting = [
- entry
- for entries in (loaded_skill.get("linked_files") or {}).values()
- if isinstance(entries, list)
- for entry in entries
- ]
+ linked = (loaded_skill.get("linked_files") or {}).values()
+ supporting = [entry for entries in linked if isinstance(entries, list) for entry in entries]
if not supporting and skill_dir:
for subdir in ("references", "templates", "scripts", "assets"):
- supporting.extend(
- str(f.relative_to(skill_dir))
- for f in sorted((skill_dir / subdir).rglob("*"))
- if f.is_file() and not f.is_symlink()
- )
+ files = sorted((skill_dir / subdir).rglob("*"))
+ supporting += [str(f.relative_to(skill_dir)) for f in files if f.is_file() and not f.is_symlink()]
return supporting
@@ -230,13 +225,7 @@ def _build_skill_message(
parts = [activation_note, "", content.strip()]
# Absolute skill dir lets the agent run bundled scripts without a skill_view() round-trip.
if skill_dir:
- parts += [
- "",
- f"[Skill directory: {skill_dir}]",
- "Resolve any relative paths in this skill (e.g. `scripts/foo.js`, "
- "`templates/config.yaml`) against that directory, then run them "
- "with the terminal tool using the absolute path.",
- ]
+ parts += ["", f"[Skill directory: {skill_dir}]", _SKILL_DIR_NOTE]
_inject_skill_config(loaded_skill, parts)
setup_note = _setup_note(loaded_skill)
if setup_note:
@@ -333,26 +322,18 @@ def _scan_skill_md(skill_md: Path, disabled: set, seen_names: set, commands: Dic
# A collision with a core command (name or alias, via resolve_command) skips
# auto-registration; the skill stays loadable via /skill <name>.
if resolve_command(cmd_name) is not None:
- logger.warning(
- "Skill %r generates slash command '/%s' which collides with a core Hermes command; "
- "skipping auto-registration. Use '/skill %s' instead.", name, cmd_name, name,
- )
+ logger.warning("Skill %r generates slash command '/%s' which collides with a core Hermes command; "
+ "skipping auto-registration. Use '/skill %s' instead.", name, cmd_name, name)
return
# Dedup on the slug too: "git_helper" and "git-helper" normalize the same.
# First-wins preserves project > local > external precedence.
cmd_key = f"/{cmd_name}"
if cmd_key in commands:
- logger.warning(
- "Skill %r maps to slash command %s already claimed by %r; keeping the first and skipping this one.",
- name, cmd_key, commands[cmd_key]["name"],
- )
+ logger.warning("Skill %r maps to slash command %s already claimed by %r; keeping the first and skipping this one.",
+ name, cmd_key, commands[cmd_key]["name"])
return
- commands[cmd_key] = {
- "name": name,
- "description": description or f"Invoke the {name} skill",
- "skill_md_path": str(skill_md),
- "skill_dir": str(skill_md.parent),
- }
+ commands[cmd_key] = {"name": name, "description": description or f"Invoke the {name} skill",
+ "skill_md_path": str(skill_md), "skill_dir": str(skill_md.parent)}
def scan_skill_commands() -> Dict[str, Dict[str, Any]]:
@@ -377,10 +358,8 @@ def scan_skill_commands() -> Dict[str, Dict[str, Any]]:
# the launch home, but a multiplexed profile scope may have changed it.
skills_dir = _skills_dir()
iters = [iter_project_skill_files(d) for d in get_project_skills_dirs()]
- iters += [
- iter_skill_index_files(d, "SKILL.md")
- for d in ([skills_dir] if skills_dir.exists() else []) + get_external_skills_dirs()
- ]
+ local = [skills_dir] if skills_dir.exists() else []
+ iters += [iter_skill_index_files(d, "SKILL.md") for d in local + get_external_skills_dirs()]
for _iter in iters:
for skill_md in _iter:
try:
@@ -464,14 +443,9 @@ def build_skill_invocation_message(
loaded = _load_skill_payload(skill_info["skill_dir"], task_id=task_id) if skill_info else None
if not loaded:
return None
- return _render_skill_block(
- loaded,
- f'[IMPORTANT: The user has invoked the "{loaded[2]}" skill, indicating they want '
- "you to follow its instructions. The full skill content is loaded below.]",
- task_id,
- user_instruction=user_instruction,
- runtime_note=runtime_note,
- )
+ note = (f'[IMPORTANT: The user has invoked the "{loaded[2]}" skill, indicating they want '
+ "you to follow its instructions. The full skill content is loaded below.]")
+ return _render_skill_block(loaded, note, task_id, user_instruction=user_instruction, runtime_note=runtime_note)
# Stacked slash-skill invocations — `/skill-a /skill-b do XYZ` loads every
@@ -505,16 +479,16 @@ def build_stacked_skill_invocation_message(
"""Build the user message for a stacked multi-skill slash invocation:
``(message, loaded_skill_names, missing_skill_names)``, or ``None`` when no skill loaded."""
commands = get_skill_commands()
+ keys = [k for k in cmd_keys if k]
loaded_names, missing, _disabled, skill_blocks = _load_skill_blocks(
- [k for k in cmd_keys if k],
+ keys,
lambda cmd_key: _load_skill_payload(commands[cmd_key]["skill_dir"], task_id=task_id) if cmd_key in commands else None,
lambda name: f'[Loaded as part of the stacked skill invocation "{name}".]', # bundle block marker
- task_id,
- missing_label=lambda k: k.lstrip("/"),
+ task_id, missing_label=lambda k: k.lstrip("/"),
)
if not skill_blocks:
return None
- typed = " ".join(k for k in cmd_keys if k)
+ typed = " ".join(keys)
header = _scaffold_header(f'"{typed}" stacked skill bundle', loaded_names, missing=missing, user_instruction=user_instruction)
return ("\n\n".join([header, *skill_blocks]), loaded_names, missing)
@@ -569,13 +543,9 @@ def build_preloaded_skills_prompt(skill_identifiers: list[str], task_id: str | N
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),
- lambda name: (
- f'[IMPORTANT: The user launched this CLI session with the "{name}" skill '
- "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,
+ lambda name: (f'[IMPORTANT: The user launched this CLI session with the "{name}" skill '
+ "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,
)
return "\n\n".join(prompt_parts), loaded_names, missing
diff --git a/agent/skill_utils.py b/agent/skill_utils.py
index ebd656f68d2..5f855894098 100644
--- a/agent/skill_utils.py
+++ b/agent/skill_utils.py
@@ -175,10 +175,8 @@ def _detect_docker() -> bool:
_ENV_DETECTORS: Dict[str, Callable[[], bool]] = {
- "kanban": _detect_kanban,
- "docker": _detect_docker,
- # The Hermes Docker image runs s6-overlay as PID 1.
- "s6": lambda: os.path.isdir("/run/s6") or os.path.isdir("/package/admin/s6-overlay"),
+ "kanban": _detect_kanban, "docker": _detect_docker,
+ "s6": lambda: os.path.isdir("/run/s6") or os.path.isdir("/package/admin/s6-overlay"), # s6-overlay is PID 1 in the image
}
@@ -521,9 +519,8 @@ def is_quarantined_project_skill(skill_md) -> bool:
try:
from tools.skills_guard import scan_skill_cached
from hermes_constants import get_hermes_home
- result, _prov = scan_skill_cached(
- skill_dir, source=_PROJECT_SCAN_SOURCE, cache_dir=get_hermes_home() / "cache" / "project_skill_scans",
- )
+ cache_dir = get_hermes_home() / "cache" / "project_skill_scans"
+ result, _prov = scan_skill_cached(skill_dir, source=_PROJECT_SCAN_SOURCE, cache_dir=cache_dir)
quarantined = result.verdict == "dangerous"
if quarantined:
logger.warning("Project skill quarantined (verdict=dangerous): %s — %s", skill_dir, result.summary)
@@ -574,11 +571,8 @@ def normalize_skill_lookup_name(identifier: str) -> str:
try:
return str(identifier_path.resolve().relative_to(primary_root.resolve()))
except Exception:
- logger.debug(
- "Skill identifier %r is an absolute path outside trusted skills "
- "roots — passing through unchanged (skill_view will reject it)",
- raw_identifier,
- )
+ logger.debug("Skill identifier %r is an absolute path outside trusted skills "
+ "roots — passing through unchanged (skill_view will reject it)", raw_identifier)
return raw_identifier
diff --git a/agent/subdirectory_hints.py b/agent/subdirectory_hints.py
index d953320440a..a981101ec3b 100644
--- a/agent/subdirectory_hints.py
+++ b/agent/subdirectory_hints.py
@@ -16,12 +16,7 @@ from agent.prompt_builder import _scan_context_content
logger = logging.getLogger(__name__)
# Same filenames as prompt_builder.py, in priority order (first match wins per dir).
-_HINT_FILENAMES = [
- "AGENTS.override.md",
- "AGENTS.md", "agents.md",
- "CLAUDE.md", "claude.md",
- ".cursorrules",
-]
+_HINT_FILENAMES = ["AGENTS.override.md", "AGENTS.md", "agents.md", "CLAUDE.md", "claude.md", ".cursorrules"]
_MAX_HINT_CHARS = 8_000
_PATH_ARG_KEYS = {"path", "file_path", "workdir"}
_COMMAND_TOOLS = {"terminal"}
@@ -30,11 +25,8 @@ _MAX_ANCESTOR_WALK = 5 # ancestor levels walked per path — bounds deep-path s
# Directories that hold *copies* of context files (backups, vendored deps,
# VCS internals, caches), never authoritative project context.
_EXCLUDED_DIR_NAMES = frozenset({
- "node_modules", "venv", ".venv", "__pycache__",
- ".git", ".hg", ".svn",
- ".Trash", ".cache", ".tox", ".mypy_cache", ".pytest_cache",
- "site-packages", "dist-packages",
- "backups", "backup", ".backups",
+ "node_modules", "venv", ".venv", "__pycache__", ".git", ".hg", ".svn", ".Trash", ".cache", ".tox",
+ ".mypy_cache", ".pytest_cache", "site-packages", "dist-packages", "backups", "backup", ".backups",
"vendor", "third_party",
})
diff --git a/agent/system_prompt.py b/agent/system_prompt.py
index 67ca0829058..3aca7e3b036 100644
--- a/agent/system_prompt.py
+++ b/agent/system_prompt.py
@@ -30,8 +30,7 @@ from utils import is_truthy_value
logger = logging.getLogger(__name__)
_PLUGIN_SECTION_FRAME_RE = re.compile(
- r"^## Plugin Context: (?P<id>[a-z0-9][a-z0-9._-]{0,127})\n"
- r"<!-- hermes-plugin-section-chars:(?P<chars>[0-9]{1,4}) -->\n\n",
+ r"^## Plugin Context: (?P<id>[a-z0-9][a-z0-9._-]{0,127})\n<!-- hermes-plugin-section-chars:(?P<chars>[0-9]{1,4}) -->\n\n",
re.MULTILINE,
)
_GATE_WORDS = {**dict.fromkeys(("true", "always", "yes", "on"), True), **dict.fromkeys(("false", "never", "no", "off"), False)}
@@ -163,9 +162,8 @@ def _restore_plugin_prompt_sections(prompt: str) -> tuple:
content = framed[match.end() : match.end() + content_len]
if content_len > MAX_SYSTEM_PROMPT_SECTION_CHARS or len(content) != content_len:
continue
- restored.append(RenderedPluginSystemPromptSection(
- id=match.group("id"), content=content, position="after_memory", plugin="persisted-prompt",
- ))
+ restored.append(RenderedPluginSystemPromptSection(id=match.group("id"), content=content,
+ position="after_memory", plugin="persisted-prompt"))
return tuple(restored) if format_system_prompt_sections(restored) == framed else ()
@@ -294,12 +292,8 @@ def _skills_prompt(agent: Any, _r: Any) -> str:
_compact_cats = coding_compact_skill_categories(platform=agent.platform, cwd=resolve_context_cwd())
except Exception:
_compact_cats = frozenset()
- return _r.build_skills_system_prompt(
- available_tools=agent.valid_tool_names,
- available_toolsets=avail_toolsets,
- compact_categories=_compact_cats or None,
- skills_dir_override=_agent_skills_dir(agent),
- )
+ return _r.build_skills_system_prompt(available_tools=agent.valid_tool_names, available_toolsets=avail_toolsets,
+ compact_categories=_compact_cats or None, skills_dir_override=_agent_skills_dir(agent))
def _bot_mode_parts(agent: Any) -> List[str]:
@@ -426,22 +420,13 @@ def _timestamp_line(agent: Any) -> str:
_start = _session_start_like(agent, now)
timestamp_line = f"Conversation started: {_start.strftime('%A, %B %d, %Y')}{_zone_suffix}"
if now.strftime("%Y%m%d") != _start.strftime("%Y%m%d"):
- timestamp_line += (
- f"\nToday's date (as of the last context rebuild): "
- f"{now.strftime('%A, %B %d, %Y')} — trust this over the start "
- f"date for what day it is now; query tools for exact time."
- )
+ timestamp_line += (f"\nToday's date (as of the last context rebuild): {now.strftime('%A, %B %d, %Y')} "
+ "— trust this over the start date for what day it is now; query tools for exact time.")
if getattr(agent, "_bot_chat_timeless_prompt", False):
timestamp_line = f"Timezone: {', '.join(_bits)}" if _bits else ""
- for label, value in (
- ("Session ID", agent.session_id if agent.pass_session_id else None),
- ("Model", agent.model),
- ("Provider", agent.provider),
- ("Platform", agent.platform),
- ):
- if value:
- timestamp_line += f"\n{label}: {value}"
- return timestamp_line
+ trailer = (("Session ID", agent.session_id if agent.pass_session_id else None), ("Model", agent.model),
+ ("Provider", agent.provider), ("Platform", agent.platform))
+ return timestamp_line + "".join(f"\n{label}: {value}" for label, value in trailer if value)
def _memory_parts(agent: Any) -> List[str]:
@@ -527,10 +512,8 @@ def _coding_parts(agent: Any) -> Tuple[List[str], List[str], List[str]]:
try:
from agent.coding_context import coding_system_prompt_parts
if agent.valid_tool_names:
- return coding_system_prompt_parts(
- platform=agent.platform, cwd=resolve_context_cwd(),
- model=agent.model, valid_tool_names=agent.valid_tool_names,
- )
+ return coding_system_prompt_parts(platform=agent.platform, cwd=resolve_context_cwd(),
+ model=agent.model, valid_tool_names=agent.valid_tool_names)
except Exception:
pass
return [], [], []
@@ -620,11 +603,7 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None)
# a resumed process can reconstruct the stable prefix without re-running plugins.
volatile_parts.extend(_plugin_section_blocks(_frozen_plugin_prompt_sections(agent), "after_memory"))
volatile_parts.append(_timestamp_line(agent))
- return {
- "stable": _join_tier(stable_parts),
- "context": _join_tier(context_parts),
- "volatile": _join_tier(volatile_parts),
- }
+ return {"stable": _join_tier(stable_parts), "context": _join_tier(context_parts), "volatile": _join_tier(volatile_parts)}
def build_system_prompt(agent: Any, system_message: Optional[str] = None) -> str:
@@ -685,18 +664,11 @@ def format_tools_for_system_message(agent: Any) -> str:
"""JSON tool definitions in the trajectory format."""
if not agent.tools:
return "[]"
- return json.dumps([{
- "name": tool["function"]["name"],
- "description": tool["function"].get("description", ""),
- "parameters": tool["function"].get("parameters", {}),
- "required": None, # Match the format in the example
- } for tool in agent.tools], ensure_ascii=False)
-
-
-__all__ = [
- "build_system_prompt_parts",
- "build_system_prompt",
- "invalidate_system_prompt",
- "restore_plugin_prompt_sections",
- "format_tools_for_system_message",
-]
+ return json.dumps([{"name": t["function"]["name"], "description": t["function"].get("description", ""),
+ "parameters": t["function"].get("parameters", {}),
+ "required": None} # Match the format in the example
+ for t in agent.tools], ensure_ascii=False)
+
+
+__all__ = ["build_system_prompt_parts", "build_system_prompt", "invalidate_system_prompt",
+ "restore_plugin_prompt_sections", "format_tools_for_system_message"]