bang_shell.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. """``!<command>`` shell mode for the interactive CLI.
  2. ``!git status`` at the composer runs directly in the session's working directory. The model is
  3. never invoked — no user/assistant message or tool result enters history — so a bang command costs
  4. zero tokens and cannot perturb role alternation or the prompt cache. CLI-only by design:
  5. gateway/API/cron sessions have their own shells and no composer (:func:`bang_shell_enabled`).
  6. """
  7. from __future__ import annotations
  8. import os
  9. import subprocess
  10. from contextlib import suppress
  11. from typing import Optional
  12. USAGE_HINT = "Usage: !<command> — run a shell command without spending a model turn (e.g. !git status)"
  13. # Interactive convenience, not agent work: keep the ceiling well under the terminal tool's foreground
  14. # cap so an accidental `!sleep 999` cannot wedge the composer (the user can Ctrl+C anyway).
  15. DEFAULT_TIMEOUT = 120
  16. def is_bang_command(text: Optional[str]) -> bool:
  17. """True when *text* is a ``!`` shell-mode submission.
  18. Only a leading ``!`` (after surrounding whitespace) counts; ``fix the bug!`` is an ordinary
  19. prompt and must reach the agent untouched.
  20. """
  21. return isinstance(text, str) and text.strip().startswith("!")
  22. def parse_bang_command(text: str) -> str:
  23. """The shell command inside a bang submission (``""`` when bare).
  24. ``! ls -la`` -> ``ls -la``; ``!!`` -> ``!`` — a literal second bang belongs to the user's shell
  25. (history expansion), not to Hermes.
  26. """
  27. return text.strip()[1:].strip() if is_bang_command(text) else ""
  28. def bang_shell_enabled() -> bool:
  29. """True only for interactive local CLI sessions.
  30. Gateway, API, and cron sessions never reach the composer and their users already have a shell;
  31. running arbitrary commands for them would be a remote-execution surface with no approving human
  32. at the keyboard.
  33. """
  34. try:
  35. from utils import env_var_enabled
  36. except Exception: # pragma: no cover - utils is always importable in-tree
  37. def env_var_enabled(name, default=""): # type: ignore[misc]
  38. return str(os.getenv(name, default)).strip().lower() in {"1", "true", "yes", "on"}
  39. return not (env_var_enabled("HERMES_GATEWAY_SESSION") or env_var_enabled("HERMES_CRON_SESSION")
  40. or (os.getenv("HERMES_SESSION_PLATFORM") or "").strip())
  41. def resolve_bang_cwd(session_key: Optional[str] = None) -> Optional[str]:
  42. """The directory a bang command should run in.
  43. Mirrors the terminal tool's order so ``!pwd`` matches the agent's own commands: the session's
  44. recorded ``cd`` state first, then the configured ``TERMINAL_CWD``/backend default.
  45. """
  46. try:
  47. from tools.terminal_tool import _get_env_config, get_session_cwd
  48. return get_session_cwd(session_key) or (_get_env_config() or {}).get("cwd") or None
  49. except Exception:
  50. return None
  51. def check_bang_approval(command: str) -> dict:
  52. """Run *command* through the terminal tool's approval gate.
  53. Reuses ``tools.terminal_tool._check_all_guards`` — exactly what ``terminal_tool()`` calls — so the
  54. hardline blocklist, user deny rules and the dangerous-command prompt all apply
  55. to user-typed bang commands too. Returns the gate's ``{"approved": bool, "message": ...}``;
  56. falls back to *approved* only when the gate itself cannot be imported (a broken install, not a
  57. policy decision).
  58. """
  59. try:
  60. from tools.terminal_tool import _check_all_guards
  61. except Exception:
  62. return {"approved": True, "message": None}
  63. # Bang commands always run locally in the CLI process, never inside a remote/sandbox backend.
  64. return _check_all_guards(command, "local", has_host_access=False)
  65. def _bang_env() -> dict:
  66. """Environment for a bang command with Hermes-managed secrets filtered.
  67. The CLI process holds every provider API key; a user-typed command may still run a third-party
  68. script, so reuse the sanitizer ``quick_commands`` and the local terminal backend use. If that
  69. boundary is unavailable, let the launch fail rather than passing the CLI's full environment.
  70. """
  71. from tools.environments.local import build_subprocess_env
  72. return build_subprocess_env()
  73. def run_bang_command(command: str, *, cwd: Optional[str] = None, timeout: int = DEFAULT_TIMEOUT, writer=None) -> int:
  74. """Execute *command*, streaming merged stdout/stderr through *writer* (default ``print``); return the exit code.
  75. Output exists only on the user's terminal — nothing is returned for insertion into history.
  76. """
  77. emit = writer or (lambda line: print(line, end="" if line.endswith("\n") else "\n"))
  78. run_cwd = os.path.expanduser(cwd) if cwd else None
  79. if run_cwd and not os.path.isdir(run_cwd):
  80. run_cwd = None
  81. try:
  82. from hermes_cli._subprocess_compat import windows_hide_flags
  83. creationflags = windows_hide_flags()
  84. except Exception:
  85. creationflags = 0
  86. try:
  87. # shell=True is intentional (matches quick_commands): the human typed this, not the model.
  88. proc = subprocess.Popen(
  89. command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
  90. encoding="utf-8", errors="replace", cwd=run_cwd, env=_bang_env(),
  91. creationflags=creationflags)
  92. except Exception as exc:
  93. emit(f"!: failed to run command: {exc}")
  94. return 127
  95. try:
  96. if proc.stdout is not None:
  97. for line in proc.stdout:
  98. emit(line.rstrip("\n"))
  99. proc.wait(timeout=timeout)
  100. except subprocess.TimeoutExpired:
  101. proc.kill()
  102. emit(f"!: command timed out after {timeout}s")
  103. return 124
  104. except KeyboardInterrupt:
  105. # Ctrl+C interrupts the command, not the Hermes session.
  106. proc.kill()
  107. emit("!: interrupted")
  108. return 130
  109. finally:
  110. if proc.stdout is not None:
  111. with suppress(Exception):
  112. proc.stdout.close()
  113. return int(proc.returncode or 0)