The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): _attempt/_handoff_keep verdict helpers, fold print+return in cli_commands_mixin
Teknium42cb3efef2b7
diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.pyindex e16415e6fb3..4acb57d83d1 100644--- a/hermes_cli/cli_commands_mixin.py+++ b/hermes_cli/cli_commands_mixin.py@@ -88,6 +88,18 @@ def _probe(module: str, name: str, default, *args):return default+_FAILED = object()+++def _attempt(label: str, errors, fn, *args, **kwargs):+ """``fn(*args, **kwargs)``, or ``_FAILED`` after printing `` <label>: <exc>`` for ``errors``."""+ try:+ return fn(*args, **kwargs)+ except errors as exc:+ _cp(f" {label}: {exc}")+ return _FAILED++def _say_block(*lines: str) -> None:"""print() the lines framed by a blank line above and below (the /browser output style)."""print()@@ -284,8 +296,7 @@ def _parse_cron_flags(tokens):try:opts["repeat"] = int(tokens[i + 1])except ValueError:- print("(._.) --repeat must be an integer")- return None+ return print("(._.) --repeat must be an integer")i += 2elif token in _CRON_VALUE_FLAGS and has_value:opts[_CRON_VALUE_FLAGS[token]] = tokens[i + 1]@@ -603,13 +614,10 @@ class CLICommandsMixin:def _checkpoint_manager(self, disabled_lines):"""The agent's checkpoint manager, or None after printing why it is unavailable."""if not hasattr(self, 'agent') or not self.agent:- print(" No active agent session.")- return None+ return print(" No active agent session.")mgr = self.agent._checkpoint_mgrif not mgr.enabled:- for line in disabled_lines:- print(line)- return None+ return _pr(*disabled_lines)return mgrdef _handle_rollback_command(self, command: str):@@ -1108,6 +1116,12 @@ class CLICommandsMixin:_HANDOFF_RUNNING_TIMEOUT = 900.0 # full synthetic agent turn + delivery_HANDOFF_HEARTBEAT_EVERY = 30.0+ @staticmethod+ def _handoff_keep(*lines: str) -> bool:+ """Print ``lines`` and keep the CLI session (the True verdict of /handoff)."""+ _cp(*lines)+ return True+def _handle_handoff_command(self, cmd_original: str) -> bool:"""Handle ``/handoff <platform>`` — transfer this CLI session to a gateway platform.@@ -1115,10 +1129,9 @@ class CLICommandsMixin:Returns False only on ``completed`` (caller exits like /quit); True keeps the session."""platform_name = _command_arg(cmd_original).lower()if not platform_name:- _cp(" Usage: /handoff <platform>",- " Hands the current session off to that platform's home channel.",- " The CLI session ends here; resume it later with /resume.")- return True+ return self._handoff_keep(" Usage: /handoff <platform>",+ " Hands the current session off to that platform's home channel.",+ " The CLI session ends here; resume it later with /resume.")home = self._handoff_validate_target(platform_name)if home is None:return True@@ -1126,8 +1139,8 @@ class CLICommandsMixin:if session_title is None:return Trueif not self._session_db.request_handoff(self.session_id, platform_name):- _cp(" Session is already in flight for handoff. Wait for it to settle, then retry.")- return True+ return self._handoff_keep(+ " Session is already in flight for handoff. Wait for it to settle, then retry.")_cp(f" Queued handoff of '{session_title}' → {platform_name} (home: {home.name})."," Waiting for the gateway to pick it up...")return self._handoff_wait(platform_name, session_title)@@ -1138,18 +1151,15 @@ class CLICommandsMixin:try:from gateway.config import load_gateway_config, Platformexcept Exception as exc: # pragma: no cover — gateway pkg always shipped- _cp(f" Could not load gateway config: {exc}")- return None+ return _cp(f" Could not load gateway config: {exc}")try:platform = Platform(platform_name)except (ValueError, KeyError):- _cp(f" Unknown platform '{platform_name}'.")- return None+ return _cp(f" Unknown platform '{platform_name}'.")try:gw_config = load_gateway_config()except Exception as exc:- _cp(f" Could not load gateway config: {exc}")- return None+ return _cp(f" Could not load gateway config: {exc}")pcfg = gw_config.platforms.get(platform)if not pcfg or not pcfg.enabled:# Relay aliasing: a relay-fronted gateway has only a RELAY block yet /handoff discord@@ -1163,8 +1173,8 @@ class CLICommandsMixin:except Exception:relay_fronts = Falseif not relay_fronts:- _cp(f" Platform '{platform_name}' is not configured/enabled in the gateway.")- return None+ return _cp(f" Platform '{platform_name}' is not configured/enabled in the "+ "gateway.")home = gw_config.get_home_channel(platform)if not home or not home.chat_id:_cp(f" No home channel configured for {platform_name}.",@@ -1177,23 +1187,20 @@ class CLICommandsMixin:display title (None after printing why the handoff cannot start)."""# An in-flight agent run would race the gateway's switch_session and the synthetic turn.if getattr(self, "_agent_running", False):- _cp(" Agent is busy. Wait for the current turn to finish, then retry /handoff.")- return None+ return _cp(" Agent is busy. Wait for the current turn to finish, then retry /handoff.")if not self._session_db:with suppress(Exception):from hermes_state import SessionDBself._session_db = SessionDB()if not self._session_db:- _cp(_db_unavailable_line())- return None+ return _cp(_db_unavailable_line())# Ensure the session row exists (an empty session has flushed nothing yet): the gateway# needs a row to switch_session onto; set_session_title's INSERT OR IGNORE creates it.try:if not self._session_db.get_session(self.session_id):self._session_db.set_session_title(self.session_id, f"handoff-{self.session_id[:8]}")except Exception as exc:- _cp(f" Could not ensure session row in state.db: {exc}")- return None+ return _cp(f" Could not ensure session row in state.db: {exc}")session_title = ""with suppress(Exception):row = self._session_db.get_session(self.session_id)@@ -1234,9 +1241,8 @@ class CLICommandsMixin:return Falseif current == "failed":err = (state_row or {}).get("error") or "unknown error"- _cp(f" Handoff failed: {err}",- " Your CLI session is intact. Try /handoff again, or /resume on the platform manually.")- return True+ return self._handoff_keep(f" Handoff failed: {err}",+ " Your CLI session is intact. Try /handoff again, or /resume on the platform manually.")now = _time.time()if current == "pending":if now >= pending_deadline:@@ -1247,11 +1253,11 @@ class CLICommandsMixin:next_heartbeat = now + self._HANDOFF_HEARTBEAT_EVERYif running_deadline is not None and now >= running_deadline:# Do NOT fail the row: the gateway owns it (split-brain bug otherwise).- _cp(" The gateway is taking unusually long to finish the transfer.",+ return self._handoff_keep(+ " The gateway is taking unusually long to finish the transfer.",f" Check {platform_name} — the session may still arrive there."," This CLI is no longer waiting. Avoid continuing this session here;"," if nothing arrives, retry /handoff once the state settles.")- return True_time.sleep(0.5)try: # pending timed out: CAS-clear so the user can retry@@ -1263,9 +1269,9 @@ class CLICommandsMixin:self._session_db.fail_handoff(self.session_id, "timed out waiting for gateway")except Exception:pass- _cp(" Timed out waiting for the gateway. Is `hermes gateway` running?",+ return self._handoff_keep(+ " Timed out waiting for the gateway. Is `hermes gateway` running?"," Your CLI session is intact.")- return True# ---- /resume, /sessions, /branch ------------------------------------------------------def _handle_resume_command(self, cmd_original: str) -> None:@@ -2169,10 +2175,9 @@ class CLICommandsMixin:return _cp(f" Interval too small — minimum is {MIN_INTERVAL_SECONDS}s.")if not prompt.strip():return _cp(" Usage: /heartbeat every <interval> <prompt> — the prompt is required.")- try:- state = mgr.set(prompt, interval)- except ValueError as exc:- return _cp(f" Invalid heartbeat: {exc}")+ state = _attempt("Invalid heartbeat", ValueError, mgr.set, prompt, interval)+ if state is _FAILED:+ returnself._start_heartbeat_watchdog()_cp(f" ♥ Heartbeat set (every {format_interval(state.interval_seconds)}): {state.prompt}",_dim_line("Fires as a normal turn whenever the session is idle and the interval has "@@ -2293,10 +2298,8 @@ class CLICommandsMixin:except ValueError:return _cp(" /goal wait: <pid> must be an integer process id.")reason = wtokens[1].strip() if len(wtokens) > 1 else ""- try:- mgr.wait_on(pid, reason=reason)- except (RuntimeError, ValueError) as exc:- return _cp(f" /goal wait: {exc}")+ if _attempt("/goal wait", (RuntimeError, ValueError), mgr.wait_on, pid, reason=reason) is _FAILED:+ returnrtxt = f" ({reason})" if reason else ""_cp(f" ⏳ Goal parked on pid {pid}{rtxt}. Loop pauses until it exits.")@@ -2309,25 +2312,21 @@ class CLICommandsMixin:for line in mgr.render_gates().splitlines():_cp(f" {line}")elif gate_lower.startswith("add "):- try:- gate = mgr.add_gate(gate_arg[len("add"):].strip())- except (RuntimeError, ValueError) as exc:- return _cp(f" /goal gate add: {exc}")- _cp(f" ⚿ Gate added: $ {gate.command} "- f"({gate.max_retries} retries, {gate.timeout_seconds}s timeout). "- f"It must pass before the goal can complete.")+ gate = _attempt("/goal gate add", (RuntimeError, ValueError),+ mgr.add_gate, gate_arg[len("add"):].strip())+ if gate is not _FAILED:+ _cp(f" ⚿ Gate added: $ {gate.command} "+ f"({gate.max_retries} retries, {gate.timeout_seconds}s timeout). "+ f"It must pass before the goal can complete.")elif gate_lower.startswith("remove ") or gate_lower.startswith("rm "):- try:- removed = mgr.remove_gate(int(gate_arg.split(None, 1)[1].strip()))- except (RuntimeError, ValueError, IndexError) as exc:- return _cp(f" /goal gate remove: {exc}")- _cp(f" ✓ Gate removed: $ {removed}")+ removed = _attempt("/goal gate remove", (RuntimeError, ValueError, IndexError),+ lambda: mgr.remove_gate(int(gate_arg.split(None, 1)[1].strip())))+ if removed is not _FAILED:+ _cp(f" ✓ Gate removed: $ {removed}")elif gate_lower == "clear":- try:- prev = mgr.clear_gates()- except RuntimeError as exc:- return _cp(f" /goal gate clear: {exc}")- _cp(f" ✓ Cleared {_plural(prev, 'gate')}.")+ prev = _attempt("/goal gate clear", RuntimeError, mgr.clear_gates)+ if prev is not _FAILED:+ _cp(f" ✓ Cleared {_plural(prev, 'gate')}.")else:_cp(" Usage: /goal gate [list | add <command> | remove <N> | clear]")@@ -2336,10 +2335,10 @@ class CLICommandsMixin:lines become a completion contract, the remaining prose the headline. Kicks the loop off."""from hermes_cli.goals import parse_contractheadline, contract = parse_contract(arg)- try:- state = mgr.set(headline or arg, contract=contract if not contract.is_empty() else None)- except ValueError as exc:- return _cp(f" Invalid goal: {exc}")+ state = _attempt("Invalid goal", ValueError, mgr.set, headline or arg,+ contract=contract if not contract.is_empty() else None)+ if state is _FAILED:+ returnself._print_goal_set(state, "Completion contract:")against = " against the contract above" if state.has_contract() else ""_cp(_dim_line(f"After each turn, a judge model checks if the goal is done{against}. "@@ -2368,10 +2367,9 @@ class CLICommandsMixin:import logging as _logging_logging.getLogger(__name__).debug("goal draft failed: %s", exc)contract = None- try:- state = mgr.set(objective, contract=contract)- except ValueError as exc:- return _cp(f" Invalid goal: {exc}")+ state = _attempt("Invalid goal", ValueError, mgr.set, objective, contract=contract)+ if state is _FAILED:+ returnself._print_goal_set(state, "Drafted completion contract:")if state.has_contract():_cp(_dim_line("Tighten any field by re-setting the goal with inline lines "@@ -2422,24 +2420,19 @@ class CLICommandsMixin:idx = int(rest.split()[0])except ValueError:return _cp(" /subgoal remove: <n> must be an integer (1-based index).")- try:- removed = mgr.remove_subgoal(idx)- except (IndexError, RuntimeError) as exc:- return _cp(f" /subgoal remove: {exc}")- _cp(f" ✓ Removed subgoal {idx}: {removed}")+ removed = _attempt("/subgoal remove", (IndexError, RuntimeError), mgr.remove_subgoal, idx)+ if removed is not _FAILED:+ _cp(f" ✓ Removed subgoal {idx}: {removed}")elif verb == "clear":- try:- prev = mgr.clear_subgoals()- except RuntimeError as exc:- return _cp(f" /subgoal clear: {exc}")- _cp(f" ✓ Cleared {_plural(prev, 'subgoal')}." if prev else _dim_line('No subgoals to clear.'))+ prev = _attempt("/subgoal clear", RuntimeError, mgr.clear_subgoals)+ if prev is not _FAILED:+ _cp(f" ✓ Cleared {_plural(prev, 'subgoal')}." if prev+ else _dim_line('No subgoals to clear.'))else: # append the whole arg as a new subgoal- try:- text = mgr.add_subgoal(arg)- except (ValueError, RuntimeError) as exc:- return _cp(f" /subgoal: {exc}")- idx = len(mgr.state.subgoals) if mgr.state else 0- _cp(f" ✓ Added subgoal {idx}: {text}")+ text = _attempt("/subgoal", (ValueError, RuntimeError), mgr.add_subgoal, arg)+ if text is not _FAILED:+ idx = len(mgr.state.subgoals) if mgr.state else 0+ _cp(f" ✓ Added subgoal {idx}: {text}")# ---- /skin, /prompt -------------------------------------------------------------------def _handle_skin_command(self, cmd: str):@@ -2612,11 +2605,10 @@ class CLICommandsMixin:from hermes_cli.colors import Colors as _Colorsnew_state = _toggle_target(arg, current)if new_state == "status":- _cp(f" {_Colors.BOLD}{label}:{_Colors.RESET} {'ON' if current else 'OFF'}{status_line}")- return None+ state = "ON" if current else "OFF"+ return _cp(f" {_Colors.BOLD}{label}:{_Colors.RESET} {state}{status_line}")if new_state is None:- _cp(f" Usage: {usage}")- return None+ return _cp(f" Usage: {usage}")if _save(config_key, new_state):state = (f"{_Colors.GREEN}ON{_Colors.RESET}" if new_stateelse f"{_Colors.DIM}OFF{_Colors.RESET}")