simplify(compat): hermes_cli small facades — drop 7 re-exports/aliases (+relay_runtime alias module), repoint 12 callers/tests
This commit is contained in:
@@ -452,7 +452,7 @@ def bounded_git_probe(argv: Sequence[str], *, timeout: float) -> str:
|
||||
``text`` with UTF-8 ``errors="replace"`` decoding, and the hidden-window ``creationflags`` on Windows
|
||||
only. On POSIX the probe is additionally placed in its own process group (``process_group=0``, Python
|
||||
≥3.11) so timeout cleanup can take down descendants — credential helpers, ``git-remote-https``, hook
|
||||
children — with the launcher instead of orphaning them (see :func:`_kill_git_process_tree`; port of
|
||||
children — with the launcher instead of orphaning them (see :func:`kill_process_tree`; port of
|
||||
openai/codex#36793). ``process_group`` only changes which group the child belongs to; it does not detach
|
||||
the terminal or alter the fast path.
|
||||
"""
|
||||
@@ -461,6 +461,3 @@ def bounded_git_probe(argv: Sequence[str], *, timeout: float) -> str:
|
||||
return ""
|
||||
return (result.stdout or "").strip()
|
||||
|
||||
|
||||
# Backward-compat alias — existing call sites/tests import the historical name.
|
||||
_kill_git_process_tree = kill_process_tree
|
||||
|
||||
@@ -23,7 +23,6 @@ from utils import (
|
||||
_preserve_file_mode, _preserve_file_owner, _restore_file_mode, _restore_file_owner, atomic_replace,
|
||||
)
|
||||
|
||||
# Private alias kept: claw.py and the backup tests import ``_format_size`` from here.
|
||||
from hermes_cli.sizefmt import format_bytes as _format_size
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
+2
-1
@@ -340,7 +340,8 @@ def _apply_migration(run_migrator: Callable[[bool], dict], opts: SimpleNamespace
|
||||
backup_archive: Optional[Path] = None
|
||||
if not opts.no_backup:
|
||||
try:
|
||||
from hermes_cli.backup import create_pre_migration_backup, _format_size
|
||||
from hermes_cli.backup import create_pre_migration_backup
|
||||
from hermes_cli.sizefmt import format_bytes as _format_size
|
||||
backup_archive = create_pre_migration_backup(hermes_home=opts.hermes_home)
|
||||
if backup_archive:
|
||||
print()
|
||||
|
||||
@@ -474,7 +474,8 @@ class CLIAgentSetupMixin:
|
||||
def _init_agent(self, *, model_override: str = None, runtime_override: dict = None, request_overrides: dict | None = None) -> bool:
|
||||
"""Build the agent on first use; when resuming, restore history from SQLite.
|
||||
Returns True on success."""
|
||||
from cli import AIAgent, ChatConsole, _cprint, _prepare_deferred_agent_startup, logger
|
||||
from cli import ChatConsole, _cprint, _prepare_deferred_agent_startup, logger
|
||||
from run_agent import AIAgent
|
||||
if self.agent is not None:
|
||||
return True
|
||||
|
||||
|
||||
@@ -398,9 +398,9 @@ def _refresh_tui_before_print(cli) -> None:
|
||||
def _print_lightpanda_engine_status() -> None:
|
||||
"""``/browser status`` line(s) about ``browser.engine: lightpanda`` — silent unless set;
|
||||
says whether it is in use or which higher-precedence setting shadows it."""
|
||||
if not _probe("tools.browser_tool", "_using_lightpanda_engine", False):
|
||||
if not _probe("tools.browser_tool_lightpanda_fallback", "_using_lightpanda_engine", False):
|
||||
return
|
||||
used, reason = _probe("tools.browser_tool", "lightpanda_engine_status", (None, None))
|
||||
used, reason = _probe("tools.browser_tool_lightpanda_fallback", "lightpanda_engine_status", (None, None))
|
||||
if reason is None:
|
||||
return
|
||||
if not used:
|
||||
@@ -521,7 +521,7 @@ def _browser_connect(cli, cdp_url: str) -> None:
|
||||
"debugging and retry /browser connect")
|
||||
os.environ["BROWSER_CDP_URL"] = found
|
||||
# Eagerly start the CDP supervisor so pending_dialogs + frame_tree show up in the next snapshot.
|
||||
_probe("tools.browser_tool", "_ensure_cdp_supervisor", None, "default")
|
||||
_probe("tools.browser_tool_cdp", "_ensure_cdp_supervisor", None, "default")
|
||||
_say_block("🌐 Browser connected to live Chromium-family browser via CDP", f" Endpoint: {found}")
|
||||
# Tell the model the CDP browser was made available on purpose.
|
||||
if hasattr(cli, '_pending_input'):
|
||||
@@ -543,7 +543,8 @@ def _browser_disconnect(cli) -> None:
|
||||
"(already using default mode)")
|
||||
os.environ.pop("BROWSER_CDP_URL", None)
|
||||
with suppress(Exception):
|
||||
from tools.browser_tool import cleanup_all_browsers, _stop_cdp_supervisor
|
||||
from tools.browser_tool import cleanup_all_browsers
|
||||
from tools.browser_tool_cdp import _stop_cdp_supervisor
|
||||
_stop_cdp_supervisor("default")
|
||||
cleanup_all_browsers()
|
||||
_say_block("🌐 Browser disconnected from live Chromium-family browser",
|
||||
@@ -590,7 +591,7 @@ def _browser_status() -> None:
|
||||
print(f"🌐 Browser: {provider.provider_name()} (cloud)")
|
||||
_print_lightpanda_engine_status()
|
||||
else:
|
||||
engine = _probe("tools.browser_tool", "_get_browser_engine", "auto")
|
||||
engine = _probe("tools.browser_tool_cloud", "_get_browser_engine", "auto")
|
||||
_pr(*_LOCAL_ENGINE_LINES.get(engine, _LOCAL_ENGINE_LINES["auto"]))
|
||||
if engine == "lightpanda":
|
||||
_print_lightpanda_engine_status()
|
||||
@@ -1708,7 +1709,7 @@ class CLICommandsMixin:
|
||||
print(f" Next run: {result['next_run_at']}")
|
||||
|
||||
def _cron_edit(self, subcommand: str, opts: dict) -> None:
|
||||
from cli import get_job
|
||||
from cron import get_job
|
||||
positionals = opts["positionals"]
|
||||
if not positionals:
|
||||
return print("(._.) Usage: /cron edit <job_id> "
|
||||
|
||||
@@ -76,7 +76,8 @@ class CLIInfoMixin:
|
||||
|
||||
def show_banner(self):
|
||||
"""Display the welcome banner in Claude Code style."""
|
||||
from cli import _build_compact_banner, build_welcome_banner, get_tool_definitions, logger
|
||||
from cli import _build_compact_banner, get_tool_definitions, logger
|
||||
from hermes_cli.banner import build_welcome_banner
|
||||
self.console.clear()
|
||||
ctx_len = None
|
||||
if hasattr(self, 'agent') and self.agent and hasattr(self.agent, 'context_compressor'):
|
||||
@@ -333,7 +334,8 @@ class CLIInfoMixin:
|
||||
|
||||
def show_tools(self):
|
||||
"""Display available tools with kawaii ASCII art."""
|
||||
from cli import get_tool_definitions, get_toolset_for_tool
|
||||
from cli import get_tool_definitions
|
||||
from model_tools import get_toolset_for_tool
|
||||
# Pre-assembly list: /tools is a discovery surface, so it must show the full catalog
|
||||
# including tools deferred behind the tool_search bridge (users verify MCP installs here).
|
||||
tools = get_tool_definitions(enabled_toolsets=self.enabled_toolsets, quiet_mode=True,
|
||||
@@ -367,7 +369,7 @@ class CLIInfoMixin:
|
||||
|
||||
def show_toolsets(self):
|
||||
"""Display available toolsets with kawaii ASCII art."""
|
||||
from cli import get_all_toolsets, get_toolset_info
|
||||
from toolsets import get_all_toolsets, get_toolset_info
|
||||
all_toolsets = get_all_toolsets()
|
||||
|
||||
print()
|
||||
@@ -475,7 +477,7 @@ class CLIInfoMixin:
|
||||
|
||||
def _show_gateway_status(self):
|
||||
"""Show status of the gateway and connected messaging platforms."""
|
||||
from cli import display_hermes_home
|
||||
from hermes_constants import display_hermes_home
|
||||
from gateway.config import load_gateway_config, Platform
|
||||
|
||||
print()
|
||||
|
||||
@@ -54,9 +54,8 @@ class CLILoopsMixin:
|
||||
_cprint(f" {_DIM}✓ UI redrawn{_RST}")
|
||||
|
||||
def _cmd_clear(self, cmd_original: str):
|
||||
from cli import (
|
||||
ChatConsole, _build_compact_banner, _clear_output_history, _cprint,
|
||||
build_welcome_banner, get_tool_definitions)
|
||||
from cli import ChatConsole, _build_compact_banner, _clear_output_history, _cprint, get_tool_definitions
|
||||
from hermes_cli.banner import build_welcome_banner
|
||||
if self._confirm_destructive_slash(
|
||||
"clear",
|
||||
"This clears the screen and starts a new session.\n"
|
||||
@@ -221,7 +220,7 @@ class CLILoopsMixin:
|
||||
self._reload_skills()
|
||||
|
||||
def _cmd_plugins(self, cmd_original: str):
|
||||
from cli import display_hermes_home
|
||||
from hermes_constants import display_hermes_home
|
||||
try:
|
||||
# Discover from disk (bundled + user) like `hermes plugins list`, so
|
||||
# installed-but-not-enabled plugins show up; the plugin manager only knows
|
||||
|
||||
@@ -24,7 +24,7 @@ def _user_turn_indices(history: list) -> list[int]:
|
||||
"""Indices of *real* user turns: excludes ephemeral scaffolding, display_kind timeline
|
||||
rows and compaction handoffs — the same predicate as resume turn counting."""
|
||||
from agent.context_compressor import user_originated_turn_view
|
||||
from run_agent import _is_ephemeral_scaffolding
|
||||
from agent.session_persistence import _is_ephemeral_scaffolding
|
||||
|
||||
return [
|
||||
i for i, m in enumerate(history)
|
||||
@@ -244,7 +244,7 @@ class CLISessionMixin:
|
||||
|
||||
def _show_session_status(self):
|
||||
"""Show gateway-style status for the current CLI session."""
|
||||
from cli import display_hermes_home
|
||||
from hermes_constants import display_hermes_home
|
||||
session_meta = {}
|
||||
if self._session_db:
|
||||
with contextlib.suppress(Exception):
|
||||
@@ -715,7 +715,7 @@ class CLISessionMixin:
|
||||
user_originated_turn_view)
|
||||
from agent.memory_manager import sanitize_context
|
||||
from agent.tool_dispatch_helpers import _is_multimodal_tool_result, _multimodal_text_summary
|
||||
from run_agent import _is_ephemeral_scaffolding
|
||||
from agent.session_persistence import _is_ephemeral_scaffolding
|
||||
|
||||
def _persistence_content(content: Any) -> Any:
|
||||
"""Project warm content exactly as the session DB flush does."""
|
||||
|
||||
@@ -12,11 +12,6 @@ sys.path.insert(0, str(PROJECT_ROOT))
|
||||
|
||||
from hermes_cli.colors import Colors, color
|
||||
|
||||
# Re-exported: ``tools/terminal_tool.py`` imports it from here to hard-block the same
|
||||
# gateway-lifecycle commands at execution time when ``_HERMES_GATEWAY=1``.
|
||||
from cron.lifecycle_guard import ( # noqa: F401
|
||||
contains_gateway_lifecycle_command as _contains_gateway_lifecycle_command)
|
||||
|
||||
|
||||
def _normalize_skills(single_skill=None, skills: Optional[Iterable[str]] = None) -> Optional[List[str]]:
|
||||
"""Deduped, stripped skill names; None when neither argument was given."""
|
||||
|
||||
@@ -27,7 +27,8 @@ def _system_package_install_cmd(pkg: str) -> str:
|
||||
|
||||
def _sqlite_upgrade_hint(install_method: str | None = None) -> str:
|
||||
"""Return an actionable SQLite upgrade hint for this install layout."""
|
||||
from hermes_cli.doctor import PROJECT_ROOT, detect_install_method
|
||||
from hermes_cli.doctor import PROJECT_ROOT
|
||||
from hermes_cli.config import detect_install_method
|
||||
method = install_method or detect_install_method(PROJECT_ROOT)
|
||||
cmd = recommended_update_command_for_method(method)
|
||||
action = cmd if is_nix_install_method(method) else { # nix: prose guidance, not a shell command
|
||||
@@ -81,7 +82,7 @@ def _read_journal_mode(db_path: Path) -> tuple[str | None, str | None]:
|
||||
|
||||
|
||||
def _format_db_size(db_path: Path) -> str:
|
||||
from hermes_cli.backup import _format_size # backup.py owns size formatting
|
||||
from hermes_cli.sizefmt import format_bytes as _format_size
|
||||
try:
|
||||
return _format_size(db_path.stat().st_size)
|
||||
except OSError:
|
||||
@@ -91,7 +92,7 @@ def _format_db_size(db_path: Path) -> str:
|
||||
def _report_database_journal_modes(hermes_home: Path | None = None, version_info: tuple[int, ...] | None = None) -> None:
|
||||
"""List each database's journal mode; warn on WAL under a vulnerable SQLite."""
|
||||
from hermes_cli.doctor import HERMES_HOME
|
||||
from hermes_state import _wal_reset_repair_hint, is_sqlite_wal_reset_vulnerable
|
||||
from hermes_state_wal import _wal_reset_repair_hint, is_sqlite_wal_reset_vulnerable
|
||||
vulnerable = is_sqlite_wal_reset_vulnerable(version_info)
|
||||
try:
|
||||
databases = _hermes_database_paths(hermes_home if hermes_home is not None else HERMES_HOME)
|
||||
@@ -261,7 +262,6 @@ def check_macos_tcc_grants() -> None:
|
||||
|
||||
See #86385.
|
||||
"""
|
||||
from hermes_cli.doctor import _desktop_app_bundle, _macos_desktop_dr
|
||||
app = _desktop_app_bundle() if sys.platform == "darwin" else None
|
||||
if app is None:
|
||||
return
|
||||
@@ -379,7 +379,7 @@ def _check_python_environment(should_fix: bool, f: Finding) -> None:
|
||||
# python-build-standalone can keep a vulnerable SQLite across upgrades).
|
||||
with warn_on_error("SQLite version probe failed: {e}", ""):
|
||||
import sqlite3
|
||||
from hermes_state import is_sqlite_wal_reset_vulnerable, sqlite_source_id
|
||||
from hermes_state_wal import is_sqlite_wal_reset_vulnerable, sqlite_source_id
|
||||
src = sqlite_source_id()
|
||||
# Warn-only: Hermes already refuses WAL on fresh DBs and runtime repair is best-effort.
|
||||
check_bool(not is_sqlite_wal_reset_vulnerable(), f"SQLite {sqlite3.sqlite_version}",
|
||||
|
||||
@@ -180,7 +180,7 @@ def _cleanup_worktree_workspace(
|
||||
it. The auto-generated ``wt/<task-id>`` branch is deleted with it; custom
|
||||
branches are kept. Best-effort."""
|
||||
try:
|
||||
from cli import _worktree_has_unpushed_commits, _worktree_is_dirty
|
||||
from hermes_cli.worktree_ops import _worktree_has_unpushed_commits, _worktree_is_dirty
|
||||
except Exception:
|
||||
return # CLI safety predicates unavailable — preserve
|
||||
try:
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import importlib.metadata # noqa: F401 — tests patch ``plugins_cmd.importlib.metadata.entry_points``
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
|
||||
@@ -13,9 +13,7 @@ import sys
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
|
||||
from hermes_cli.sessions_cmd_browse import ( # noqa: F401 (re-exports)
|
||||
_annotate_session_statuses, _relative_time, _session_browse_picker, _session_status_tag,
|
||||
)
|
||||
from hermes_cli.sessions_cmd_browse import _relative_time, _session_browse_picker
|
||||
|
||||
|
||||
def get_hermes_home():
|
||||
@@ -88,7 +86,8 @@ def _write_output(output, text, summary) -> None:
|
||||
# -- handlers that must run BEFORE SessionDB() is opened ----------------------
|
||||
|
||||
def _cmd_repair(args):
|
||||
from hermes_state import DEFAULT_DB_PATH as db_path, SessionDB, _db_opens_cleanly, repair_state_db_schema
|
||||
from hermes_state import DEFAULT_DB_PATH as db_path, SessionDB
|
||||
from hermes_state_repair import _db_opens_cleanly, repair_state_db_schema
|
||||
if not db_path.exists():
|
||||
print(f"No session database at {db_path} (nothing to repair).")
|
||||
return
|
||||
@@ -250,7 +249,7 @@ def _default_exclude(args):
|
||||
|
||||
|
||||
def _cmd_list(db, args):
|
||||
from hermes_state import workspace_key as _ws_key
|
||||
from hermes_state_sessions import workspace_key as _ws_key
|
||||
sessions = db.list_sessions_rich(source=args.source, exclude_sources=_default_exclude(args), limit=args.limit)
|
||||
|
||||
# Workspace filter: workspace key (git repo root, else cwd) — path substring or exact basename.
|
||||
|
||||
+14
-14
@@ -108,23 +108,23 @@ def _archive_untracked(tree: Path, untracked: List[str]) -> Optional[Path]:
|
||||
return None
|
||||
|
||||
|
||||
def _classify_tree(_cli, repo_root: str, entry: Path, merge_cache, remote_heads) -> tuple[str, str, List[str]]:
|
||||
def _classify_tree(_ops, repo_root: str, entry: Path, merge_cache, remote_heads) -> tuple[str, str, List[str]]:
|
||||
"""Return (verdict, reason, untracked) for one tree under ``.worktrees/``."""
|
||||
path = str(entry)
|
||||
if _KANBAN_RE.match(entry.name):
|
||||
return "keep", "kanban task tree (owned by kanban gc)", []
|
||||
if _cli._worktree_lock_is_live(repo_root, path, timeout=5) == "live":
|
||||
if _ops._worktree_lock_is_live(repo_root, path, timeout=5) == "live":
|
||||
return "keep", "in use by a running hermes session", []
|
||||
tracked_dirty, untracked = _dirty_split(path)
|
||||
if tracked_dirty:
|
||||
return "keep", "uncommitted tracked changes (real work)", []
|
||||
archive_note = f"{len(untracked)} untracked file(s) will be archived"
|
||||
if _cli._worktree_has_unpushed_commits(path, timeout=5) and not _cli._worktree_commits_all_merged_upstream(
|
||||
if _ops._worktree_has_unpushed_commits(path, timeout=5) and not _ops._worktree_commits_all_merged_upstream(
|
||||
path, timeout=30, cache=merge_cache, max_ahead=_MAX_CHERRY_AHEAD):
|
||||
# Pushed-branch tier: single-branch fetch refspecs (managed-install default) leave pushed
|
||||
# PR branches with no refs/remotes/* entry, so `git log HEAD --not --remotes` reads them
|
||||
# as unpushed forever. A head EXACTLY matching the remote branch has nothing origin lacks.
|
||||
if not _cli._worktree_branch_pushed_exact(path, remote_heads, timeout=10):
|
||||
if not _ops._worktree_branch_pushed_exact(path, remote_heads, timeout=10):
|
||||
return "keep", "unpushed commits not found upstream", []
|
||||
if untracked:
|
||||
return "reap-keep-branch", f"pushed to origin (open-PR lane); branch kept; {archive_note}", untracked
|
||||
@@ -136,18 +136,18 @@ def _classify_tree(_cli, repo_root: str, entry: Path, merge_cache, remote_heads)
|
||||
|
||||
def audit_worktrees(repo_root: str, *, with_sizes: bool = True) -> List[TreeRecord]:
|
||||
"""Classify every tree under ``.worktrees/`` without mutating anything."""
|
||||
import cli as _cli # lazy: cli.py is heavy
|
||||
from hermes_cli import worktree_ops as _ops
|
||||
worktrees_dir = Path(repo_root) / ".worktrees"
|
||||
if not worktrees_dir.exists():
|
||||
return []
|
||||
|
||||
if _cli._repo_is_shallow(repo_root):
|
||||
_cli._deepen_shallow_repo(repo_root)
|
||||
if _ops._repo_is_shallow(repo_root):
|
||||
_ops._deepen_shallow_repo(repo_root)
|
||||
|
||||
merge_cache = _cli._load_worktree_merge_cache()
|
||||
merge_cache = _ops._load_worktree_merge_cache()
|
||||
cache_size_before = len(merge_cache)
|
||||
# One ls-remote for the whole sweep; None (offline) degrades pushed-tier verdicts to keep.
|
||||
remote_heads = _cli._fetch_remote_branch_heads(repo_root)
|
||||
remote_heads = _ops._fetch_remote_branch_heads(repo_root)
|
||||
|
||||
now = time.time()
|
||||
records: List[TreeRecord] = []
|
||||
@@ -162,14 +162,14 @@ def audit_worktrees(repo_root: str, *, with_sizes: bool = True) -> List[TreeReco
|
||||
branch = _git(["branch", "--show-current"], cwd=str(entry), timeout=5).stdout.strip()
|
||||
except Exception:
|
||||
branch = ""
|
||||
verdict, reason, untracked = _classify_tree(_cli, repo_root, entry, merge_cache, remote_heads)
|
||||
verdict, reason, untracked = _classify_tree(_ops, repo_root, entry, merge_cache, remote_heads)
|
||||
records.append(TreeRecord(
|
||||
name=entry.name, path=str(entry), branch=branch,
|
||||
age_days=age_days, size_mb=_tree_size_mb(entry) if with_sizes else None,
|
||||
verdict=verdict, reason=reason, untracked=untracked))
|
||||
|
||||
if len(merge_cache) != cache_size_before:
|
||||
_cli._save_worktree_merge_cache(merge_cache)
|
||||
_ops._save_worktree_merge_cache(merge_cache)
|
||||
return records
|
||||
|
||||
|
||||
@@ -225,9 +225,9 @@ def reclaim_worktrees(
|
||||
def audit_branches(repo_root: str) -> List[BranchRecord]:
|
||||
"""Classify EVERY local branch: deletable when fully merged OR every commit is patch-equivalent
|
||||
upstream (``git cherry``) and not checked out. The gate is content reachability, not name."""
|
||||
import cli as _cli
|
||||
if _cli._repo_is_shallow(repo_root):
|
||||
_cli._deepen_shallow_repo(repo_root)
|
||||
from hermes_cli import worktree_ops as _ops
|
||||
if _ops._repo_is_shallow(repo_root):
|
||||
_ops._deepen_shallow_repo(repo_root)
|
||||
|
||||
def _lines(result) -> List[str]:
|
||||
return [b.strip() for b in result.stdout.splitlines() if b.strip()]
|
||||
|
||||
Reference in New Issue
Block a user