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).
This commit is contained in:
1 parent
44f891a820
commit
ee2b165e78
44 files changed
+29
-217
No files matched your search
@@ -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 = (
|
||||
|
||||
@@ -10,7 +10,6 @@ import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -10,7 +10,6 @@ import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from difflib import SequenceMatcher
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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'))
|
||||
|
||||
+4
-9
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.<name>.
|
||||
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,
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -32,7 +32,6 @@ import faulthandler
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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_<hex>_ prefix for display
|
||||
injection = f"[Content of {parts[2] if len(parts) >= 3 else p.name}]:\n{content}"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -4,7 +4,6 @@ from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
@@ -5,7 +5,6 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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 <root>/bin or <root>/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
|
||||
@@ -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")
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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__)
|
||||
|
||||
Reference in new issue
Block a user