From ee2b165e78f98b6fc66852d1f045a9251680dbc2 Mon Sep 17 00:00:00 2001 From: ethernet Date: Fri, 18 Sep 2026 19:31:50 -0400 Subject: [PATCH] chore: drop merge-resolution notes, dead imports and a dead probe module - 15 `MERGE-CHECK:` conflict-resolution comments removed from prod code (two were TODOs already done: the utf-8-sig sessions.json read lives in session_persistence, the pm-aware cron script helpers in scheduler_script). - 49 imports the branch left unused (ruff F401, none present at the merge base, none inside PLUGIN-COMPAT blocks). update_cmd's frozen-surface re-exports are trimmed to the names tests/compat/old_updater_surface.json actually lists under hermes_cli.update_cmd; the rest resolve through hermes_cli.main.__getattr__. - tools/environments/local_gitbash_probe.py: nothing imported it once _find_bash delegated to pm.shell(). - Three try/except wrappers around calls that cannot raise (install_truststore, get_hermes_home, and a duplicated except clause in supermemory). --- agent/azure_identity_adapter.py | 3 - agent/model_metadata.py | 1 - agent/secret_sources/_cache.py | 2 +- agent/shell_hooks.py | 2 +- agent/trace_upload.py | 1 - cron/scheduler.py | 4 - gateway/platforms/base.py | 1 - gateway/run_voice.py | 1 - gateway/session.py | 6 - hermes_cli/backup.py | 4 - hermes_cli/banner.py | 1 - hermes_cli/cli_agent_setup_mixin.py | 2 +- hermes_cli/cli_commands_mixin.py | 2 - hermes_cli/main.py | 13 +-- hermes_cli/plugins_cmd.py | 2 +- hermes_cli/plugins_updates.py | 3 +- hermes_cli/update_cmd.py | 13 +-- hermes_cli/update_cmd_maint.py | 1 - hermes_cli/version_info.py | 11 +- hermes_cli/web_server.py | 3 +- hermes_startup_watchdog.py | 1 - plugins/disk-cleanup/__init__.py | 1 - plugins/google_meet/process_manager.py | 1 - plugins/google_meet/realtime/openai_client.py | 2 +- plugins/memory/mem0/_setup.py | 2 +- plugins/memory/supermemory/__init__.py | 15 +-- plugins/platforms/whatsapp/adapter.py | 1 - plugins/web/firecrawl/provider.py | 2 +- pm/cli.py | 1 - pm/packages.py | 1 - pm/update.py | 1 - scripts/bundles/bytecode.py | 2 - tests/tools/test_find_shell.py | 9 +- tools/computer_use/cua_backend.py | 6 +- tools/environments/base.py | 1 - tools/environments/local.py | 3 - tools/environments/local_gitbash_probe.py | 105 ------------------ tools/mcp_tool_sampling.py | 2 +- tools/registry.py | 1 - tools/skill_usage.py | 2 - tools/skills_hub.py | 1 - tools/skills_sync.py | 2 +- tools/tts_tool.py | 4 - tools/wake_word.py | 4 - 44 files changed, 29 insertions(+), 217 deletions(-) delete mode 100644 tools/environments/local_gitbash_probe.py diff --git a/agent/azure_identity_adapter.py b/agent/azure_identity_adapter.py index f88bc33e5e..42a4a4052a 100644 --- a/agent/azure_identity_adapter.py +++ b/agent/azure_identity_adapter.py @@ -28,9 +28,6 @@ SCOPE_AI_AZURE_DEFAULT = "https://ai.azure.com/.default" # Lazy SDK import — only loaded when the Entra path is actually used. # --------------------------------------------------------------------------- -# MERGE-CHECK: kept our pm feature name ("azure-identity" pip package) because -# _require_azure_identity routes through pm.ensure_import; upstream's -# "provider.azure_identity" was a key for their ensure() registry. _AZURE_IDENTITY_FEATURE = "azure-identity" _INSTALL_MSG = "The 'azure-identity' package is required for Azure AI Foundry Entra ID authentication. " _LAZY_INSTALL_HINT = ( diff --git a/agent/model_metadata.py b/agent/model_metadata.py index 39c21258c9..1efc77351e 100644 --- a/agent/model_metadata.py +++ b/agent/model_metadata.py @@ -10,7 +10,6 @@ import hashlib import ipaddress import json import logging -import os import re import time from pathlib import Path diff --git a/agent/secret_sources/_cache.py b/agent/secret_sources/_cache.py index 975cfb7a12..ae5003e39f 100644 --- a/agent/secret_sources/_cache.py +++ b/agent/secret_sources/_cache.py @@ -109,7 +109,7 @@ class DiskCache(Generic[K]): if ttl_seconds <= 0: return None try: - with open(self.path(home_path), "r", encoding="utf-8-sig") as f: # MERGE-CHECK: theirs' correct path + ours' utf-8-sig + with open(self.path(home_path), "r", encoding="utf-8-sig") as f: payload = json.load(f) except (OSError, json.JSONDecodeError): return None diff --git a/agent/shell_hooks.py b/agent/shell_hooks.py index e1f6b818ec..7c19e536b0 100644 --- a/agent/shell_hooks.py +++ b/agent/shell_hooks.py @@ -454,7 +454,7 @@ def allowlist_path() -> Path: def load_allowlist() -> Dict[str, Any]: """Return the parsed allowlist, or an empty skeleton if absent.""" try: - raw = json.loads(allowlist_path().read_text(encoding="utf-8-sig")) # MERGE-CHECK: kept ours (utf-8-sig BOM tolerance) + theirs (raw=None path) + raw = json.loads(allowlist_path().read_text(encoding="utf-8-sig")) except (json.JSONDecodeError, OSError): raw = None if not isinstance(raw, dict): diff --git a/agent/trace_upload.py b/agent/trace_upload.py index 241db54fcb..0e8e987a79 100644 --- a/agent/trace_upload.py +++ b/agent/trace_upload.py @@ -11,7 +11,6 @@ import json import logging import os import uuid -from contextlib import suppress from datetime import datetime, timezone from typing import Any, Dict, List, Optional, Tuple diff --git a/cron/scheduler.py b/cron/scheduler.py index dcb9b3609e..832c77facf 100644 --- a/cron/scheduler.py +++ b/cron/scheduler.py @@ -1152,10 +1152,6 @@ _FIRE_CLAIM_HEARTBEAT_GRACE_SECONDS = _RUN_CLAIM_HEARTBEAT_SECONDS * 3 _FIRE_CLAIM_MISS_CONFIRM_SECONDS = 1.0 -# MERGE-CHECK: our pm-aware cron-script helpers (_pm_runtime_venv_dir, _pm_store_python_exe, the -# pm-aware _windows_cron_python_invocation/_windows_cron_bootstrap_argv) lived in this upstream-deleted -# block. Upstream moved the script helpers to cron/scheduler_script.py WITHOUT pm awareness (pyvenv.cfg -# probing instead); that file is outside this merge's file list, so porting the pm logic is left to the parent. def _cron_cleanup_timeout_seconds() -> float: """Return the wall-clock bound for cron post-run cleanup.""" default = 10.0 diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py index b37fdf48de..45a709f46d 100644 --- a/gateway/platforms/base.py +++ b/gateway/platforms/base.py @@ -2769,7 +2769,6 @@ class BasePlatformAdapter(ABC): (Signal). Returns success when at least one image was delivered — the outcome the turn-level delivery tracker records; every override must return the same aggregate, or a media-only turn on that platform reports FAILURE (#106153).""" - from urllib.parse import unquote as _unquote delivered = False for image_url, alt_text in images: if human_delay > 0: diff --git a/gateway/run_voice.py b/gateway/run_voice.py index 84155705d4..d822c71dd2 100644 --- a/gateway/run_voice.py +++ b/gateway/run_voice.py @@ -10,7 +10,6 @@ import json import logging import os import re -import sys import time from contextlib import suppress from difflib import SequenceMatcher diff --git a/gateway/session.py b/gateway/session.py index 56a8b4ebb4..22e1133b03 100644 --- a/gateway/session.py +++ b/gateway/session.py @@ -846,12 +846,6 @@ class SessionStore( return True - # MERGE-CHECK: our pre-refactor SessionStore methods (_ensure_loaded.._heal_compression_tip_locked) - # were dropped - upstream decomposed them into session_persistence/session_recovery/session_lifecycle/ - # session_transcript mixins (imported above). ACTION FOR PARENT: our utf-8-sig sessions.json read fix - # (was in our _ensure_loaded_locked) needs porting to gateway/session_persistence.py (~line 286, - # encoding utf-8 -> utf-8-sig) - that file is outside this task's file list. - def has_any_sessions(self) -> bool: """Whether any session has ever been created. SQLite is the source of truth (ended sessions diff --git a/hermes_cli/backup.py b/hermes_cli/backup.py index 452c0f1d03..79b1aa3562 100644 --- a/hermes_cli/backup.py +++ b/hermes_cli/backup.py @@ -21,10 +21,6 @@ from hermes_constants import ( display_hermes_home, ) from hermes_state_dbfile import RETIRED_GENERATION_DIR_SUFFIX -from utils import ( - _preserve_file_mode, _preserve_file_owner, _restore_file_mode, _restore_file_owner, atomic_replace, - default_new_file_mode, -) from hermes_cli.archive_safe import normalize_archive_parts from hermes_cli.backup_sqlite import _close_quietly, _safe_copy_db diff --git a/hermes_cli/banner.py b/hermes_cli/banner.py index 5b64e4873c..0d71fc2203 100644 --- a/hermes_cli/banner.py +++ b/hermes_cli/banner.py @@ -9,7 +9,6 @@ import threading from pathlib import Path from hermes_cli import source_check # Historical updater import (tests/compat/old_updater_surface.json). In-tree callers use the owner. -from hermes_cli.source_check import _github_compare_behind from hermes_constants import get_hermes_home from typing import TYPE_CHECKING, Any, Dict, List, Optional diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.py index a02e73c430..c7d5f69683 100644 --- a/hermes_cli/cli_agent_setup_mixin.py +++ b/hermes_cli/cli_agent_setup_mixin.py @@ -605,7 +605,7 @@ 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 ChatConsole, _DIM, _RST, _accent_hex, _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 diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.py index f9a614f3b7..bfe3178f16 100644 --- a/hermes_cli/cli_commands_mixin.py +++ b/hermes_cli/cli_commands_mixin.py @@ -14,7 +14,6 @@ import json import os import shlex import subprocess -import sys import tempfile import threading import time @@ -995,7 +994,6 @@ class CLICommandsMixin: doesn't fire for image-only clipboard content (e.g., VSCode terminal, Windows Terminal with WSL2). """ - from cli import _DIM, _RST, _cprint from hermes_cli.clipboard import has_clipboard_image if not has_clipboard_image(): _cp(_dim_line('(._.) No image found in clipboard')) diff --git a/hermes_cli/main.py b/hermes_cli/main.py index 033b3d1435..e52a52dd58 100644 --- a/hermes_cli/main.py +++ b/hermes_cli/main.py @@ -3467,16 +3467,11 @@ def main(): except Exception: pass - # One TLS authority: trust the OS store process-wide before any outbound - # call resolves a CA bundle (see agent/ssl_verify.py). Covers the CLI - # entrypoint, which agent_init's own install_truststore() call does not - # reach when the CLI never constructs an AIAgent (subcommands, help). - try: - from agent.ssl_verify import install_truststore + # One TLS authority: trust the OS store before any outbound call resolves a + # CA bundle (agent/ssl_verify.py). Never raises; False just means OpenSSL's paths. + from agent.ssl_verify import install_truststore - install_truststore() - except Exception: - pass + install_truststore() # Sweep stale ``hermes.exe.old.*`` quarantine files from previous Windows # updates. No-op elsewhere. diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.py index 2830db5dde..d99e3c2fe4 100644 --- a/hermes_cli/plugins_cmd.py +++ b/hermes_cli/plugins_cmd.py @@ -1594,7 +1594,7 @@ def cmd_trust_update_url(name: str) -> None: plugins_dir = _plugins_dir() target = _require_installed_plugin(name, plugins_dir, console) - from hermes_cli.plugins_provenance import plugins_provenance, read_sidecar_rows + from hermes_cli.plugins_provenance import read_sidecar_rows rows = read_sidecar_rows(plugins_dir) row = rows.get(target.name) diff --git a/hermes_cli/plugins_updates.py b/hermes_cli/plugins_updates.py index 9bdfe84277..786b8f2a7d 100644 --- a/hermes_cli/plugins_updates.py +++ b/hermes_cli/plugins_updates.py @@ -18,7 +18,7 @@ import importlib.metadata import json import re import subprocess -from dataclasses import dataclass, field +from dataclasses import dataclass from pathlib import Path from typing import Any, Callable, Optional @@ -28,7 +28,6 @@ from hermes_cli.plugins_provenance import ( Provenance, ProvenanceClass, plugins_provenance, - read_sidecar_rows, ) _FETCH_TIMEOUT = 10.0 diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py index 5eb7e0d5be..241745ad78 100644 --- a/hermes_cli/update_cmd.py +++ b/hermes_cli/update_cmd.py @@ -8,7 +8,6 @@ main -> update_cmd -> update_cmd_*; ``_m()`` resolves ``hermes_cli.main`` at cal import logging from contextlib import suppress import os -import re import shlex import shutil # noqa: F401 (tests patch update_cmd.shutil.*; split modules resolve it here) import subprocess @@ -26,7 +25,6 @@ from hermes_cli.update_channel import adopt_retired_channel from pm.receipt import accept_worker_receipt as _accept_completion_pm_receipt from hermes_cli import update_receipt as _completion_receipt, update_cmd_config as _completion_config from hermes_cli._old_updater import stop_for_relaunch -from hermes_constants import venv_python_path # Re-exports: every split-module name stays reachable (and monkeypatchable) as update_cmd.. from hermes_cli.update_abort_recovery import ( # noqa: F401 @@ -77,16 +75,11 @@ from hermes_cli.update_cmd_stash import ( # noqa: F401 from hermes_cli.update_cmd_config import ( # noqa: F401 _LAST_SIBLING_SNAPSHOTS, _check_and_apply_config_migration, _migrate_sibling_profile_configs, _print_items, _reload_config_modules, _run_config_check_fresh, _run_migrate_config_fresh) -from hermes_cli.update_cmd_validation import ( # historical updater imports +from hermes_cli.update_cmd_validation import ( # noqa: F401 — frozen updater surface (tests/compat) _UPDATE_CRITICAL_MODULES, _critical_module_import_failures, _validate_critical_modules_import) -from hermes_cli.old_updater_deps import ( # historical updater imports only - _capture_active_lazy_features, _npm_lockfile_changed, _path_uid, - _rebuild_desktop_after_update, _refresh_active_lazy_features, - _refresh_active_memory_provider_dependencies, _update_node_dependencies, - _handoff_reapable_backend_pids, _ledger_manual_serve_holders, _ledger_reapable_backend_pids, - _leftover_pausable_gateway_pids, _orphaned_desktop_backend_pids, - _relaunch_stopped_serves, _stop_process_trees) +from hermes_cli.old_updater_deps import ( # noqa: F401 — frozen updater surface (tests/compat) + _path_uid, _rebuild_desktop_after_update, _update_node_dependencies) from hermes_cli.update_cmd_git import ( # noqa: F401 OFFICIAL_REPO_URL, OFFICIAL_REPO_URLS, SKIP_UPSTREAM_PROMPT_FILE, _ORPHAN_RESCUE_REFS_TO_KEEP, _ORPHAN_RESCUE_REF_MAX_AGE_DAYS, _add_upstream_remote, _assess_parked_branch_switch, diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.py index 92d23a5305..fc13d0f285 100644 --- a/hermes_cli/update_cmd_maint.py +++ b/hermes_cli/update_cmd_maint.py @@ -14,7 +14,6 @@ import sys import time as _time from pathlib import Path from typing import Optional -from hermes_constants import venv_python_path from hermes_cli.update_cmd_common import _best_effort diff --git a/hermes_cli/version_info.py b/hermes_cli/version_info.py index 7d029091e2..ef74e9473f 100644 --- a/hermes_cli/version_info.py +++ b/hermes_cli/version_info.py @@ -62,14 +62,11 @@ def _resolve_repo_dir() -> Path | None: repo_dir = Path(__file__).parent.parent.resolve() if (repo_dir / ".git").exists(): return repo_dir - try: - from hermes_constants import get_hermes_home + from hermes_constants import get_hermes_home - candidate = get_hermes_home() / "hermes-agent" - if (candidate / ".git").exists(): - return candidate - except Exception: - pass + candidate = get_hermes_home() / "hermes-agent" + if (candidate / ".git").exists(): + return candidate return None diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py index e49e4368bb..bde26f874b 100644 --- a/hermes_cli/web_server.py +++ b/hermes_cli/web_server.py @@ -47,8 +47,7 @@ except ImportError: from pm import ensure_import ensure_import("web") from fastapi import ( - FastAPI, File, Form, HTTPException, Query, Request, UploadFile, - WebSocket, WebSocketDisconnect, + FastAPI, HTTPException, Request, ) from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse diff --git a/hermes_startup_watchdog.py b/hermes_startup_watchdog.py index 06531eef31..e7f03dc483 100644 --- a/hermes_startup_watchdog.py +++ b/hermes_startup_watchdog.py @@ -32,7 +32,6 @@ import faulthandler import json import logging import os -import sys import threading import time from datetime import datetime, timezone diff --git a/plugins/disk-cleanup/__init__.py b/plugins/disk-cleanup/__init__.py index dacfc546b3..51a664fe76 100644 --- a/plugins/disk-cleanup/__init__.py +++ b/plugins/disk-cleanup/__init__.py @@ -7,7 +7,6 @@ from __future__ import annotations -import contextlib import logging import os import re diff --git a/plugins/google_meet/process_manager.py b/plugins/google_meet/process_manager.py index 354d2361ef..2398b9d04b 100644 --- a/plugins/google_meet/process_manager.py +++ b/plugins/google_meet/process_manager.py @@ -21,7 +21,6 @@ from typing import Any, Dict, Optional from hermes_constants import get_hermes_home -from plugins.google_meet._jsonfile import read_json from utils import atomic_json_write diff --git a/plugins/google_meet/realtime/openai_client.py b/plugins/google_meet/realtime/openai_client.py index f983e9f8e6..a4b9ed7ef5 100644 --- a/plugins/google_meet/realtime/openai_client.py +++ b/plugins/google_meet/realtime/openai_client.py @@ -150,7 +150,7 @@ class RealtimeSpeaker: if not self.queue_path.exists(): return [] out: list[dict] = [] - for line in self.queue_path.read_text(encoding="utf-8-sig").splitlines(): # MERGE-CHECK: ported our BOM-tolerant read fix onto upstream structure + for line in self.queue_path.read_text(encoding="utf-8-sig").splitlines(): with contextlib.suppress(ValueError): entry = json.loads(line) if line.strip() else None if isinstance(entry, dict): diff --git a/plugins/memory/mem0/_setup.py b/plugins/memory/mem0/_setup.py index cea3bce7e6..d12dfeaf72 100644 --- a/plugins/memory/mem0/_setup.py +++ b/plugins/memory/mem0/_setup.py @@ -18,7 +18,7 @@ from typing import Any from hermes_constants import get_hermes_home # noqa: F401 — patched by tests -from ._oss_providers import EMBEDDER_PROVIDERS, KNOWN_DIMS, LLM_PROVIDERS, SECTION_REGISTRIES, VECTOR_PROVIDERS, validate_oss_config, vector_default_config +from ._oss_providers import EMBEDDER_PROVIDERS, KNOWN_DIMS, LLM_PROVIDERS, VECTOR_PROVIDERS, validate_oss_config, vector_default_config _OLLAMA_URL = "http://localhost:11434" _PGVECTOR_CONTAINER, _PGVECTOR_IMAGE, _PGVECTOR_PASSWORD = "hermes-pgvector", "pgvector/pgvector:pg17", "hermes" diff --git a/plugins/memory/supermemory/__init__.py b/plugins/memory/supermemory/__init__.py index db985cf60c..2be3f40399 100644 --- a/plugins/memory/supermemory/__init__.py +++ b/plugins/memory/supermemory/__init__.py @@ -2,7 +2,7 @@ from __future__ import annotations -import importlib +import contextlib import json import logging import os @@ -178,18 +178,11 @@ def _memory_fields(item: Any, *keys: str) -> dict: class _SupermemoryClient: def __init__(self, api_key: str, timeout: float, container_tag: str, search_mode: str = "hybrid", base_url: str = ""): - # Lazy-install the supermemory SDK on demand. ensure() honors - # security.allow_lazy_installs (default true) and, on a sealed Docker - # venv, redirects the install to the durable target. On failure we - # fall through so the raw import below produces the canonical - # ImportError message. - try: + # Make the pinned extra importable; on failure fall through so the raw + # import below produces the canonical ImportError message. + with contextlib.suppress(Exception): from pm import ensure_import as _lazy_ensure _lazy_ensure("supermemory") - except ImportError: - pass - except Exception: - pass from supermemory import Supermemory self._api_key, self._container_tag, self._timeout = api_key, container_tag, timeout self._search_mode = search_mode if search_mode in _VALID_SEARCH_MODES else "hybrid" diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.py index 1f203ad42d..de313047cb 100644 --- a/plugins/platforms/whatsapp/adapter.py +++ b/plugins/platforms/whatsapp/adapter.py @@ -828,7 +828,6 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter): if file_size > _MAX_TEXT_INJECT_BYTES: print(f"[{self.name}] Skipping text injection for {doc_path} ({file_size} bytes > {_MAX_TEXT_INJECT_BYTES})", flush=True) continue - # MERGE-CHECK: our utf-8-sig read fix kept (BOM-tolerant document injection). content = p.read_text(encoding="utf-8-sig", errors="replace") parts = p.name.split("_", 2) # strip the doc__ prefix for display injection = f"[Content of {parts[2] if len(parts) >= 3 else p.name}]:\n{content}" diff --git a/plugins/web/firecrawl/provider.py b/plugins/web/firecrawl/provider.py index 56a844c120..1ec5c6dcda 100644 --- a/plugins/web/firecrawl/provider.py +++ b/plugins/web/firecrawl/provider.py @@ -12,7 +12,7 @@ from typing import Any, Dict, List, Optional import httpx -from plugins.web._common import BaseWebSearchProvider, keyless_extract, keyless_search, lazy_ensure, search_fail, search_ok, setup_schema +from plugins.web._common import BaseWebSearchProvider, keyless_extract, keyless_search, search_fail, search_ok, setup_schema from tools import managed_tool_gateway as _gateway from tools import tool_backend_helpers as _backend_helpers from tools.url_safety import is_safe_url diff --git a/pm/cli.py b/pm/cli.py index 948b768961..d97ed12c5c 100644 --- a/pm/cli.py +++ b/pm/cli.py @@ -4,7 +4,6 @@ from __future__ import annotations import argparse import json -import os import shutil import subprocess import sys diff --git a/pm/packages.py b/pm/packages.py index 31445d6deb..137605600f 100644 --- a/pm/packages.py +++ b/pm/packages.py @@ -5,7 +5,6 @@ from __future__ import annotations import logging import os -import platform import shutil import subprocess import sys diff --git a/pm/update.py b/pm/update.py index 1ef4cbd9ac..f653b75e8d 100644 --- a/pm/update.py +++ b/pm/update.py @@ -35,7 +35,6 @@ from dataclasses import dataclass, field from typing import Iterator, Optional from pm.network import retry_network -from pm.registry import get_package # The context holds no data outside a resolve/pin call, including failed calls. diff --git a/scripts/bundles/bytecode.py b/scripts/bundles/bytecode.py index d160a9bed0..0476c5fbde 100644 --- a/scripts/bundles/bytecode.py +++ b/scripts/bundles/bytecode.py @@ -28,8 +28,6 @@ the baked roots must have a pyc. Unparseable fixtures (deliberately invalid test data) are counted and skipped, not failed. """ -import os -import py_compile import subprocess from pathlib import Path diff --git a/tests/tools/test_find_shell.py b/tests/tools/test_find_shell.py index 69b723fdd2..9a0292d95d 100644 --- a/tests/tools/test_find_shell.py +++ b/tests/tools/test_find_shell.py @@ -91,24 +91,17 @@ class TestFindBashCollapsedToPmShell: def test_delegates_to_pm_shell(self, monkeypatch): """_find_bash returns whatever pm.shell() resolves (store bash or provisioned PATH).""" - import tools.environments.local as local_mod - from tools.environments import local_gitbash_probe as gitbash_probe - monkeypatch.setattr( "pm.shell.bash", lambda: r"C:\store\tools\git-x\usr\bin\bash.exe" ) assert _find_bash() == r"C:\store\tools\git-x\usr\bin\bash.exe" - gitbash_probe._bash_starts_cache.clear() def test_raises_when_pm_shell_finds_nothing(self, monkeypatch): """A store with no bash (and no PATH bash) surfaces a clear error pointing at `hermes pm install` instead of hunting locations.""" - import tools.environments.local as local_mod - from tools.environments import local_gitbash_probe as gitbash_probe - monkeypatch.setattr("pm.shell.bash", lambda: None) with pytest.raises(RuntimeError) as exc_info: - local_mod._find_bash() + _find_bash() assert "No shell found" in str(exc_info.value) assert "hermes pm install" in str(exc_info.value) diff --git a/tools/computer_use/cua_backend.py b/tools/computer_use/cua_backend.py index b16f17eb56..8e1ea252f3 100644 --- a/tools/computer_use/cua_backend.py +++ b/tools/computer_use/cua_backend.py @@ -9,13 +9,12 @@ Siblings: ``cua_backend_driver`` (binary/contract), ``cua_backend_capture`` + `` from __future__ import annotations import contextlib -import importlib import logging import os import subprocess import sys import uuid -from pathlib import PurePosixPath, PureWindowsPath +from pathlib import PureWindowsPath from typing import Any, Dict, List, Optional, Tuple from hermes_cli._subprocess_compat import windows_hide_flags @@ -23,8 +22,7 @@ from tools.computer_use.backend import ActionResult, ComputerUseBackend from tools.computer_use.cua_backend_capture import _CaptureMixin from tools.computer_use.cua_backend_daemon import _EmbeddedCuaDaemon from tools.computer_use.cua_backend_driver import ( - _CUA_DRIVER_CMD_ENV, cua_driver_binary_available, cua_driver_runtime_contract_status, - resolve_cua_driver_cmd) + _CUA_DRIVER_CMD_ENV, cua_driver_binary_available, cua_driver_runtime_contract_status) from tools.computer_use.cua_backend_input import _InputMixin from tools.computer_use.cua_backend_parse import _action_result_from from tools.computer_use.cua_backend_session import _AsyncBridge, _CuaDriverSession diff --git a/tools/environments/base.py b/tools/environments/base.py index 28ebbce1ee..8c349c43af 100644 --- a/tools/environments/base.py +++ b/tools/environments/base.py @@ -10,7 +10,6 @@ or a temp file (local). Cohesive pieces live in sibling modules (``base_output`` import json import logging import os -import re import shlex import threading import time diff --git a/tools/environments/local.py b/tools/environments/local.py index 4de96821ac..eba0f0378a 100644 --- a/tools/environments/local.py +++ b/tools/environments/local.py @@ -24,9 +24,6 @@ from tools.environments.local_env_policy import ( _ALWAYS_STRIP_KEYS, _HERMES_PROVIDER_ENV_BLOCKLIST, _HERMES_PROVIDER_ENV_FORCE_PREFIX, _is_hermes_internal_secret, _is_terminal_first_party_env, _matches_terminal_first_party_prefix, _plugin_terminal_env_strip_keys, strip_profile_gate_env) -from tools.environments.local_gitbash_probe import ( - _bash_probe_details_cache, _bash_starts, _git_bash_aslr_help, - _looks_like_msys_spawn_failure, _mandatory_aslr_enabled) from tools.environments.local_pythonpath import ( _build_hermes_repo_root_aliases, _strip_hermes_owned_pythonpath_and_runtime_markers) diff --git a/tools/environments/local_gitbash_probe.py b/tools/environments/local_gitbash_probe.py deleted file mode 100644 index ac7dabf27e..0000000000 --- a/tools/environments/local_gitbash_probe.py +++ /dev/null @@ -1,105 +0,0 @@ -"""Git Bash health probe + Mandatory-ASLR diagnostics (Windows), used by -``local._find_bash`` to pick a bash.exe that can actually launch MSYS children -and to build the targeted remediation when none can.""" - -import logging -import ntpath -import platform -import shutil -import subprocess - -from hermes_cli._subprocess_compat import windows_hide_flags - -_IS_WINDOWS = platform.system() == "Windows" - -# Same logger as the origin module so log routing is unchanged. -logger = logging.getLogger("tools.environments.local") - -_bash_starts_cache: dict[str, bool] = {} -_bash_probe_details_cache: dict[str, str] = {} -_mandatory_aslr_enabled_cache: "bool | None" = None - -# External ``true`` and ``cat`` are intentional: a builtin-only ``exit 0`` probe -# misses Git-for-Windows fork/spawn failures under system-wide Mandatory ASLR. -_BASH_EXTERNAL_PROGRAM_PROBE = "/usr/bin/true; /usr/bin/cat --version >/dev/null" - -_MSYS_SPAWN_FAILURE_MARKERS = ("dofork:", "child_copy:", "0xc0000142", "0xc0000005") - - -def _looks_like_msys_spawn_failure(details: str) -> bool: - """Match Git-for-Windows child-launch failures associated with ASLR.""" - lowered = details.lower() - return any(marker in lowered for marker in _MSYS_SPAWN_FAILURE_MARKERS) - - -def _mandatory_aslr_enabled() -> "bool | None": - """Return Windows' system-wide ForceRelocateImages state when available.""" - global _mandatory_aslr_enabled_cache - if _mandatory_aslr_enabled_cache is not None: - return _mandatory_aslr_enabled_cache - cmd = [shutil.which("powershell.exe") or "powershell.exe", "-NoProfile", "-NonInteractive", - "-Command", "(Get-ProcessMitigation -System).Aslr.ForceRelocateImages.ToString()"] - try: - result = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", - errors="replace", timeout=10, creationflags=windows_hide_flags(), stdin=subprocess.DEVNULL) - except Exception as exc: - logger.debug("Could not query Windows Mandatory ASLR state: %s", exc) - return None - if result.returncode != 0: - return None - value = (result.stdout or "").strip().upper() - _mandatory_aslr_enabled_cache = {"ON": True, "OFF": False, "NOTSET": False}.get(value) - return _mandatory_aslr_enabled_cache - - -def _git_root_from_bash(bash: str) -> str: - """Resolve Git's root from either /bin or /usr/bin bash.""" - bin_dir = ntpath.dirname(ntpath.normpath(bash)) - if ntpath.basename(bin_dir).lower() != "bin": - return ntpath.dirname(bin_dir) - parent = ntpath.dirname(bin_dir) - return ntpath.dirname(parent) if ntpath.basename(parent).lower() == "usr" else parent - - -def _git_bash_aslr_help(bash: str, details: str = "") -> str: - """Build the targeted per-program Mandatory-ASLR remediation.""" - escaped_root = _git_root_from_bash(bash).replace("'", "''") - detail_line = f"\nGit Bash probe output: {details[:500]}" if details else "" - return ( - f"Git Bash at {bash} cannot launch required MSYS child processes while " - "Windows Mandatory ASLR (ForceRelocateImages) is enabled, or its output " - f"matches that Git-for-Windows failure class.{detail_line}\n" - "Reinstalling Git will not change the Windows mitigation policy. Open " - "PowerShell as Administrator and run:\n" - f"$gitRoot = '{escaped_root}'\n" - 'Get-Item "$gitRoot\\bin\\bash.exe", "$gitRoot\\usr\\bin\\*.exe" ' - "-ErrorAction SilentlyContinue | ForEach-Object { " - "Set-ProcessMitigation -Name $_.FullName -Disable ForceRelocateImages }\n" - "Then restart Hermes. If the override is blocked or later re-applied, " - "ask your Windows administrator to allow this per-program exception." - ) - - -def _bash_starts(bash: str) -> bool: - """True if *bash* can launch external MSYS programs (cached per path). - ``--noprofile --norc`` so a broken login post-install (``Directory - \\drivers\\etc``) does not falsely condemn an otherwise usable bash.""" - if bash in _bash_starts_cache: - return _bash_starts_cache[bash] - try: - result = subprocess.run( - [bash, "--noprofile", "--norc", "-c", _BASH_EXTERNAL_PROGRAM_PROBE], - capture_output=True, text=True, encoding="utf-8", errors="replace", - timeout=15, creationflags=windows_hide_flags() if _IS_WINDOWS else 0, - stdin=subprocess.DEVNULL) # #78820: never hand the TUI gateway's stdin pipe to MSYS bash - ok = result.returncode == 0 - if not ok: - combined = f"{result.stdout or ''}{result.stderr or ''}".strip() - _bash_probe_details_cache[bash] = combined[:2000] - logger.debug("bash probe failed for %s: %s", bash, combined[:200]) - except Exception as exc: - _bash_probe_details_cache[bash] = str(exc)[:2000] - logger.debug("bash probe error for %s: %s", bash, exc) - ok = False - _bash_starts_cache[bash] = ok - return ok diff --git a/tools/mcp_tool_sampling.py b/tools/mcp_tool_sampling.py index 055031fcb3..b343dd44e8 100644 --- a/tools/mcp_tool_sampling.py +++ b/tools/mcp_tool_sampling.py @@ -12,7 +12,7 @@ from tools.mcp_tool_common import _MISSING, _exc_str, _safe_numeric, _sanitize_e from tools.mcp_tool_schema import _normalize_mcp_input_schema if TYPE_CHECKING: # annotations only; mcp_tool imports this module, so a real import is circular - from tools.mcp_tool import MCPServerTask + pass logger = logging.getLogger("tools.mcp_tool") diff --git a/tools/registry.py b/tools/registry.py index 5e211bc051..6c346caf51 100644 --- a/tools/registry.py +++ b/tools/registry.py @@ -70,7 +70,6 @@ def _module_registers_tools(module_path: Path) -> bool: Only module-body statements count, so helpers registering inside a function are skipped; a text prefilter avoids ``ast.parse`` for files lacking both words.""" try: - # MERGE-CHECK: our utf-8-sig read fix kept (BOM-tolerant; ours read tool modules this way) source = module_path.read_text(encoding="utf-8-sig") if "registry" not in source or "register" not in source: return False diff --git a/tools/skill_usage.py b/tools/skill_usage.py index 0ffa780042..33ce21a8ec 100644 --- a/tools/skill_usage.py +++ b/tools/skill_usage.py @@ -101,7 +101,6 @@ def _read_lines(path: Path, fail_log: str) -> List[str]: if not path.exists(): return [] try: - # MERGE-CHECK: our utf-8-sig read fix kept (BOM-tolerant; ours read metadata files this way) return [s for s in (line.strip() for line in path.read_text(encoding="utf-8-sig").splitlines()) if s] except OSError as e: logger.debug(fail_log, e) @@ -161,7 +160,6 @@ def _read_hub_installed_names() -> Set[str]: try: # errors="replace": hub descriptions can carry Windows-1252 high bytes; a strict read raises # UnicodeDecodeError (a ValueError, not caught below) and would 500 the whole /api/skills endpoint. - # MERGE-CHECK: utf-8-sig kept from ours (BOM-tolerant lock.json read). data = json.loads(lock_path.read_text(encoding="utf-8-sig", errors="replace")) installed = (data.get("installed") or {}) if isinstance(data, dict) else None if not isinstance(installed, dict): diff --git a/tools/skills_hub.py b/tools/skills_hub.py index d3b1d78857..ff3a7c9f25 100644 --- a/tools/skills_hub.py +++ b/tools/skills_hub.py @@ -208,7 +208,6 @@ def _read_json_if_fresh(path: Path, ttl: float) -> Optional[Any]: try: if time.time() - path.stat().st_mtime > ttl: return None - # MERGE-CHECK: our utf-8-sig read fix kept (BOM-tolerant; ours read cache files this way) return json.loads(path.read_text(encoding="utf-8-sig")) except (OSError, json.JSONDecodeError): return None diff --git a/tools/skills_sync.py b/tools/skills_sync.py index 89b0fd2cd9..68c8bfa3a6 100644 --- a/tools/skills_sync.py +++ b/tools/skills_sync.py @@ -24,7 +24,7 @@ for _stream in (sys.stdout, sys.stderr): _stream.reconfigure(encoding="utf-8", errors="replace") from hermes_constants import get_bundled_skills_dir, get_hermes_home, get_optional_skills_dir from agent.skill_utils import ESSENTIAL_SKILLS, is_excluded_skill_path -from tools.skill_usage import _read_skill_name, read_suppressed_names +from tools.skill_usage import _read_skill_name from tools.skills_sync_optional import ( _backfill_optional_provenance, _ignore_runtime_cache, _is_runtime_cache, _read_hub_install_paths, ) diff --git a/tools/tts_tool.py b/tools/tts_tool.py index 61e3eaa440..4f1b264395 100644 --- a/tools/tts_tool.py +++ b/tools/tts_tool.py @@ -49,8 +49,6 @@ from tools.tts_tool_plugins import ( from tools.tts_tool_openai import _generate_deepinfra_tts, _generate_openai_tts, _has_openai_audio_backend -# MERGE-CHECK: pm (our branch) replaces upstream's removed tools.lazy_deps; upstream lazy_deps -# feature ids mapped to the pm extras they install. _PM_FEATURE_ALIASES = {"tts.edge": "edge-tts", "tts.elevenlabs": "tts-premium", "tts.mistral": "mistral"} # --- Lazy SDK importers -- providers import only when used (headless boxes lack PortAudio etc.) --- @@ -62,8 +60,6 @@ def _sdk_importer(module: str, attr: Optional[str] = None, feature: Optional[str the raw import still raises cleanly. sounddevice also raises OSError without PortAudio.""" def _import(): if feature: - # MERGE-CHECK: upstream refactor wins; pm.ensure_import replaces the removed - # tools.lazy_deps feature-install (pm extras: tts.edge->edge-tts etc.) with contextlib.suppress(Exception): from pm import ensure_import as _pm_ensure _pm_ensure(_PM_FEATURE_ALIASES.get(feature, feature)) diff --git a/tools/wake_word.py b/tools/wake_word.py index 04c9bff3b3..59ee49b158 100644 --- a/tools/wake_word.py +++ b/tools/wake_word.py @@ -23,10 +23,6 @@ from typing import Any, Callable, Dict, Optional from tools.wake_word_engines import ( _Engine, - _OpenWakeWordEngine, - _PorcupineEngine, - _SherpaKwsEngine, - _sub, ) logger = logging.getLogger(__name__)