Skip to content

The agent that grows with you

refactor(hermes_cli): blueprint_cmd — match passes as ordered table, simpler kv parse

Teknium852178c312a3
diff --git a/hermes_cli/blueprint_cmd.py b/hermes_cli/blueprint_cmd.py
index 187f2a49704..d51cd42fb76 100644
--- a/hermes_cli/blueprint_cmd.py
+++ b/hermes_cli/blueprint_cmd.py
@@ -49,22 +49,29 @@ def _parse_kv(tokens) -> Tuple[Dict[str, str], list]:
values: Dict[str, str] = {}
leftovers = []
for tok in tokens:
- if "=" in tok:
- k, _, v = tok.partition("=")
- k = k.strip()
- if k:
- values[k] = v.strip()
- continue
- leftovers.append(tok)
+ k, sep, v = tok.partition("=")
+ if sep and k.strip():
+ values[k.strip()] = v.strip()
+ else:
+ leftovers.append(tok)
return values, leftovers
+def _pick(candidates: List[Any]) -> Optional[Tuple[Optional[Any], List[Any]]]:
+ """One candidate -> (it, []); several -> (None, all); none -> None (keep searching)."""
+ if len(candidates) == 1:
+ return candidates[0], []
+ if candidates:
+ return None, candidates
+ return None
+
+
def match_blueprint(query: str) -> Tuple[Optional[Any], List[Any]]:
"""Resolve a free-typed blueprint name to a blueprint.
Matching is forgiving because chat-line users type the name (unlike the dashboard/Discord where
- it's picked): exact key first, then case-insensitive prefix on key or title, then a difflib
- fuzzy pass.
+ it's picked): exact key first, then case-insensitive prefix on key or title, then substring
+ anywhere in key/title/description, then a difflib fuzzy pass on keys.
"""
from cron.blueprint_catalog import CATALOG, get_blueprint
@@ -76,35 +83,15 @@ def match_blueprint(query: str) -> Tuple[Optional[Any], List[Any]]:
if exact is not None:
return exact, []
- # Prefix match on key or title word-start.
- prefix = [
- r for r in CATALOG
- if r.key.lower().startswith(q)
- or any(w.lower().startswith(q) for w in r.title.split())
- ]
- if len(prefix) == 1:
- return prefix[0], []
- if len(prefix) > 1:
- return None, prefix
-
- # Substring match anywhere in key/title/description.
- substr = [
- r for r in CATALOG
- if q in r.key.lower() or q in r.title.lower() or q in r.description.lower()
- ]
- if len(substr) == 1:
- return substr[0], []
- if len(substr) > 1:
- return None, substr
-
- # Fuzzy on keys (typo tolerance).
- keys = [r.key for r in CATALOG]
- close = difflib.get_close_matches(q, keys, n=3, cutoff=0.6)
- if len(close) == 1:
- return get_blueprint(close[0]), []
- if len(close) > 1:
- return None, [get_blueprint(k) for k in close]
-
+ passes = (
+ lambda: [r for r in CATALOG if r.key.lower().startswith(q) or any(w.lower().startswith(q) for w in r.title.split())],
+ lambda: [r for r in CATALOG if q in r.key.lower() or q in r.title.lower() or q in r.description.lower()],
+ lambda: [get_blueprint(k) for k in difflib.get_close_matches(q, [r.key for r in CATALOG], n=3, cutoff=0.6)],
+ )
+ for candidates in passes:
+ picked = _pick(candidates())
+ if picked is not None:
+ return picked
return None, []
@@ -126,16 +113,13 @@ def build_blueprint_seed(blueprint) -> str:
"""
from cron.blueprint_catalog import WEEKDAY_PRESETS
- lines: List[str] = []
- lines.append(
+ lines: List[str] = [
f"Set up the '{blueprint.title}' automation for me (automation blueprint "
- f"'{blueprint.key}'). {blueprint.description}"
- )
- lines.append("")
- lines.append(
+ f"'{blueprint.key}'). {blueprint.description}",
+ "",
"Ask me for each of these, one at a time, offering the default in "
- "brackets if I don't have a preference:"
- )
+ "brackets if I don't have a preference:",
+ ]
for s in blueprint.slots:
bits = [f"- {s.label} ({s.name})"]
if s.options:
@@ -178,8 +162,7 @@ def _fmt_catalog() -> str:
def _fmt_candidates(query: str, candidates: List[Any]) -> str:
lines = [f"'{query}' matches several blueprints — which one?\n"]
- for r in candidates:
- lines.append(f" • {r.key} — {r.title}")
+ lines.extend(f" • {r.key} — {r.title}" for r in candidates)
lines.append("\nRun `/blueprint <name>` with one of the names above.")
return "\n".join(lines)
@@ -187,22 +170,16 @@ def _fmt_candidates(query: str, candidates: List[Any]) -> str:
def _fmt_no_match(query: str) -> str:
from cron.blueprint_catalog import CATALOG
- keys = [r.key for r in CATALOG]
- close = difflib.get_close_matches((query or "").lower(), keys, n=3, cutoff=0.4)
+ close = difflib.get_close_matches((query or "").lower(), [r.key for r in CATALOG], n=3, cutoff=0.4)
msg = f"No automation blueprint matches '{query}'."
if close:
msg += " Did you mean: " + ", ".join(close) + "?"
- msg += " Run /blueprint to see the catalog."
- return msg
+ return msg + " Run /blueprint to see the catalog."
def _manage_hint(surface: str) -> str:
- """Post-create management hint. /cron is a CLI-only slash command; on gateway platforms the user
- manages jobs by asking the agent (cronjob tool) or from the dashboard.
- """
- if surface == "cli":
- return "Manage it with /cron."
- return "Ask me to list, pause, or remove it any time."
+ """/cron is CLI-only; on gateway platforms jobs are managed via the agent (cronjob tool) or dashboard."""
+ return "Manage it with /cron." if surface == "cli" else "Ask me to list, pause, or remove it any time."
def handle_blueprint_command(
@@ -213,13 +190,10 @@ def handle_blueprint_command(
) -> BlueprintCommandResult:
"""Dispatch a ``/blueprint`` invocation.
- Returns a :class:`BlueprintCommandResult`. When ``agent_seed`` is set the caller must feed it to
- the agent as the next user turn; otherwise the command is fully handled and only ``text`` is
- shown.
-
- ``args`` is everything after ``/blueprint``. ``origin`` lets a directly created job deliver back
- to the chat it was set up from. ``surface`` (``"cli"`` | ``"gateway"``) picks the right wording
- for follow-up hints — ``/cron`` only exists on the CLI.
+ When ``agent_seed`` is set on the result the caller must feed it to the agent as the next user
+ turn; otherwise the command is fully handled and only ``text`` is shown. ``args`` is everything
+ after ``/blueprint``; ``origin`` lets a directly created job deliver back to the chat it was set
+ up from; ``surface`` (``"cli"`` | ``"gateway"``) picks the follow-up hint wording.
"""
try:
from cron.blueprint_catalog import fill_blueprint, BlueprintFillError
@@ -232,7 +206,6 @@ def handle_blueprint_command(
except ValueError:
tokens = (args or "").split()
- # Bare -> list catalog.
if not tokens:
return BlueprintCommandResult(_fmt_catalog())
@@ -241,18 +214,12 @@ def handle_blueprint_command(
blueprint, candidates = match_blueprint(query)
if blueprint is None:
- if candidates:
- return BlueprintCommandResult(_fmt_candidates(query, candidates))
- return BlueprintCommandResult(_fmt_no_match(query))
+ return BlueprintCommandResult(_fmt_candidates(query, candidates) if candidates else _fmt_no_match(query))
# `<name>` with no inline slot values -> seed the agent to ask for them.
if not values:
- seed = build_blueprint_seed(blueprint)
- text = (
- f"Setting up '{blueprint.title}' ({_humanize_schedule(blueprint)}). "
- "I'll ask you a couple of things…"
- )
- return BlueprintCommandResult(text, agent_seed=seed)
+ text = f"Setting up '{blueprint.title}' ({_humanize_schedule(blueprint)}). I'll ask you a couple of things…"
+ return BlueprintCommandResult(text, agent_seed=build_blueprint_seed(blueprint))
# `<name> slot=val …` -> fill + create directly (deterministic shortcut).
try:
@@ -264,10 +231,7 @@ def handle_blueprint_command(
)
try:
- from cron.scheduler import (
- CronSchedulerRegistrationError,
- create_job_with_scheduler_registration,
- )
+ from cron.scheduler import CronSchedulerRegistrationError, create_job_with_scheduler_registration
job = create_job_with_scheduler_registration(**spec)
except CronSchedulerRegistrationError as e: