The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(local_runtime): collapse swallow-and-default try/except ladders to contextlib.suppress; single struct reader in read_gguf_header
Teknium090fd9c6e9c2
diff --git a/hermes_cli/local_runtime/bootstrap.py b/hermes_cli/local_runtime/bootstrap.pyindex a08fbeb43cc..37d7b6472a4 100644--- a/hermes_cli/local_runtime/bootstrap.py+++ b/hermes_cli/local_runtime/bootstrap.py@@ -9,6 +9,7 @@ local_runtime disabled never pay the import.from __future__ import annotations+from contextlib import suppressimport loggingimport osimport signal@@ -33,14 +34,12 @@ def _detect_gpu_vendor() -> str | None:smi = _nvidia_smi_path()if smi is None:return None- try:+ with suppress(OSError, subprocess.TimeoutExpired):out = subprocess.run([smi, "--query-gpu=name", "--format=csv,noheader"],capture_output=True, text=True, timeout=10)if out.returncode == 0 and out.stdout.strip():return "nvidia " + out.stdout.strip().splitlines()[0]- except (OSError, subprocess.TimeoutExpired):- passreturn None@@ -91,13 +90,12 @@ def staged_model_ids() -> "list[str]":def _presets_stale() -> bool:"""True when a staged model has no section in the preset INI — it would autoload with stockfit instead of a policy decision."""- try:+ with suppress(Exception):from hermes_cli.local_runtime.presets import read_preset_decisionsknown = set(read_preset_decisions())return any(mid not in known for mid in staged_model_ids())- except Exception: # noqa: BLE001- return False+ return Falsedef _stop_state_server(state: dict) -> None:@@ -257,10 +255,8 @@ def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":except Exception:# start() can fail after the router process exists (health timeout): leaving it# running unsupervised strands its VRAM behind a port nothing will clean up.- try:+ with suppress(Exception):sup.stop()- except Exception: # noqa: BLE001 — cleanup is best-effort- passraise_SUPERVISOR = suplogger.info("managed llama-server up at %s (backend=%s tag=%s)",diff --git a/hermes_cli/local_runtime/capabilities.py b/hermes_cli/local_runtime/capabilities.pyindex 895db98ae66..349f922d917 100644--- a/hermes_cli/local_runtime/capabilities.py+++ b/hermes_cli/local_runtime/capabilities.py@@ -8,6 +8,7 @@ screenshot silently leaving the machine).from __future__ import annotations+from contextlib import suppressimport logginglogger = logging.getLogger(__name__)@@ -29,30 +30,26 @@ def is_managed_provider(provider: str, base_url: str = "") -> bool:return Trueif p != "custom" or not base_url:return False- try:+ with suppress(Exception):from hermes_cli.local_runtime.growth import is_managed_endpointreturn is_managed_endpoint(base_url)- except Exception: # noqa: BLE001- return False+ return Falsedef _props_modalities(model_id: str) -> "bool | None":"""Ask the running server whether this loaded child sees images. None when the server is down,the model isn't loaded, or the build doesn't report modalities."""- try:+ with suppress(Exception):from hermes_cli.local_runtime.endpoint import managed_get_json, managed_rootep = managed_root()if ep is None:return None- props = managed_get_json(*ep, f"/props?model={model_id}", timeout_s=3)- modalities = props.get("modalities")+ modalities = managed_get_json(*ep, f"/props?model={model_id}", timeout_s=3).get("modalities")if isinstance(modalities, dict) and "vision" in modalities:return bool(modalities["vision"])- return None- except Exception: # noqa: BLE001- return None+ return Nonedef managed_model_supports_vision(model_id: str) -> "bool | None":@@ -61,26 +58,19 @@ def managed_model_supports_vision(model_id: str) -> "bool | None":if not model_id:return None- # Only answer for models actually staged with us.- try:- from hermes_cli.local_runtime.bootstrap import staged_model_ids+ with suppress(Exception):+ from hermes_cli.local_runtime.bootstrap import assets_dir, staged_model_ids+ from hermes_cli.local_runtime.catalog import find_entry_for_model+ # Only answer for models actually staged with us.if model_id not in staged_model_ids():return None- except Exception: # noqa: BLE001- return None-- live = _props_modalities(model_id)- if live is not None:- return live-- # Staged but not loaded (or an older server build): the catalog knows whether this model- # ships a vision projector. Capability requires the projector to actually be on disk — a- # model downloaded before its mmproj (partial delete, old layout) genuinely cannot see.- try:- from hermes_cli.local_runtime.bootstrap import assets_dir- from hermes_cli.local_runtime.catalog import find_entry_for_model-+ live = _props_modalities(model_id)+ if live is not None:+ return live+ # Staged but not loaded (or an older server build): the catalog knows whether this model+ # ships a vision projector. Capability requires the projector to actually be on disk — a+ # model downloaded before its mmproj (partial delete, old layout) genuinely cannot see.hit = find_entry_for_model(model_id)if hit is None:return None@@ -88,5 +78,4 @@ def managed_model_supports_vision(model_id: str) -> "bool | None":if entry.mmproj is None:return Falsereturn (assets_dir() / entry.mmproj.local_name).exists()- except Exception: # noqa: BLE001- return None+ return Nonediff --git a/hermes_cli/local_runtime/endpoint.py b/hermes_cli/local_runtime/endpoint.pyindex 437422bfe80..ac1a2ffd81b 100644--- a/hermes_cli/local_runtime/endpoint.py+++ b/hermes_cli/local_runtime/endpoint.py@@ -7,6 +7,7 @@ its state file appears.from __future__ import annotations+from contextlib import suppressimport jsonimport loggingimport threading@@ -23,12 +24,11 @@ def _pid_alive(pid: int) -> bool:(optimistic). On Windows ``os.kill(pid, 0)`` TERMINATES the process — never use it as a probe."""if not pid or pid < 0:return False- try:+ with suppress(Exception):import psutil # type: ignorereturn psutil.pid_exists(pid)- except Exception: # noqa: BLE001- return True+ return Truedef _state_endpoint() -> dict | None:@@ -61,14 +61,13 @@ def managed_root() -> "tuple[str, str] | None":ownership-guarded reader, not a raw state-file read: on the shared stable port a foreigninstall's server answers /health for anyone, and a raw read would attach callers to someoneelse's server."""- try:+ with suppress(Exception):state = _state_endpoint()if state is None:return Nonebase = str(state.get("base_url", "")).rsplit("/v1", 1)[0]return (base, str(state.get("api_key", ""))) if base else None- except Exception: # noqa: BLE001- return None+ return Nonedef managed_get_json(base: str, api_key: str, route: str, timeout_s: float) -> object:@@ -144,12 +143,11 @@ def _boot_in_flight(config: dict | None) -> bool:"""True when the managed runtime is enabled and installed (a verified-manifest scan underruntimes_root(), NOT a bare ``server_binary()`` call — that needs an install_dir, and callingit bare once made this gate throw-and-return False forever, disabling the boot wait)."""- try:+ with suppress(Exception):config = _load_config_if_none(config)if not ((config or {}).get("local_runtime") or {}).get("enabled"):return Falsefrom hermes_cli.local_runtime.binaries import manifest_verified, runtimes_rootreturn any(manifest_verified(m) for m in runtimes_root().glob("*/*/manifest.json"))- except Exception: # noqa: BLE001- return False+ return Falsediff --git a/hermes_cli/local_runtime/gguf.py b/hermes_cli/local_runtime/gguf.pyindex ad753ceee09..4c56d44bb91 100644--- a/hermes_cli/local_runtime/gguf.py+++ b/hermes_cli/local_runtime/gguf.py@@ -152,40 +152,39 @@ class GGUFHeader:def read_gguf_header(path: str | Path) -> GGUFHeader:path = Path(path)+ def read(f, fmt: str):+ return struct.unpack(fmt, f.read(struct.calcsize(fmt)))+def read_str(f) -> str:- (n,) = struct.unpack("<Q", f.read(8))+ (n,) = read(f, "<Q")return f.read(n).decode("utf-8", errors="replace")def read_value(f, vtype: int):if vtype == _V_STRING:return read_str(f)if vtype == _V_ARRAY:- (etype,) = struct.unpack("<I", f.read(4))- (n,) = struct.unpack("<Q", f.read(8))+ etype, n = read(f, "<IQ")return [read_value(f, etype) for _ in range(n)]- fmt = _SCALAR_FMT[vtype]- (value,) = struct.unpack(fmt, f.read(struct.calcsize(fmt)))- return value+ return read(f, _SCALAR_FMT[vtype])[0]with open(path, "rb") as f:if f.read(4) != _GGUF_MAGIC:raise ValueError(f"not a GGUF file: {path}")- (version,) = struct.unpack("<I", f.read(4))- n_tensors, n_kv = struct.unpack("<QQ", f.read(16))+ version, n_tensors, n_kv = read(f, "<IQQ")metadata: dict = {}for _ in range(n_kv):key = read_str(f)- (vtype,) = struct.unpack("<I", f.read(4))+ (vtype,) = read(f, "<I")metadata[key] = read_value(f, vtype)tensor_bytes = 0embd_bytes = 0for _ in range(n_tensors):name = read_str(f)- (n_dims,) = struct.unpack("<I", f.read(4))- dims = struct.unpack(f"<{n_dims}Q", f.read(8 * n_dims))- (ttype,) = struct.unpack("<I", f.read(4))+ (n_dims,) = read(f, "<I")+ dims = read(f, f"<{n_dims}Q")+ (ttype,) = read(f, "<I")f.read(8) # offsetsize = _GGML_TYPE_SIZES.get(ttype)if size is None:diff --git a/hermes_cli/local_runtime/growth.py b/hermes_cli/local_runtime/growth.pyindex d5329b3b76d..fb8a4b165fe 100644--- a/hermes_cli/local_runtime/growth.py+++ b/hermes_cli/local_runtime/growth.py@@ -6,6 +6,7 @@ other-process supervisors keep their own policies.from __future__ import annotations+from contextlib import suppressimport jsonimport logging@@ -20,12 +21,11 @@ def window_overrides_path():def load_window_overrides() -> dict:"""model_id -> granted window (int). Empty on any read problem."""- try:+ with suppress(Exception):with open(window_overrides_path(), encoding="utf-8") as fh:data = json.load(fh)return {str(k): int(v) for k, v in data.items()}- except Exception: # noqa: BLE001- return {}+ return {}def _write_overrides(overrides: dict) -> None:@@ -50,16 +50,13 @@ def clear_window_override(model_id: str) -> None:def is_managed_endpoint(base_url: str) -> bool:"""True when base_url is the server this process's state file points at."""- try:+ with suppress(Exception):from hermes_cli.local_runtime.endpoint import _state_endpointstate = _state_endpoint()- if state is None:- return False- return (base_url or "").rstrip("/") == str(- state.get("base_url", "")).rstrip("/")- except Exception: # noqa: BLE001- return False+ return state is not None and (+ (base_url or "").rstrip("/") == str(state.get("base_url", "")).rstrip("/"))+ return Falsedef maybe_grow_window(model_id: str, *, base_url: str, session_tokens: int,diff --git a/hermes_cli/local_runtime/hardware.py b/hermes_cli/local_runtime/hardware.pyindex 0d3ca542c0c..a5fdfc65abe 100644--- a/hermes_cli/local_runtime/hardware.py+++ b/hermes_cli/local_runtime/hardware.py@@ -10,6 +10,7 @@ interactive environment.from __future__ import annotations+from contextlib import suppressimport loggingimport osimport re@@ -88,7 +89,7 @@ def _ram_bytes() -> tuple[int, int]:if total <= 0:return 0, 0avail = total // 2 # conservative fallback- try:+ with suppress(OSError, ValueError):out = _stdout("/usr/bin/vm_stat")page_m = re.search(r"page size of (\d+)", out)page = int(page_m.group(1)) if page_m else 16384@@ -99,17 +100,13 @@ def _ram_bytes() -> tuple[int, int]:if (m := re.search(rf"{key}:\s+(\d+)\.", out)))if pages > 0:avail = pages * page- except (OSError, ValueError):- passreturn total, avail# POSIXpage = int(_stdout("getconf", "PAGE_SIZE") or 4096)total = int(_stdout("getconf", "_PHYS_PAGES") or 0) * pageavail = total // 2 # conservative when _AVPHYS is unavailable- try:+ with suppress(OSError, ValueError):avail = int(_stdout("getconf", "_AVPHYS_PAGES") or 0) * page or avail- except (OSError, ValueError):- passreturn total, availexcept (OSError, ValueError):return 0, 0@@ -147,7 +144,7 @@ def _nvidia_vram() -> tuple[int, int] | None:exe = _nvidia_smi_path()if exe is None:return None- try:+ with suppress(OSError, ValueError, subprocess.TimeoutExpired):out = subprocess.run([exe, "--query-gpu=memory.total,memory.free","--format=csv,noheader,nounits"],@@ -156,8 +153,7 @@ def _nvidia_vram() -> tuple[int, int] | None:return Nonetotal_mib, free_mib = (int(x) for x in out.stdout.strip().splitlines()[0].split(","))return total_mib << 20, free_mib << 20- except (OSError, ValueError, subprocess.TimeoutExpired):- return None+ return Nonedef _cuda_driver_pool() -> "tuple[int, bool | None] | None":@@ -175,7 +171,7 @@ def _cuda_driver_pool() -> "tuple[int, bool | None] | None":continueelse:return None- try:+ with suppress(OSError, AttributeError):if cuda.cuInit(0) != 0:return Nonedev = ctypes.c_int()@@ -191,26 +187,20 @@ def _cuda_driver_pool() -> "tuple[int, bool | None] | None":ctypes.byref(attr), _CU_DEVICE_ATTRIBUTE_INTEGRATED, dev) == 0:integrated = bool(attr.value)return total.value, integrated- except (OSError, AttributeError):- return None+ return Nonedef _engine_device_pool() -> "tuple[int, bool | None] | None":"""(engine_total_bytes, None) from the installed runtime's own --list-devices, or None. Thefallback when the driver API is unreachable: asks the exact binary that will do theallocating. Carries no integrated verdict — callers must gate it."""- try:- from hermes_cli.local_runtime.binaries import (- installed_tags,- runtimes_root,- server_binary,- )+ with suppress(Exception): # a probe miss must never block budgeting+ from hermes_cli.local_runtime.binaries import installed_tags, runtimes_root, server_binarytags = installed_tags()if not tags:return None- tag_dir = runtimes_root() / tags[0]- backend_dirs = [d for d in tag_dir.iterdir() if d.is_dir()]+ backend_dirs = [d for d in (runtimes_root() / tags[0]).iterdir() if d.is_dir()]if not backend_dirs:return Noneexe = server_binary(backend_dirs[0])@@ -222,9 +212,7 @@ def _engine_device_pool() -> "tuple[int, bool | None] | None":m = _DEVICE_LINE_RE.search(line)if m:return int(m.group(1)) << 20, None- return None- except Exception: # noqa: BLE001 — a probe miss must never block budgeting- return None+ return Nonedef _device_pool_view() -> "tuple[int, bool | None] | None":diff --git a/hermes_cli/local_runtime/supervisor.py b/hermes_cli/local_runtime/supervisor.pyindex d70d8281c79..6e840a9f53c 100644--- a/hermes_cli/local_runtime/supervisor.py+++ b/hermes_cli/local_runtime/supervisor.py@@ -11,6 +11,7 @@ Windows via IPv6 fallback.from __future__ import annotations+from contextlib import suppressimport jsonimport loggingimport secrets@@ -45,10 +46,8 @@ def state_path() -> Path:def _quiet(fn) -> None:"""Best-effort call; a child that vanished mid-walk is not an error."""- try:+ with suppress(Exception):fn()- except Exception: # noqa: BLE001- passdef _free_port() -> int:@@ -79,12 +78,10 @@ def _stable_api_key() -> str:connection errors."""key_path = runtimes_root() / ".api_key"- try:+ with suppress(OSError):existing = key_path.read_text(encoding="utf-8").strip()if len(existing) >= 16:return existing- except OSError:- passkey = secrets.token_urlsafe(24)try:key_path.parent.mkdir(parents=True, exist_ok=True)@@ -179,10 +176,7 @@ class LlamaServerSupervisor:self.log_path.parent.mkdir(parents=True, exist_ok=True)if self._log_handle is not None:# The crash-restart loop calls _spawn repeatedly; each restart would leak one fd.- try:- self._log_handle.close()- except Exception: # noqa: BLE001 — best-effort- pass+ _quiet(self._log_handle.close)self._log_handle = open(self.log_path, "a", encoding="utf-8", errors="replace")self._log_handle.write(f"\n# spawn: {cmd}\n")self._log_handle.flush()@@ -220,12 +214,10 @@ class LlamaServerSupervisor:raise RuntimeError(f"llama-server exited rc={self.proc.returncode} during startup "f"(log: {self.log_path})")- try:+ with suppress(urllib.error.URLError, OSError, TimeoutError):with urllib.request.urlopen(self._url("/health"), timeout=3) as r:if r.status == 200:return- except (urllib.error.URLError, OSError, TimeoutError):- passtime.sleep(1)raise TimeoutError(f"llama-server not healthy after {timeout_s}s (log: {self.log_path})")@@ -272,12 +264,11 @@ class LlamaServerSupervisor:Windows does no cleanup) orphans them with the weights still resident. Enumerate childrenFIRST (the parent must be alive to walk them), terminate all, escalate to kill."""- try:+ children: list = []+ with suppress(Exception): # no psutil view; still stop the routerimport psutilchildren = psutil.Process(proc.pid).children(recursive=True)- except Exception: # noqa: BLE001 — no psutil view; still stop the router- children = []proc.terminate()for child in children:_quiet(child.terminate)