Files
hermes-agent/hermes_cli/goal_command.py
Teknium f2b19fd37c refactor(slash): retire the folded command names
The folds Teknium approved are on main (/verbose focus, /statusbar battery|indicator,
/status's egress block, /model --runtime, /pet hatch, /goal add, /help <page>,
/billing topup|upgrade, TUI /verbose details|density), but the old names still ran.
They are now retired with RETIRED_COMMANDS: typing /focus, /battery, /indicator,
/egress, /codex-runtime, /hatch, /generate-pet, /subgoal, /commands, /topup,
/subscription or /upgrade (either _ or - spelling) runs nothing on the CLI, gateway,
TUI and Desktop and answers "`/old` is now `/new`.". The TUI answers its own /details,
/detail and /density the same way (slash.retired), since they never existed elsewhere.

The old names leave help, menus, completion, the Telegram menu priority, the Slack
/hermes-only set, the Desktop registry and description keys, and the docs tables (the
Renamed commands table lists each). Handlers only the old names reached are removed;
the umbrella commands still call the shared handlers.

Slash access: the folded forms check their own user_allowed_commands keys (goal-add,
model-runtime, status-egress, help-pages) instead of the retired names, and an
operator list that still names subgoal, codex-runtime, egress, commands or topup
grants what replaced it, so no existing config loses or gains access.
2026-11-29 03:22:20 -08:00

266 lines
12 KiB
Python

"""The CLI's /goal semantics, shared by every goal command surface.
Adapters supply authorization and schedule the returned prompt; this module alone
parses subcommands and mutates goal state. It never changes conversation history.
"""
from __future__ import annotations
from dataclasses import dataclass, replace
import logging
from typing import Callable
from hermes_cli import goals
logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class GoalCommandResult:
output: str
prompt: str | None = None
kickoff: bool = False
clear_pending: str | None = None
error: bool = False
def _english(key, default, **values):
return default.format(**values)
def _status(mgr, arg, render):
return GoalCommandResult(mgr.status_line())
def _show(mgr, arg, render):
return GoalCommandResult(f"{mgr.status_line()}\n{mgr.render_contract()}")
def _pause(mgr, arg, render):
state = mgr.pause(reason="user-paused")
return GoalCommandResult(
render("gateway.goal.paused", "⏸ Goal paused: {goal}", goal=state.goal) if state
else render("gateway.goal.no_goal_set", "No goal set."),
clear_pending="pause" if state else None,
)
def _resume(mgr, arg, render):
state = mgr.resume()
if state is None:
return GoalCommandResult(render("gateway.goal.no_resume", "No goal to resume."))
return GoalCommandResult(render("gateway.goal.resumed", "▶ Goal resumed: {goal}", goal=state.goal),
prompt=mgr.next_continuation_prompt())
def _clear(mgr, arg, render):
had = mgr.has_goal()
mgr.clear()
return GoalCommandResult(render("gateway.goal_cleared", "✓ Goal cleared.") if had else
render("gateway.no_active_goal", "No active goal."), clear_pending="clear")
def _unwait(mgr, arg, render):
return GoalCommandResult("▶ Wait barrier cleared — goal loop resumes." if mgr.stop_waiting()
else "No wait barrier set.")
def _wait(mgr, arg):
if not arg:
return GoalCommandResult("Usage: /goal wait <pid> [reason]", error=True)
tokens = arg.split(None, 1)
try:
pid = int(tokens[0])
except ValueError:
return GoalCommandResult("/goal wait: <pid> must be an integer process id.", error=True)
reason = tokens[1].strip() if len(tokens) > 1 else ""
mgr.wait_on(pid, reason=reason)
suffix = f" ({reason})" if reason else ""
return GoalCommandResult(f"⏳ Goal parked on pid {pid}{suffix}. Loop pauses until it exits.")
def _gate_add(mgr, arg):
gate = mgr.add_gate(arg)
return GoalCommandResult(f"⚿ Gate added: $ {gate.command} "
f"({gate.max_retries} retries, {gate.timeout_seconds}s timeout). "
"It must pass before the goal can complete.")
def _gate_remove(mgr, arg):
return GoalCommandResult(f"✓ Gate removed: $ {mgr.remove_gate(int(arg))}")
def _gate_clear(mgr, arg):
count = mgr.clear_gates()
return GoalCommandResult(f"✓ Cleared {count} gate{'s' if count != 1 else ''}.")
def _subgoals(mgr, arg, render):
if not mgr.has_goal():
return GoalCommandResult(render("gateway.subgoal.no_goal", "No active goal. Set one with /goal <text>."))
return GoalCommandResult(f"{mgr.status_line()}\n{mgr.render_subgoals()}")
def _subgoal_add(mgr, arg, render):
if not arg:
return GoalCommandResult("Usage: /goal add <criterion> (use /goal -- <text> for a goal that starts with 'add')",
error=True)
text = mgr.add_subgoal(arg)
return GoalCommandResult(render("gateway.subgoal.added", "✓ Added subgoal {index}: {text}",
index=len(mgr.state.subgoals), text=text))
def _subgoal_remove(mgr, arg, render):
if arg.lower() == "all":
count = mgr.clear_subgoals()
if not count:
return GoalCommandResult(render("gateway.subgoal.none_to_clear", "No subgoals to clear."))
key = "gateway.subgoal.cleared_one" if count == 1 else "gateway.subgoal.cleared_other"
return GoalCommandResult(render(key, "✓ Cleared {count} subgoal" + ("." if count == 1 else "s."), count=count))
try:
index = int(arg)
except ValueError:
return GoalCommandResult("Usage: /goal remove <N|all> (N is the 1-based subgoal number from /goal subgoals; "
"use /goal -- <text> for a goal that starts with 'remove')", error=True)
removed = mgr.remove_subgoal(index)
return GoalCommandResult(render("gateway.subgoal.removed", "✓ Removed subgoal {index}: {text}",
index=index, text=removed))
# The /subgoal forms as /goal verbs: ``add <text>``, ``remove <N|all>``, bare ``subgoals`` lists them.
_SUBGOAL_HANDLERS = {"add": _subgoal_add, "remove": _subgoal_remove}
_GATE_HANDLERS = {"add": _gate_add, "remove": _gate_remove, "rm": _gate_remove, "clear": _gate_clear}
_EXACT_HANDLERS = {
"": _status, "status": _status, "show": _show, "pause": _pause,
"resume": _resume, "continue": _resume, "unpause": _resume,
"clear": _clear, "stop": _clear, "done": _clear, "unwait": _unwait, "subgoals": _subgoals,
}
# Non-destructive control verbs: with trailing words the verb still wins, so
# `/goal resume last goal` resumes instead of silently replacing the goal text.
# clear/stop/done stay out — guessing wrong would end a goal the user meant to keep.
_BARE_CONTROL_VERBS = frozenset({"resume", "continue", "unpause", "pause", "status", "show", "unwait", "subgoals"})
# First words that make a command goal control (the gateway busy path dispatches these).
_CONTROL_FIRST_WORDS = _BARE_CONTROL_VERBS | {"wait", "gate", *_SUBGOAL_HANDLERS}
def _bare_control(mgr, verb, rest, render):
result = _EXACT_HANDLERS[verb](mgr, "", render)
return replace(result, output=result.output + (
f"\n(ignored {rest!r}: a control command never sets goal text — use /goal -- <text> "
"when the goal really starts with a control word.)"))
def _gate(mgr, arg, authorize_gate):
if not arg or arg.lower() == "list":
return GoalCommandResult(mgr.render_gates())
tokens = arg.split(None, 1)
verb, rest = tokens[0].lower(), tokens[1].strip() if len(tokens) > 1 else ""
handler = _GATE_HANDLERS.get(verb)
if handler is None or (verb == "clear" and rest) or (verb != "clear" and not rest):
return GoalCommandResult("Usage: /goal gate [list | add <command> | remove <N> | clear]", error=True)
# Gates run shell commands without a later approval. The adapter must explicitly
# authorize creation; recovery commands remain available to non-admin senders.
if verb == "add" and (denial := authorize_gate()):
return GoalCommandResult(denial, error=True)
try:
return handler(mgr, rest)
except (RuntimeError, ValueError, IndexError) as exc:
operation = "remove" if verb == "rm" else verb
return GoalCommandResult(f"/goal gate {operation}: {exc}", error=True)
def _set(mgr, arg, *, drafting, last_user_message, render, progress):
if drafting:
if not arg:
return GoalCommandResult("Usage: /goal draft <objective in plain language>", error=True)
if progress is not None:
progress("Drafting completion contract…")
try:
contract = goals.draft_contract(arg)
except Exception as exc:
logger.debug("goal draft failed: %s", exc)
contract = None
headline = arg
else:
headline, contract = goals.parse_contract(arg)
contract = contract if not contract.is_empty() else None
previous = mgr.state.goal if mgr.has_goal() else ""
state = mgr.set(headline or arg, contract=contract)
output = render("gateway.goal.set", "⊙ Goal set ({budget}-turn budget): {goal}",
budget=state.max_turns, goal=state.goal)
if previous and previous != state.goal:
output += f"\n(replaced the previous goal)\n was: {previous}"
if state.has_contract():
label = "Drafted completion contract:" if drafting else "Completion contract:"
output += f"\n{label}\n{state.contract.render_block()}"
if drafting:
output += ("\nTighten any field by re-setting the goal with inline lines "
"(e.g. verify: <command>), then /goal resume. Use /goal show to review."
if state.has_contract() else
"\nCouldn't draft a contract (aux model unavailable) — running as a "
"free-form goal. The per-turn judge still applies.")
else:
against = " against the contract above" if state.has_contract() else ""
output += (f"\nAfter each turn, a judge model checks if the goal is done{against}. "
"Hermes keeps working until it is, you pause/clear it, or the budget is "
"exhausted. Use /goal status, /goal show, /goal pause, /goal resume, /goal clear.")
return GoalCommandResult(output, goals.goal_kick_prompt(state.goal, last_user_message), kickoff=True)
def is_subgoal_form(arg: str) -> bool:
"""Whether this /goal command is a /subgoal form (``add``, ``remove``, ``subgoals``): the
gateway gates it on the ``goal-add`` slash permission too."""
words = arg.strip().split(None, 1)
return bool(words) and (words[0].lower() in _SUBGOAL_HANDLERS or words[0].lower() == "subgoals")
def is_goal_control(arg: str) -> bool:
"""Whether this command controls an existing goal rather than replacing it."""
normalized = arg.strip().lower()
first = normalized.split(None, 1)[0] if normalized else ""
return normalized in _EXACT_HANDLERS or first in _CONTROL_FIRST_WORDS
def dispatch_goal_command(
mgr: goals.GoalManager, arg: str, *, authorize_gate: Callable[[], str | None],
last_user_message=None, render: Callable = _english,
progress: Callable[[str], None] | None = None,
) -> GoalCommandResult:
"""Apply one command. ``authorize_gate`` returns a denial or None (explicit approval).
Synchronous like GoalManager: async adapters run this off-loop with copied
ContextVars so draft credentials and persisted I/O stay in the caller's profile.
"""
arg = arg.strip()
tokens = arg.split(None, 1)
verb = tokens[0].lower() if tokens else ""
rest = tokens[1].strip() if len(tokens) > 1 else ""
prefix = "Invalid goal"
try:
if verb == "--":
# Verbatim goal text for goals that start with a control word (`/goal -- pause the cron`).
return _set(mgr, rest, drafting=False, last_user_message=last_user_message,
render=render, progress=progress)
if handler := _EXACT_HANDLERS.get(arg.lower()):
return handler(mgr, "", render)
if verb in _BARE_CONTROL_VERBS:
return _bare_control(mgr, verb, rest, render)
if verb == "wait":
prefix = "/goal wait"
return _wait(mgr, rest)
if verb == "gate":
prefix = "/goal gate"
return _gate(mgr, rest, authorize_gate)
if subgoal_handler := _SUBGOAL_HANDLERS.get(verb):
prefix = f"/goal {verb}"
if not mgr.has_goal():
return _subgoals(mgr, "", render)
return subgoal_handler(mgr, rest, render)
return _set(mgr, rest if verb == "draft" else arg,
drafting=verb == "draft", last_user_message=last_user_message,
render=render, progress=progress)
except (RuntimeError, ValueError, IndexError) as exc:
output = (render("gateway.goal.invalid", "Invalid goal: {error}", error=str(exc))
if prefix == "Invalid goal" else f"{prefix}: {exc}")
return GoalCommandResult(output, error=True)