cli_commands_session_tools.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. """Shared print/translate helpers + session-info slash handlers (``cli_commands_mixin`` split).
  2. Moved verbatim from ``hermes_cli/cli_commands_mixin.py`` (file-line ratchet #68779): the
  3. lazy-binding contract carries over unchanged — ``cli.py``-internal symbols are imported at
  4. call time via ``from cli import ...``, so patch seams on the ``cli`` facade still intercept.
  5. ``cli_commands_mixin`` re-imports every helper moved here, so existing ``from
  6. cli_commands_mixin import _t`` style imports keep working.
  7. """
  8. from __future__ import annotations
  9. import argparse
  10. import importlib
  11. import io
  12. import shlex
  13. from contextlib import redirect_stdout
  14. from io import StringIO
  15. from agent.i18n import t
  16. def _cp(*lines: str) -> None:
  17. """``_cprint`` each line (lazy import: cli.py imports this module)."""
  18. from cli import _cprint
  19. for line in lines:
  20. _cprint(line)
  21. def _pr(*lines: str) -> None:
  22. """print() each line."""
  23. for line in lines:
  24. print(line)
  25. def _save(key: str, value) -> bool:
  26. """cli.save_config_value, resolved lazily (cli.py imports this module)."""
  27. from cli import save_config_value
  28. return save_config_value(key, value)
  29. def _dim(text: str) -> str:
  30. """Wrap ``text`` in the dim ANSI escape."""
  31. from cli import _DIM, _RST
  32. return f"{_DIM}{text}{_RST}"
  33. def _dim_line(text: str) -> str:
  34. """Two-space indented dim line (the standard slash-command hint shape)."""
  35. return " " + _dim(text)
  36. def _accent(text: str) -> str:
  37. """Wrap ``text`` in the skin accent ANSI escape."""
  38. from cli import _ACCENT, _RST
  39. return f"{_ACCENT}{text}{_RST}"
  40. def _accent_line(text: str) -> str:
  41. """Two-space indented accent line (the standard slash-command headline shape)."""
  42. return f" {_accent(text)}"
  43. def _t(key: str, **kwargs) -> str:
  44. """Catalog text for this module: ``cli.commands.<key>`` in the active language."""
  45. return t(f"cli.commands.{key}", **kwargs)
  46. def _tn(key: str, count: int, **kwargs) -> str:
  47. """Plural-aware ``_t``: ``<key>_one`` when ``count == 1``, else ``<key>_other``."""
  48. return _t(f"{key}_{'one' if count == 1 else 'other'}", count=count, **kwargs)
  49. def _gt(key: str, **kwargs) -> str:
  50. """A ``gateway.<key>`` catalog entry the CLI shares verbatim with the messaging gateway."""
  51. return t(f"gateway.{key}", **kwargs)
  52. def _lines(text: str, pad: str = " ") -> list:
  53. """Each line of a (possibly multi-line) catalog value prefixed with ``pad`` (blank lines kept)."""
  54. return [f"{pad}{line}" if line else "" for line in text.splitlines()]
  55. def _rollback_kept(result: dict) -> None:
  56. """The kept / not-removed path lines of a restore result (in-process CLI and gateway client alike)."""
  57. from hermes_cli.cli_commands_mixin import _summarize_paths
  58. if skipped := result.get("skipped_user_edits"):
  59. _pr(*_lines(_gt("rollback.kept_user_edits", files=_summarize_paths(skipped))))
  60. if oversize := result.get("skipped_oversize"):
  61. print(f" {_gt('rollback.kept_oversize', files=_summarize_paths(oversize))}")
  62. if failed := result.get("failed_deletes"):
  63. print(f" {_gt('rollback.failed_deletes', files=_summarize_paths(failed))}")
  64. def _probe(module: str, name: str, default, *args):
  65. """``<module>.<name>(*args)`` or ``default`` when the import or the call fails (optional
  66. subsystems: browser backends, async delegations, wake word, ...)."""
  67. try:
  68. return getattr(importlib.import_module(module), name)(*args)
  69. except Exception:
  70. return default
  71. class CLICommandsSessionToolsMixin:
  72. """``/stop``, ``/agents``, ``/journey``, ``/paste``, ``/copy``, ``/image``, ``/tools``,
  73. ``/profile`` handlers (moved from ``CLICommandsMixin``)."""
  74. # ---- /stop, /agents -------------------------------------------------------------------
  75. def _handle_stop_command(self):
  76. """Handle /stop — kill all running background processes and background (async) delegations.
  77. Typed while a turn runs it stops that turn first, as Ctrl+C does (the registry's
  78. ``busy_policy="interrupt_then_dispatch"``; the input loop dispatches it inline, on the UI
  79. thread). The interrupt is immediate; the background cleanup then runs on a worker thread,
  80. since ``kill_all`` waits out each process's stop grace period and would freeze input.
  81. See #14602.
  82. """
  83. if not getattr(self, "_agent_running", False):
  84. return _stop_background_work()
  85. if getattr(self, "agent", None):
  86. from agent.interrupt_compat import request_hard_interrupt
  87. _cp(f" {t('cli.tui.interrupting')}")
  88. request_hard_interrupt(self.agent)
  89. from agent.memory_provider import spawn_context_thread
  90. spawn_context_thread(_stop_background_work, name="cli-stop").start()
  91. def _handle_agents_command(self):
  92. """Handle /agents — show background processes and agent status. On the gateway both run there:
  93. the session's ``process.list`` and its usage's running-subagent count (no per-delegation rows)."""
  94. from hermes_cli.gateway_tools import process_registry as _registry, process_view
  95. from tools.process_registry import format_uptime_short
  96. process_registry, view = _registry(), process_view()
  97. if view is not None:
  98. view.refresh(force=True)
  99. processes = process_registry.list_sessions()
  100. running = [p for p in processes if p.get("status") == "running"]
  101. finished = [p for p in processes if p.get("status") != "running"]
  102. _cp(f" {_t('agents.running_processes', count=len(running))}")
  103. for p in running:
  104. up = format_uptime_short(p.get("uptime_seconds", 0))
  105. _cp(f" {p.get('session_id', '?')} · {up} · {p.get('command', '')[:80]}")
  106. if finished:
  107. _cp(f" {_t('agents.recently_finished', count=len(finished))}")
  108. if view is None:
  109. _print_local_delegations()
  110. elif n_async := view.active_delegations():
  111. _cp(f" {_t('agents.background_delegations', count=n_async)}")
  112. agent_running = getattr(self, "_agent_running", False)
  113. _cp(f" {_t('agents.agent_running') if agent_running else _t('agents.agent_idle')}")
  114. # ---- /journey, /paste, /copy, /image --------------------------------------------------
  115. def _handle_journey_command(self, cmd_original: str) -> None:
  116. """Handle /journey — the learning timeline (see `hermes journey`). Read-only views render
  117. Rich color that patch_stdout would swallow, so capture with forced ANSI and re-emit via
  118. ``_cprint``; ``delete``/``edit`` are interactive and keep real stdio."""
  119. from hermes_cli.journey import register_cli
  120. parser = argparse.ArgumentParser(prog="/journey", add_help=False)
  121. register_cli(parser)
  122. try:
  123. args = parser.parse_args(shlex.split(cmd_original)[1:])
  124. except SystemExit:
  125. return
  126. try:
  127. if getattr(args, "journey_action", None) in ("delete", "edit"):
  128. args.func(args)
  129. return
  130. args.force_color = True
  131. buf = io.StringIO()
  132. with redirect_stdout(buf):
  133. args.func(args)
  134. _cp(buf.getvalue().rstrip("\n"))
  135. except Exception as exc:
  136. _cp(f" {_t('journey.failed', error=exc)}")
  137. def _handle_paste_command(self):
  138. """Handle /paste — explicitly check clipboard for an image.
  139. This is the reliable fallback for terminals where BracketedPaste
  140. doesn't fire for image-only clipboard content (e.g., VSCode terminal,
  141. Windows Terminal with WSL2).
  142. """
  143. from hermes_cli.clipboard import has_clipboard_image
  144. if not has_clipboard_image():
  145. _cp(_dim_line(_t("paste.no_image")))
  146. elif self._try_attach_clipboard_image():
  147. _cp(f" {_t('paste.attached', index=len(self._attached_images))}")
  148. else:
  149. _cp(_dim_line(_t("paste.extract_failed")))
  150. def _handle_copy_command(self, cmd_original: str) -> None:
  151. """Handle /copy [number] — copy assistant output to clipboard."""
  152. from cli import _assistant_copy_text
  153. arg = _command_arg(cmd_original)
  154. assistant = [m for m in self.conversation_history if m.get("role") == "assistant"]
  155. if not assistant:
  156. return _cp(f" {_t('copy.nothing_yet')}")
  157. if arg:
  158. try:
  159. idx = int(arg) - 1
  160. except ValueError:
  161. return _cp(f" {_t('copy.usage')}")
  162. if idx < 0 or idx >= len(assistant):
  163. return _cp(f" {_t('copy.invalid_number', max=len(assistant))}")
  164. else: # latest response that has copyable text
  165. idx = next((i for i in range(len(assistant) - 1, -1, -1)
  166. if _assistant_copy_text(assistant[i].get("content"))), -1)
  167. if idx < 0:
  168. return _cp(f" {_t('copy.nothing_in_responses')}")
  169. text = _assistant_copy_text(assistant[idx].get("content"))
  170. if not text:
  171. return _cp(f" {_t('copy.nothing_in_response')}")
  172. try:
  173. from hermes_cli.clipboard import is_remote_shell_session, write_clipboard_text
  174. # Over SSH native tools write the REMOTE clipboard; OSC 52 reaches the user's terminal.
  175. # Locally, OSC 52 is the fallback when native tools are unavailable/fail (SSH/tmux).
  176. if is_remote_shell_session() or not write_clipboard_text(text):
  177. # Fixes #31528.
  178. self._write_osc52_clipboard(text)
  179. _cp(f" {_t('copy.copied_osc52', index=idx + 1)}")
  180. else:
  181. _cp(f" {_t('copy.copied', index=idx + 1)}")
  182. except Exception as e:
  183. _cp(f" {_t('copy.failed', error=e)}")
  184. def _handle_image_command(self, cmd_original: str):
  185. """Handle /image <path> — attach a local image file for the next prompt."""
  186. from cli import _DIM, _IMAGE_EXTENSIONS, _RST, _cprint, _resolve_attachment_path, _split_path_input
  187. raw_args = (cmd_original.split(None, 1)[1].strip() if " " in cmd_original else "")
  188. if not raw_args:
  189. hint = "/path/to/image.png"
  190. _cprint(f" {_DIM}{_t('image.usage', example=hint)}{_RST}")
  191. return
  192. path_token, _remainder = _split_path_input(raw_args)
  193. image_path = _resolve_attachment_path(path_token)
  194. if image_path is None:
  195. return _cp(_dim_line(_t("image.not_found", path=path_token)))
  196. if image_path.suffix.lower() not in _IMAGE_EXTENSIONS:
  197. return _cp(_dim_line(_t("image.unsupported", name=image_path.name)))
  198. self._attached_images.append(image_path)
  199. _cp(f" {_t('image.attached', name=image_path.name)}")
  200. if _remainder:
  201. _cprint(f" {_DIM}{_t('image.now_type_prompt', text=_remainder)}{_RST}")
  202. # ---- /tools, /profile -----------------------------------------------------------------
  203. def _handle_tools_command(self, cmd: str):
  204. """Handle /tools [list|disable|enable]. Bare shows the tool list; ``list`` shows per-toolset
  205. status; disable/enable save to config and reset the session so the new tool set takes
  206. effect cleanly (no prompt-cache breakage mid-conversation)."""
  207. parts = _shlex_args(cmd)
  208. subcommand = parts[0] if parts else ""
  209. if subcommand not in {"list", "disable", "enable"}:
  210. return self.show_tools()
  211. if subcommand == "list":
  212. return self._run_tools_config(tools_action="list", platform="cli")
  213. names = parts[1:]
  214. if not names:
  215. return _pr(_t("tools.usage", subcommand=subcommand),
  216. f" {_t('tools.example_toolset', subcommand=subcommand)}",
  217. f" {_t('tools.example_mcp', subcommand=subcommand)}")
  218. # Typing the command is consent. Do NOT use input() — it hangs in prompt_toolkit's loop.
  219. _cp(_accent(_t("tools.disabling" if subcommand == "disable" else "tools.enabling",
  220. names=", ".join(names))))
  221. self._run_tools_config(tools_action=subcommand, names=names, platform="cli")
  222. from hermes_cli.tools_config import _get_platform_tools
  223. from hermes_cli.config import load_config
  224. self.enabled_toolsets = sorted(_get_platform_tools(load_config(), "cli")) # plain data for session.create
  225. self.new_session()
  226. _cp(_dim(_t("tools.session_reset")))
  227. def _run_tools_config(self, **ns) -> None:
  228. """Run ``tools_disable_enable_command``. Inside the interactive TUI its ANSI print() output
  229. is captured (isatty=True so colors still render) and re-emitted through _cprint so
  230. patch_stdout's StdoutProxy doesn't garble the escapes; standalone/tests call straight through."""
  231. from argparse import Namespace
  232. from hermes_cli.tools_config import tools_disable_enable_command
  233. if getattr(self, "_app", None) is None:
  234. return tools_disable_enable_command(Namespace(**ns))
  235. buf = _TTYBuf()
  236. with redirect_stdout(buf):
  237. tools_disable_enable_command(Namespace(**ns))
  238. _cp(*buf.getvalue().splitlines())
  239. def _handle_autoprune_command(self, cmd: str):
  240. """/autoprune [on|off|later|status] — the low-disk auto-prune decision."""
  241. from hermes_cli.slash_exec import CommandContext, execute_command
  242. _say_block(execute_command("autoprune", CommandContext(surface="cli", args=cmd.partition(" ")[2])).text)
  243. def _handle_profile_command(self):
  244. """Display active profile name and home directory."""
  245. from hermes_cli.slash_exec import CommandContext, execute_command
  246. reply = execute_command("profile", CommandContext(surface="cli"))
  247. _say_block(f" {_t('profile.profile', profile=reply.data['profile'])}",
  248. f" {_t('profile.home', home=reply.data['home'])}")
  249. def _stop_background_work() -> None:
  250. """``/stop``'s cleanup: kill the background processes, then interrupt the background (async)
  251. delegations. Mid-turn it runs on a worker thread, so it prints through ``_cprint``: a plain
  252. print() from off the input loop is buried by the prompt_toolkit redraw."""
  253. from hermes_cli.gateway_tools import process_registry as _registry, process_view
  254. process_registry, view = _registry(), process_view()
  255. if view is not None:
  256. view.refresh(force=True)
  257. running = [p for p in process_registry.list_sessions() if p.get("status") == "running"]
  258. # Background subagents live in their own registry, not the process registry.
  259. n_async = view.active_delegations() if view is not None else _probe("tools.async_delegation", "active_count", 0)
  260. if not running and not n_async:
  261. return _cp(f" {_t('stop.none_running')}")
  262. if running:
  263. _cp(f" {_t('stop.stopping', count=len(running))}")
  264. _cp(f" {_t('stop.stopped', count=process_registry.kill_all(source='cli.stop'))}")
  265. if n_async:
  266. if view is not None:
  267. interrupted = view.interrupt_delegations() # the gateway interrupts this session's own
  268. else:
  269. from tools.async_delegation import interrupt_all
  270. interrupted = interrupt_all(reason='/stop')
  271. _cp(f" {_t('stop.interrupted_delegations', count=interrupted)}")
  272. def print_session_diff(cli, result: dict, stat_only: bool) -> None:
  273. """Render a ``CheckpointManager.session_diff`` result (``/diff session``): this process's agent's,
  274. or the gateway session's ``rollback.session_diff`` (``diff_lines``: its uncut body's line count)."""
  275. if not result.get("success"):
  276. return print(f" {result.get('error') or _t('shared.could_not_generate_diff')}")
  277. stat, diff = result.get("stat", ""), result.get("diff", "")
  278. if result.get("empty") or (not stat and not diff):
  279. return print(f" {_t('diff.no_session_changes')}")
  280. if stat:
  281. cli._print_diff_text(f"\n{stat}")
  282. if (diff or result.get("diff_lines")) and not stat_only: # a body cut to nothing still names its lines
  283. cli._print_diff_body(diff, _t("diff.stat_hint_session"), total=int(result.get("diff_lines") or 0))
  284. def _print_local_delegations() -> None:
  285. """This process's background (async) delegations — delegate_task(background=true)."""
  286. delegations = _probe("tools.async_delegation", "list_async_delegations", [])
  287. if not delegations:
  288. return
  289. running_d = [d for d in delegations if d.get("status") in ("running", "stalling")]
  290. _cp(f" {_t('agents.background_delegations', count=len(running_d))}")
  291. for d in delegations:
  292. status = d.get("status", "?")
  293. line = f" {d.get('delegation_id', '?')} · {status} · {(d.get('goal') or '')[:60]}"
  294. # Live-status detail for in-flight delegations.
  295. # See #51690.
  296. if status == "stalling":
  297. quiet = d.get("stalled_after_quiet_seconds")
  298. if quiet is not None:
  299. line += _t("agents.no_progress", seconds=f"{quiet:.0f}")
  300. elif status == "running":
  301. quiet = d.get("seconds_since_progress")
  302. if quiet is not None and quiet >= 60:
  303. line += _t("agents.quiet", seconds=f"{quiet:.0f}")
  304. _cp(line)
  305. for i, child in enumerate(d.get("children_activity") or []):
  306. if not isinstance(child, dict):
  307. continue
  308. tool = child.get("current_tool")
  309. doing = _t("agents.in_tool", tool=tool) if tool else _t("agents.between_turns")
  310. part = " " + _t("agents.child_line", index=i + 1,
  311. api_calls=child.get("api_calls", "?"), doing=doing)
  312. idle = child.get("seconds_since_activity")
  313. if idle is not None:
  314. part += _t("agents.last_activity", seconds=f"{idle:.0f}")
  315. _cp(part)
  316. class _TTYBuf(StringIO):
  317. """StringIO that claims to be a TTY so ``hermes_cli.colors.color()`` still emits ANSI escapes."""
  318. def isatty(self) -> bool:
  319. return True
  320. def _say_block(*lines: str) -> None:
  321. """print() the lines framed by a blank line above and below (the /browser output style)."""
  322. _pr("", *lines, "")
  323. def _command_arg(cmd: str, *, lower: bool = False) -> str:
  324. """Everything after the slash-command word, stripped (optionally lowercased)."""
  325. parts = (cmd or "").strip().split(None, 1)
  326. arg = parts[1].strip() if len(parts) > 1 else ""
  327. return arg.lower() if lower else arg
  328. def _shlex_args(cmd: str) -> list:
  329. """Tokens after the command word; falls back to whitespace split on unbalanced quotes."""
  330. try:
  331. return shlex.split(cmd)[1:] if cmd else []
  332. except ValueError:
  333. return (cmd or "").split()[1:]