The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(cli): split _chat_render_turn and _process_unregistered_slash into per-branch helpers
Tekniumf0d24b3c2e6b
diff --git a/cli.py b/cli.pyindex ff0e5be94e6..df27b397be8 100644--- a/cli.py+++ b/cli.py@@ -6283,182 +6283,151 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin, CLITuiMixexpansion -> unknown-command message. Always returns True unlessit re-dispatches through process_command."""- # Check for user-defined quick commands (bypass agent loop, no LLM call)base_cmd = cmd_lower.split()[0]skill_commands = _ensure_skill_commands()skill_bundles = get_skill_bundles()quick_commands = self.config.get("quick_commands", {})+ user_args = cmd_original[len(base_cmd):].strip()if base_cmd.lstrip("/") in quick_commands:- qcmd = quick_commands[base_cmd.lstrip("/")]- if qcmd.get("type") == "exec":- import subprocess- exec_cmd = qcmd.get("command", "")- if exec_cmd:- try:- # shell=True is intentional: quick_commands are user-defined- # shell snippets from config.yaml — not agent/LLM controlled.- # Sanitize env to prevent credential leakage —- # quick commands run in the CLI process which- # has all API keys in os.environ.- from tools.environments.local import build_subprocess_env- sanitized_env = build_subprocess_env()- from hermes_cli._subprocess_compat import windows_hide_flags- result = subprocess.run(- exec_cmd, shell=True, capture_output=True,- text=True, encoding="utf-8", errors="replace", timeout=30, env=sanitized_env,- # No console flash on Windows (#56747).- creationflags=windows_hide_flags(),- )- output = result.stdout.strip() or result.stderr.strip()- if output:- from agent.redact import redact_sensitive_text- output = redact_sensitive_text(output)- self._console_print(_rich_text_from_ansi(output))- else:- self._console_print("[dim]Command returned no output[/]")- except subprocess.TimeoutExpired:- self._console_print("[bold red]Quick command timed out (30s)[/]")- except Exception as e:- self._console_print(f"[bold red]Quick command error: {e}[/]")- else:- self._console_print(f"[bold red]Quick command '{base_cmd}' has no command defined[/]")- elif qcmd.get("type") == "alias":- target = qcmd.get("target", "").strip()- if target:- target = target if target.startswith("/") else f"/{target}"- user_args = cmd_original[len(base_cmd):].strip()- aliased_command = f"{target} {user_args}".strip()- return self.process_command(aliased_command)- else:- self._console_print(f"[bold red]Quick command '{base_cmd}' has no target defined[/]")- else:- self._console_print(f"[bold red]Quick command '{base_cmd}' has unsupported type (supported: 'exec', 'alias')[/]")- # Check for plugin-registered slash commands- elif base_cmd.lstrip("/") in _get_plugin_cmd_handler_names():- from hermes_cli.plugins import (- get_plugin_command_handler,- resolve_plugin_command_result,- )- plugin_handler = get_plugin_command_handler(base_cmd.lstrip("/"))- if plugin_handler:- user_args = cmd_original[len(base_cmd):].strip()- try:- result = resolve_plugin_command_result(- plugin_handler(user_args)- )- if result:- _cprint(str(result))- except Exception as e:- _cprint(f"\033[1;31mPlugin command error: {e}{_RST}")- # Skill bundles take precedence over individual skills — /<bundle>- # loads multiple skills at once. Rescans cheaply when files change.+ return self._run_quick_command(base_cmd, quick_commands[base_cmd.lstrip("/")], user_args)+ if base_cmd.lstrip("/") in _get_plugin_cmd_handler_names():+ self._run_plugin_slash_command(base_cmd, user_args)elif base_cmd in skill_bundles:- user_instruction = cmd_original[len(base_cmd):].strip()- bundle_result = build_bundle_invocation_message(- base_cmd, user_instruction, task_id=self.session_id- )- if bundle_result:- msg, loaded_names, missing = bundle_result- bundle_info = skill_bundles[base_cmd]- print(- f"\n⚡ Loading bundle: {bundle_info['name']} "- f"({len(loaded_names)} skills)"- )- if missing:- ChatConsole().print(- f"[yellow]Skipped missing skills: {', '.join(missing)}[/]"- )- if hasattr(self, '_pending_input'):- self._pending_input.put(msg)- else:- ChatConsole().print(- f"[bold red]Failed to load bundle for {base_cmd}[/]"- )- # Check for skill slash commands (/gif-search, /axolotl, etc.)+ self._run_skill_bundle_command(base_cmd, skill_bundles[base_cmd], user_args)elif base_cmd in skill_commands:- rest = cmd_original[len(base_cmd):].strip()- # Stacked slash-skill invocations: `/skill-a /skill-b do XYZ`- # loads every leading skill (up to 5), not just the first.- # Inspired by Claude Code v2.1.199.- from agent.skill_commands import (- build_stacked_skill_invocation_message,- split_stacked_skill_commands,- )- extra_keys, user_instruction = split_stacked_skill_commands(rest)- if extra_keys:- stacked_result = build_stacked_skill_invocation_message(- [base_cmd, *extra_keys],- user_instruction,- task_id=self.session_id,+ self._run_skill_slash_command(base_cmd, skill_commands[base_cmd], user_args)+ else:+ return self._expand_slash_prefix(cmd_original, cmd_lower, skill_commands, skill_bundles)+ return True++ def _run_quick_command(self, base_cmd: str, qcmd: dict, user_args: str) -> bool:+ """User-defined quick command (config.yaml): ``exec`` runs a shell snippet, ``alias`` re-dispatches."""+ qtype = qcmd.get("type")+ if qtype == "exec":+ import subprocess+ exec_cmd = qcmd.get("command", "")+ if not exec_cmd:+ self._console_print(f"[bold red]Quick command '{base_cmd}' has no command defined[/]")+ return True+ try:+ # shell=True is intentional: user-defined shell snippets from config.yaml,+ # never agent/LLM controlled. The env is sanitized because the CLI process+ # holds every API key in os.environ.+ from tools.environments.local import build_subprocess_env+ from hermes_cli._subprocess_compat import windows_hide_flags+ result = subprocess.run(+ exec_cmd, shell=True, capture_output=True,+ text=True, encoding="utf-8", errors="replace", timeout=30, env=build_subprocess_env(),+ # No console flash on Windows (#56747).+ creationflags=windows_hide_flags(),)- if stacked_result:- msg, loaded_names, missing = stacked_result- print(- f"\n⚡ Loading {len(loaded_names)} stacked skills: "- f"{', '.join(loaded_names)}"- )- if missing:- ChatConsole().print(- f"[yellow]Skipped missing skills: {', '.join(missing)}[/]"- )- if hasattr(self, '_pending_input'):- self._pending_input.put(msg)+ output = result.stdout.strip() or result.stderr.strip()+ if output:+ from agent.redact import redact_sensitive_text+ self._console_print(_rich_text_from_ansi(redact_sensitive_text(output)))else:- ChatConsole().print(- f"[bold red]Failed to load stacked skills for {base_cmd}[/]"- )- return True- user_instruction = rest- msg = build_skill_invocation_message(- base_cmd, user_instruction, task_id=self.session_id+ self._console_print("[dim]Command returned no output[/]")+ except subprocess.TimeoutExpired:+ self._console_print("[bold red]Quick command timed out (30s)[/]")+ except Exception as e:+ self._console_print(f"[bold red]Quick command error: {e}[/]")+ elif qtype == "alias":+ target = qcmd.get("target", "").strip()+ if target:+ target = target if target.startswith("/") else f"/{target}"+ return self.process_command(f"{target} {user_args}".strip())+ self._console_print(f"[bold red]Quick command '{base_cmd}' has no target defined[/]")+ else:+ self._console_print(f"[bold red]Quick command '{base_cmd}' has unsupported type (supported: 'exec', 'alias')[/]")+ return True++ def _run_plugin_slash_command(self, base_cmd: str, user_args: str) -> None:+ from hermes_cli.plugins import (+ get_plugin_command_handler,+ resolve_plugin_command_result,+ )+ plugin_handler = get_plugin_command_handler(base_cmd.lstrip("/"))+ if plugin_handler:+ try:+ result = resolve_plugin_command_result(plugin_handler(user_args))+ if result:+ _cprint(str(result))+ except Exception as e:+ _cprint(f"\033[1;31mPlugin command error: {e}{_RST}")++ def _queue_skill_message(self, msg) -> None:+ if hasattr(self, '_pending_input'):+ self._pending_input.put(msg)++ def _run_skill_bundle_command(self, base_cmd: str, bundle_info: dict, user_instruction: str) -> None:+ """``/<bundle>`` loads several skills at once (bundles win over same-named skills)."""+ bundle_result = build_bundle_invocation_message(+ base_cmd, user_instruction, task_id=self.session_id+ )+ if not bundle_result:+ ChatConsole().print(f"[bold red]Failed to load bundle for {base_cmd}[/]")+ return+ msg, loaded_names, missing = bundle_result+ print(f"\n⚡ Loading bundle: {bundle_info['name']} ({len(loaded_names)} skills)")+ if missing:+ ChatConsole().print(f"[yellow]Skipped missing skills: {', '.join(missing)}[/]")+ self._queue_skill_message(msg)++ def _run_skill_slash_command(self, base_cmd: str, skill_info: dict, rest: str) -> None:+ """``/<skill> ...``; stacked ``/skill-a /skill-b do XYZ`` loads every leading skill (up to 5)."""+ from agent.skill_commands import (+ build_stacked_skill_invocation_message,+ split_stacked_skill_commands,+ )+ extra_keys, user_instruction = split_stacked_skill_commands(rest)+ if extra_keys:+ stacked_result = build_stacked_skill_invocation_message(+ [base_cmd, *extra_keys],+ user_instruction,+ task_id=self.session_id,)- if msg:- skill_name = skill_commands[base_cmd]["name"]- print(f"\n⚡ Loading skill: {skill_name}")- if hasattr(self, '_pending_input'):- self._pending_input.put(msg)- else:- ChatConsole().print(f"[bold red]Failed to load skill for {base_cmd}[/]")+ if not stacked_result:+ ChatConsole().print(f"[bold red]Failed to load stacked skills for {base_cmd}[/]")+ return+ msg, loaded_names, missing = stacked_result+ print(f"\n⚡ Loading {len(loaded_names)} stacked skills: {', '.join(loaded_names)}")+ if missing:+ ChatConsole().print(f"[yellow]Skipped missing skills: {', '.join(missing)}[/]")+ self._queue_skill_message(msg)+ return+ msg = build_skill_invocation_message(base_cmd, rest, task_id=self.session_id)+ if msg:+ print(f"\n⚡ Loading skill: {skill_info['name']}")+ self._queue_skill_message(msg)else:- # Prefix matching: if input uniquely identifies one command, execute it.- # Matches against both built-in COMMANDS and installed skill commands so- # that execution-time resolution agrees with tab-completion.- from hermes_cli.commands import COMMANDS- typed_base = cmd_lower.split()[0]- all_known = set(COMMANDS) | set(skill_commands) | set(skill_bundles)- matches = [c for c in all_known if c.startswith(typed_base)]- if len(matches) > 1:- # Prefer an exact match (typed the full command name)- exact = [c for c in matches if c == typed_base]- if len(exact) == 1:- matches = exact- else:- # Prefer the unique shortest match:- # /qui → /quit (5) wins over /quint-pipeline (15)- min_len = min(len(c) for c in matches)- shortest = [c for c in matches if len(c) == min_len]- if len(shortest) == 1:- matches = shortest- if len(matches) == 1:- # Expand the prefix to the full command name, preserving arguments.- # Guard against redispatching the same token to avoid infinite- # recursion when the expanded name still doesn't hit an exact branch- # (e.g. /config with extra args that are not yet handled above).- full_name = matches[0]- if full_name == typed_base:- # Already an exact token — no expansion possible; fall through- _cprint(f"\033[1;31mUnknown command: {cmd_lower}{_RST}")- _cprint(f"{_DIM}{_ACCENT}Type /help for available commands{_RST}")- else:- remainder = cmd_original.strip()[len(typed_base):]- full_cmd = full_name + remainder- return self.process_command(full_cmd)- elif len(matches) > 1:- _cprint(f"{_ACCENT}Ambiguous command: {cmd_lower}{_RST}")- _cprint(f"{_DIM}Did you mean: {', '.join(sorted(matches))}?{_RST}")+ ChatConsole().print(f"[bold red]Failed to load skill for {base_cmd}[/]")++ def _expand_slash_prefix(self, cmd_original: str, cmd_lower: str, skill_commands, skill_bundles) -> bool:+ """Unique-prefix expansion against built-in COMMANDS + skill commands/bundles (agrees with tab-completion)."""+ from hermes_cli.commands import COMMANDS+ typed_base = cmd_lower.split()[0]+ all_known = set(COMMANDS) | set(skill_commands) | set(skill_bundles)+ matches = [c for c in all_known if c.startswith(typed_base)]+ if len(matches) > 1:+ exact = [c for c in matches if c == typed_base]+ if len(exact) == 1:+ matches = exactelse:- _cprint(f"\033[1;31mUnknown command: {cmd_lower}{_RST}")- _cprint(f"{_DIM}{_ACCENT}Type /help for available commands{_RST}")+ # Unique shortest match wins: /qui → /quit (5) over /quint-pipeline (15)+ min_len = min(len(c) for c in matches)+ shortest = [c for c in matches if len(c) == min_len]+ if len(shortest) == 1:+ matches = shortest+ if len(matches) == 1 and matches[0] != typed_base:+ # Expand to the full name, preserving arguments.+ return self.process_command(matches[0] + cmd_original.strip()[len(typed_base):])+ if len(matches) > 1:+ _cprint(f"{_ACCENT}Ambiguous command: {cmd_lower}{_RST}")+ _cprint(f"{_DIM}Did you mean: {', '.join(sorted(matches))}?{_RST}")+ else:+ # Exact token with no handler (never re-dispatch the same token: recursion), or no match.+ _cprint(f"\033[1;31mUnknown command: {cmd_lower}{_RST}")+ _cprint(f"{_DIM}{_ACCENT}Type /help for available commands{_RST}")return Truedef _owns_process_notification(self, event: dict) -> bool:@@ -7158,6 +7127,90 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin, CLITuiMixself._voice_continuous = False_cprint(f"\n{_DIM}Continuous voice mode stopped due to error.{_RST}")+ pending_message, _show_interrupt_marker = self._chat_resolve_interrupt(turn, agent_thread, interrupt_msg, response)++ response_previewed = turn.result.get("response_previewed", False) if turn.result else False++ self._chat_print_reasoning_box(turn)++ self._chat_print_response_panel(turn, response, response_previewed)++ # #60920: Print interruption marker with history suppressed so it+ # is never recorded in _OUTPUT_HISTORY. The marker was previously+ # appended to `response` which caused a duplicate on terminal redraw+ # when _replay_output_history replayed it. Printing it here with+ # _suspend_output_history preserves the user-visible indicator while+ # keeping _OUTPUT_HISTORY clean for replay.+ if _show_interrupt_marker:+ with _suspend_output_history():+ _cprint(f"\n{_DIM}── [Interrupted — processing new message] ──{_RST}")+++ # Focus view: dim recovery line reporting what was hidden this turn+ # (and how to reveal it). Printed after the response so the turn+ # reads prompt → answer → "⋯ N tool lines hidden". Display-only;+ # resets the counter for the next turn.+ try:+ self._emit_focus_recovery_line()+ except Exception:+ pass++ # Play terminal bell when agent finishes (if enabled).+ # Works over SSH — the bell propagates to the user's terminal.+ self._ring_bell(context="turn complete")++ # Notify when iteration budget was hit+ if turn.result and not turn.result.get("completed") and not turn.result.get("interrupted"):+ _api_calls = turn.result.get("api_calls", 0)+ if _api_calls >= getattr(self.agent, "max_iterations", 500):+ _max_iter = getattr(self.agent, "max_iterations", 500)+ _cprint(+ f"\n{_DIM}⚠ Iteration budget reached "+ f"({_api_calls}/{_max_iter}) — "+ f"response may be incomplete{_RST}"+ )++ # Speak response aloud if voice TTS is enabled+ # Skip batch TTS when streaming TTS already handled it+ if self._voice_tts and response and not turn.use_streaming_tts:+ self._voice_speak_response_async(response)+++ # Re-queue the interrupt message (and any that arrived while we were+ # processing the first) as the next prompt for process_loop.+ # Only reached when busy_input_mode == "interrupt" (the default).+ # In "queue" mode Enter routes directly to _pending_input so this+ # block is never hit.+ if pending_message and hasattr(self, '_pending_input'):+ all_parts = [pending_message]+ while not self._interrupt_queue.empty():+ try:+ extra = self._interrupt_queue.get_nowait()+ if extra:+ all_parts.append(extra)+ except queue.Empty:+ break+ combined = "\n".join(all_parts)+ n = len(all_parts)+ preview = combined[:50] + ("..." if len(combined) > 50 else "")+ if n > 1:+ print(f"\n⚡ Sending {n} messages after interrupt: '{preview}'")+ else:+ print(f"\n⚡ Sending after interrupt: '{preview}'")+ self._pending_input.put(combined)++ # If a /steer was left over (agent finished before another tool+ # batch could absorb it), deliver it as the next user turn.+ _leftover_steer = turn.result.get("pending_steer") if turn.result else None+ if _leftover_steer and hasattr(self, '_pending_input'):+ preview = _leftover_steer[:60] + ("..." if len(_leftover_steer) > 60 else "")+ print(f"\n⏩ Delivering leftover /steer as next turn: '{preview}'")+ self._pending_input.put(_leftover_steer)++ return response++ def _chat_resolve_interrupt(self, turn, agent_thread, interrupt_msg, response):+ """Decide the re-queued interrupt message and whether to print the interrupt marker; clears a stale agent interrupt flag."""# Handle interrupt - check if we were interruptedpending_message = None_show_interrupt_marker = False@@ -7200,9 +7253,10 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin, CLITuiMixself.agent.clear_interrupt()except Exception:pass+ return pending_message, _show_interrupt_marker- response_previewed = turn.result.get("response_previewed", False) if turn.result else False-+ def _chat_print_reasoning_box(self, turn):+ """Collapsed reasoning box when show_reasoning is on and streaming did not already show it this turn."""# Display reasoning (thinking) box if enabled and available.# Skip when streaming already showed reasoning live. Use the# turn-persistent flag (_reasoning_shown_this_turn) instead of@@ -7228,6 +7282,8 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin, CLITuiMixdisplay_reasoning = reasoning.strip()_cprint(f"\n{r_top}\n{_DIM}{display_reasoning}{_RST}\n{r_bot}")+ def _chat_print_response_panel(self, turn, response, response_previewed):+ """Response box: close the TTS-drawn box, print the post-stream transform, or render the Rich Panel; then the billing CTA."""if response and not response_previewed:# Use skin engine for label/color with fallbacktry:@@ -7303,80 +7359,6 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin, CLITuiMixexcept Exception:pass- # #60920: Print interruption marker with history suppressed so it- # is never recorded in _OUTPUT_HISTORY. The marker was previously- # appended to `response` which caused a duplicate on terminal redraw- # when _replay_output_history replayed it. Printing it here with- # _suspend_output_history preserves the user-visible indicator while- # keeping _OUTPUT_HISTORY clean for replay.- if _show_interrupt_marker:- with _suspend_output_history():- _cprint(f"\n{_DIM}── [Interrupted — processing new message] ──{_RST}")--- # Focus view: dim recovery line reporting what was hidden this turn- # (and how to reveal it). Printed after the response so the turn- # reads prompt → answer → "⋯ N tool lines hidden". Display-only;- # resets the counter for the next turn.- try:- self._emit_focus_recovery_line()- except Exception:- pass-- # Play terminal bell when agent finishes (if enabled).- # Works over SSH — the bell propagates to the user's terminal.- self._ring_bell(context="turn complete")-- # Notify when iteration budget was hit- if turn.result and not turn.result.get("completed") and not turn.result.get("interrupted"):- _api_calls = turn.result.get("api_calls", 0)- if _api_calls >= getattr(self.agent, "max_iterations", 500):- _max_iter = getattr(self.agent, "max_iterations", 500)- _cprint(- f"\n{_DIM}⚠ Iteration budget reached "- f"({_api_calls}/{_max_iter}) — "- f"response may be incomplete{_RST}"- )-- # Speak response aloud if voice TTS is enabled- # Skip batch TTS when streaming TTS already handled it- if self._voice_tts and response and not turn.use_streaming_tts:- self._voice_speak_response_async(response)--- # Re-queue the interrupt message (and any that arrived while we were- # processing the first) as the next prompt for process_loop.- # Only reached when busy_input_mode == "interrupt" (the default).- # In "queue" mode Enter routes directly to _pending_input so this- # block is never hit.- if pending_message and hasattr(self, '_pending_input'):- all_parts = [pending_message]- while not self._interrupt_queue.empty():- try:- extra = self._interrupt_queue.get_nowait()- if extra:- all_parts.append(extra)- except queue.Empty:- break- combined = "\n".join(all_parts)- n = len(all_parts)- preview = combined[:50] + ("..." if len(combined) > 50 else "")- if n > 1:- print(f"\n⚡ Sending {n} messages after interrupt: '{preview}'")- else:- print(f"\n⚡ Sending after interrupt: '{preview}'")- self._pending_input.put(combined)-- # If a /steer was left over (agent finished before another tool- # batch could absorb it), deliver it as the next user turn.- _leftover_steer = turn.result.get("pending_steer") if turn.result else None- if _leftover_steer and hasattr(self, '_pending_input'):- preview = _leftover_steer[:60] + ("..." if len(_leftover_steer) > 60 else "")- print(f"\n⏩ Delivering leftover /steer as next turn: '{preview}'")- self._pending_input.put(_leftover_steer)-- return response-def _tui_process_loop(self):while not self._should_exit:try: