goal_command.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. """The CLI's /goal semantics, shared by every goal command surface.
  2. Adapters supply authorization and schedule the returned prompt; this module alone
  3. parses subcommands and mutates goal state. It never changes conversation history.
  4. """
  5. from __future__ import annotations
  6. from dataclasses import dataclass, replace
  7. import logging
  8. from typing import Callable
  9. from hermes_cli import goals
  10. logger = logging.getLogger(__name__)
  11. @dataclass(frozen=True)
  12. class GoalCommandResult:
  13. output: str
  14. prompt: str | None = None
  15. kickoff: bool = False
  16. clear_pending: str | None = None
  17. error: bool = False
  18. def _english(key, default, **values):
  19. return default.format(**values)
  20. def _status(mgr, arg, render):
  21. return GoalCommandResult(mgr.status_line())
  22. def _show(mgr, arg, render):
  23. return GoalCommandResult(f"{mgr.status_line()}\n{mgr.render_contract()}")
  24. def _pause(mgr, arg, render):
  25. state = mgr.pause(reason="user-paused")
  26. return GoalCommandResult(
  27. render("gateway.goal.paused", "⏸ Goal paused: {goal}", goal=state.goal) if state
  28. else render("gateway.goal.no_goal_set", "No goal set."),
  29. clear_pending="pause" if state else None,
  30. )
  31. def _resume(mgr, arg, render):
  32. state = mgr.resume()
  33. if state is None:
  34. return GoalCommandResult(render("gateway.goal.no_resume", "No goal to resume."))
  35. return GoalCommandResult(render("gateway.goal.resumed", "▶ Goal resumed: {goal}", goal=state.goal),
  36. prompt=mgr.next_continuation_prompt())
  37. def _clear(mgr, arg, render):
  38. had = mgr.has_goal()
  39. mgr.clear()
  40. return GoalCommandResult(render("gateway.goal_cleared", "✓ Goal cleared.") if had else
  41. render("gateway.no_active_goal", "No active goal."), clear_pending="clear")
  42. def _unwait(mgr, arg, render):
  43. return GoalCommandResult("▶ Wait barrier cleared — goal loop resumes." if mgr.stop_waiting()
  44. else "No wait barrier set.")
  45. def _wait(mgr, arg):
  46. if not arg:
  47. return GoalCommandResult("Usage: /goal wait <pid> [reason]", error=True)
  48. tokens = arg.split(None, 1)
  49. try:
  50. pid = int(tokens[0])
  51. except ValueError:
  52. return GoalCommandResult("/goal wait: <pid> must be an integer process id.", error=True)
  53. reason = tokens[1].strip() if len(tokens) > 1 else ""
  54. mgr.wait_on(pid, reason=reason)
  55. suffix = f" ({reason})" if reason else ""
  56. return GoalCommandResult(f"⏳ Goal parked on pid {pid}{suffix}. Loop pauses until it exits.")
  57. def _gate_add(mgr, arg):
  58. gate = mgr.add_gate(arg)
  59. return GoalCommandResult(f"⚿ Gate added: $ {gate.command} "
  60. f"({gate.max_retries} retries, {gate.timeout_seconds}s timeout). "
  61. "It must pass before the goal can complete.")
  62. def _gate_remove(mgr, arg):
  63. return GoalCommandResult(f"✓ Gate removed: $ {mgr.remove_gate(int(arg))}")
  64. def _gate_clear(mgr, arg):
  65. count = mgr.clear_gates()
  66. return GoalCommandResult(f"✓ Cleared {count} gate{'s' if count != 1 else ''}.")
  67. _GATE_HANDLERS = {"add": _gate_add, "remove": _gate_remove, "rm": _gate_remove, "clear": _gate_clear}
  68. _EXACT_HANDLERS = {
  69. "": _status, "status": _status, "show": _show, "pause": _pause,
  70. "resume": _resume, "continue": _resume, "unpause": _resume,
  71. "clear": _clear, "stop": _clear, "done": _clear, "unwait": _unwait,
  72. }
  73. # Non-destructive control verbs: with trailing words the verb still wins, so
  74. # `/goal resume last goal` resumes instead of silently replacing the goal text.
  75. # clear/stop/done stay out — guessing wrong would end a goal the user meant to keep.
  76. _BARE_CONTROL_VERBS = frozenset({"resume", "continue", "unpause", "pause", "status", "show", "unwait"})
  77. # First words that make a command goal control (the gateway busy path dispatches these).
  78. _CONTROL_FIRST_WORDS = _BARE_CONTROL_VERBS | {"wait", "gate"}
  79. def _bare_control(mgr, verb, rest, render):
  80. result = _EXACT_HANDLERS[verb](mgr, "", render)
  81. return replace(result, output=result.output + (
  82. f"\n(ignored {rest!r}: a control command never sets goal text — use /goal -- <text> "
  83. "when the goal really starts with a control word.)"))
  84. def _gate(mgr, arg, authorize_gate):
  85. if not arg or arg.lower() == "list":
  86. return GoalCommandResult(mgr.render_gates())
  87. tokens = arg.split(None, 1)
  88. verb, rest = tokens[0].lower(), tokens[1].strip() if len(tokens) > 1 else ""
  89. handler = _GATE_HANDLERS.get(verb)
  90. if handler is None or (verb == "clear" and rest) or (verb != "clear" and not rest):
  91. return GoalCommandResult("Usage: /goal gate [list | add <command> | remove <N> | clear]", error=True)
  92. # Gates run shell commands without a later approval. The adapter must explicitly
  93. # authorize creation; recovery commands remain available to non-admin senders.
  94. if verb == "add" and (denial := authorize_gate()):
  95. return GoalCommandResult(denial, error=True)
  96. try:
  97. return handler(mgr, rest)
  98. except (RuntimeError, ValueError, IndexError) as exc:
  99. operation = "remove" if verb == "rm" else verb
  100. return GoalCommandResult(f"/goal gate {operation}: {exc}", error=True)
  101. def _set(mgr, arg, *, drafting, last_user_message, render, progress):
  102. if drafting:
  103. if not arg:
  104. return GoalCommandResult("Usage: /goal draft <objective in plain language>", error=True)
  105. if progress is not None:
  106. progress("Drafting completion contract…")
  107. try:
  108. contract = goals.draft_contract(arg)
  109. except Exception as exc:
  110. logger.debug("goal draft failed: %s", exc)
  111. contract = None
  112. headline = arg
  113. else:
  114. headline, contract = goals.parse_contract(arg)
  115. contract = contract if not contract.is_empty() else None
  116. previous = mgr.state.goal if mgr.has_goal() else ""
  117. state = mgr.set(headline or arg, contract=contract)
  118. output = render("gateway.goal.set", "⊙ Goal set ({budget}-turn budget): {goal}",
  119. budget=state.max_turns, goal=state.goal)
  120. if previous and previous != state.goal:
  121. output += f"\n(replaced the previous goal)\n was: {previous}"
  122. if state.has_contract():
  123. label = "Drafted completion contract:" if drafting else "Completion contract:"
  124. output += f"\n{label}\n{state.contract.render_block()}"
  125. if drafting:
  126. output += ("\nTighten any field by re-setting the goal with inline lines "
  127. "(e.g. verify: <command>), then /goal resume. Use /goal show to review."
  128. if state.has_contract() else
  129. "\nCouldn't draft a contract (aux model unavailable) — running as a "
  130. "free-form goal. The per-turn judge still applies.")
  131. else:
  132. against = " against the contract above" if state.has_contract() else ""
  133. output += (f"\nAfter each turn, a judge model checks if the goal is done{against}. "
  134. "Hermes keeps working until it is, you pause/clear it, or the budget is "
  135. "exhausted. Use /goal status, /goal show, /goal pause, /goal resume, /goal clear.")
  136. return GoalCommandResult(output, goals.goal_kick_prompt(state.goal, last_user_message), kickoff=True)
  137. def is_goal_control(arg: str) -> bool:
  138. """Whether this command controls an existing goal rather than replacing it."""
  139. normalized = arg.strip().lower()
  140. first = normalized.split(None, 1)[0] if normalized else ""
  141. return normalized in _EXACT_HANDLERS or first in _CONTROL_FIRST_WORDS
  142. def dispatch_goal_command(
  143. mgr: goals.GoalManager, arg: str, *, authorize_gate: Callable[[], str | None],
  144. last_user_message=None, render: Callable = _english,
  145. progress: Callable[[str], None] | None = None,
  146. ) -> GoalCommandResult:
  147. """Apply one command. ``authorize_gate`` returns a denial or None (explicit approval).
  148. Synchronous like GoalManager: async adapters run this off-loop with copied
  149. ContextVars so draft credentials and persisted I/O stay in the caller's profile.
  150. """
  151. arg = arg.strip()
  152. tokens = arg.split(None, 1)
  153. verb = tokens[0].lower() if tokens else ""
  154. rest = tokens[1].strip() if len(tokens) > 1 else ""
  155. prefix = "Invalid goal"
  156. try:
  157. if verb == "--":
  158. # Verbatim goal text for goals that start with a control word (`/goal -- pause the cron`).
  159. return _set(mgr, rest, drafting=False, last_user_message=last_user_message,
  160. render=render, progress=progress)
  161. if handler := _EXACT_HANDLERS.get(arg.lower()):
  162. return handler(mgr, "", render)
  163. if verb in _BARE_CONTROL_VERBS:
  164. return _bare_control(mgr, verb, rest, render)
  165. if verb == "wait":
  166. prefix = "/goal wait"
  167. return _wait(mgr, rest)
  168. if verb == "gate":
  169. prefix = "/goal gate"
  170. return _gate(mgr, rest, authorize_gate)
  171. return _set(mgr, rest if verb == "draft" else arg,
  172. drafting=verb == "draft", last_user_message=last_user_message,
  173. render=render, progress=progress)
  174. except (RuntimeError, ValueError, IndexError) as exc:
  175. output = (render("gateway.goal.invalid", "Invalid goal: {error}", error=str(exc))
  176. if prefix == "Invalid goal" else f"{prefix}: {exc}")
  177. return GoalCommandResult(output, error=True)