Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
485 changes: 239 additions & 246 deletions agent/agent_init.py

Large diffs are not rendered by default.

29 changes: 23 additions & 6 deletions agent/prompt_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from pathlib import Path

from hermes_constants import get_hermes_home, get_skills_dir, is_wsl
from hermes_cli.config import cfg_get, load_config
from typing import Optional

from agent.runtime_cwd import resolve_agent_cwd
Expand All @@ -26,6 +27,9 @@
)
from utils import atomic_json_write

# TOON-lite compact encoding for skills index (opt-in via context.compact_format)
from agent.toon_lite import format_skills_index_toon as _toon_skills_index

logger = logging.getLogger(__name__)

# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -1254,13 +1258,26 @@ def build_skills_system_prompt(
"If a skill you loaded was missing steps, had wrong commands, or needed "
"pitfalls you discovered, update it before finishing.\n"
"\n"
"<available_skills>\n"
+ "\n".join(index_lines) + "\n"
"</available_skills>\n"
"\n"
"Only proceed without loading a skill if genuinely none are relevant to the task."
)

# Use skill routing table when configured (compact intent→skill mapping)
if bool(cfg_get(load_config(), "skills", "routing_table", default=False)):
from agent.skill_router import format_skills_routing_table as _rtr
_router_block = _rtr(skills_by_category, category_descriptions)
if _router_block:
result += _router_block
elif bool(cfg_get(load_config(), "context", "compact_format", default=False)):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The compact branch removes <available_skills>, but hermes_cli/prompt_size.py and agent/context_breakdown.py identify the skills section only with that tag pair. Update those consumers and add compact-mode accounting tests so diagnostics do not report zero skill usage.

result += _toon_skills_index(skills_by_category, category_descriptions)
result += "\n\nOnly proceed without loading a skill if genuinely none are relevant to the task."
else:
result += (
"<available_skills>\n"
+ "\n".join(index_lines) + "\n"
"</available_skills>\n"
"\n"
"Only proceed without loading a skill if genuinely none are relevant to the task."
)

# ── Store in LRU cache ────────────────────────────────────────────
with _SKILLS_PROMPT_CACHE_LOCK:
_SKILLS_PROMPT_CACHE[cache_key] = result
Expand Down Expand Up @@ -1361,7 +1378,7 @@ def load_soul_md() -> Optional[str]:
``skip_soul=True`` so SOUL.md isn't injected twice.
"""
try:
from hermes_cli.config import ensure_hermes_home
from hermes_cli.config import ensure_hermes_home, cfg_get
ensure_hermes_home()
except Exception as e:
logger.debug("Could not ensure HERMES_HOME before loading SOUL.md: %s", e)
Expand Down
100 changes: 100 additions & 0 deletions agent/skill_router.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
"""Skill routing table — compact intent→skill mapping for system prompt.

Replaces the full ``<available_skills>`` block with a routing-oriented format
that maps categories to skill names. Skill names are self-describing
(e.g. ``github-code-review``, ``systematic-debugging``) so the model can pick
the closest match and load the full skill with ``skill_view(name)``.

Savings vs full listing: ~75 % fewer tokens (~800 vs ~3100 for a typical
60-skill installation).
"""

from __future__ import annotations

from typing import Dict, List, Tuple


def _derive_routing_hints(
skills_by_category: Dict[str, List[Tuple[str, str]]],
category_descriptions: Dict[str, str],
) -> Dict[str, str]:
"""Derive brief routing hints (3-6 words) from category descriptions.

Truncates long descriptions and falls back to representative skill names
when the description is missing or irrelevant."""
hints: Dict[str, str] = {}
for category, skills in sorted(skills_by_category.items()):
if not skills:
continue
names = [name for name, _ in skills]

cat_desc = (category_descriptions.get(category) or "").strip().strip("'\"")

if cat_desc:
# Try to extract the most meaningful fragment
# Category descriptions follow pattern: "Skills for X — ..." or "X skills: ..."
# We want just the core domain description
for prefix in ("Skills for ", "Knowledge and Tools for "):
if cat_desc.startswith(prefix):
cat_desc = cat_desc[len(prefix):]
break
# Take first ~50 chars or up to first period/semicolon
if len(cat_desc) > 50:
cut = max(cat_desc[:50].rfind(" "), cat_desc[:50].rfind(","), 30)
cat_desc = cat_desc[:cut] if cut > 0 else cat_desc[:50]
hints[category] = cat_desc
elif len(names) <= 3:
hints[category] = ", ".join(names)
else:
sample = names[:2]
hints[category] = f"{', '.join(sample)} +{len(names)-2} more"

return hints


def format_skills_routing_table(
skills_by_category: Dict[str, List[Tuple[str, str]]],
category_descriptions: Dict[str, str] | None = None,
) -> str:
"""Build a compact routing table from the skill index.

Format::

## Skill Router
category: skill1, skill2, skill3 # routing hint

The model scans for a matching category, picks a skill name, and calls
``skill_view(name)`` for the full instructions.

Returns empty string if no skills.
"""
if not skills_by_category:
return ""

category_descriptions = category_descriptions or {}
hints = _derive_routing_hints(skills_by_category, category_descriptions)

lines: List[str] = [
"## Skill Router",
"Scan for matching category, load with skill_view(name).",
"Skill names are descriptive — pick the closest match.",
"",
]

for category in sorted(skills_by_category.keys()):
skills = skills_by_category[category]
if not skills:
continue

# Deduplicate and sort
skill_names = sorted(set(name for name, _ in skills))
names_str = ", ".join(skill_names)
hint = hints.get(category, category)
lines.append(f" {category}: {names_str} # {hint}")

lines.append("")
lines.append(
"Only proceed without loading a skill if genuinely none are relevant."
)

return "\n".join(lines)
Loading