The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(local-runtime): budget the engine the shared server runs, in the caller's profile
teknium123c1e6bc6db5
diff --git a/hermes_cli/local_runtime/bootstrap.py b/hermes_cli/local_runtime/bootstrap.pyindex dd4ae9f5da5..41ff89e3944 100644--- a/hermes_cli/local_runtime/bootstrap.py+++ b/hermes_cli/local_runtime/bootstrap.py@@ -20,6 +20,9 @@ from hermes_cli.local_runtime.gguf import SPLIT_PART_RE, model_id_from_stemlogger = logging.getLogger(__name__)_SUPERVISOR = None # process-wide singleton; one router per Hermes process+# The engine that singleton runs (or is booting). Budgets price ITS devices: the server is shared by+# every profile this process hosts, so another profile's ``local_runtime.backend`` must not resize it.+_SERVING_ENGINE = Nonedef _detect_gpu_vendor() -> str | None:@@ -378,7 +381,7 @@ def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":"""Idempotent boot of the managed runtime. Returns the supervisor (or None whendisabled/unavailable). Never raises into a session start — failures log and return None; chatfalls back to configured providers."""- global _SUPERVISOR+ global _SUPERVISOR, _SERVING_ENGINEsection = (config or {}).get("local_runtime") or {}if not force and not section.get("enabled"):return None@@ -424,6 +427,7 @@ def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":if engine is None:logger.info("local runtime enabled but no PM engine installed; use the Local Models pane")return None+ _SERVING_ENGINE = enginemdir = models_dir()mdir.mkdir(parents=True, exist_ok=True)@@ -446,15 +450,17 @@ def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":_start_idle_sweeper(sup)return supexcept Exception as exc: # noqa: BLE001 — never break session start+ _SERVING_ENGINE = Nonelogger.warning("managed local runtime unavailable: %s", exc)return Nonedef shutdown_local_runtime() -> None:- global _SUPERVISOR+ global _SUPERVISOR, _SERVING_ENGINEif _SUPERVISOR is not None:_SUPERVISOR.stop()_SUPERVISOR = None+ _SERVING_ENGINE = Nonedef get_supervisor():@@ -463,6 +469,11 @@ def get_supervisor():return _SUPERVISOR+def serving_engine():+ """The engine the process-local server runs or is booting, or None when there is none."""+ return _SERVING_ENGINE++_SWEEP_EVERY_S = 120_REFIT_EVERY_S = 30diff --git a/hermes_cli/local_runtime/endpoint.py b/hermes_cli/local_runtime/endpoint.pyindex 34c3e98a61d..eff1dc6ca13 100644--- a/hermes_cli/local_runtime/endpoint.py+++ b/hermes_cli/local_runtime/endpoint.py@@ -131,8 +131,10 @@ def _kick_managed_boot(config: dict | None) -> None:finally:_KICK_LOCK.release()- threading.Thread(target=_boot, daemon=True,- name="lr-on-demand-boot").start()+ from agent.memory_provider import spawn_context_thread++ # The caller's profile scope: ``config=None`` resolves (and the boot prices) under it.+ spawn_context_thread(_boot, name="lr-on-demand-boot").start()def _boot_in_flight(config: dict | None) -> bool:diff --git a/hermes_cli/local_runtime/hardware.py b/hermes_cli/local_runtime/hardware.pyindex 675903a60a6..187dd3fabd9 100644--- a/hermes_cli/local_runtime/hardware.py+++ b/hermes_cli/local_runtime/hardware.py@@ -298,10 +298,15 @@ def _cuda_driver_pool() -> "tuple[int, bool | None] | None":def _configured_engine():- """The installed engine for ``local_runtime.backend``; the probes below run that exact build."""+ """The engine the probes below run: the managed server's own when one is up or booting, else+ the installed engine for ``local_runtime.backend``."""from hermes_cli.config import load_config_readonlyfrom hermes_cli.local_runtime.binaries import installed_engine+ from hermes_cli.local_runtime.bootstrap import serving_engine+ engine = serving_engine()+ if engine is not None:+ return enginesection = load_config_readonly().get("local_runtime") or {}return installed_engine(section.get("backend") or "auto")diff --git a/hermes_cli/web_routers/local_models.py b/hermes_cli/web_routers/local_models.pyindex ace7abce3e0..8a43a4b2432 100644--- a/hermes_cli/web_routers/local_models.py+++ b/hermes_cli/web_routers/local_models.py@@ -35,6 +35,7 @@ from hermes_cli.local_runtime import (binaries, bootstrap, catalog, context_policy, estimator, growth, hardware, hf_browse,load_progress, presets, supervisor,)+from agent.memory_provider import spawn_context_threadfrom pm.downloader import Download, DownloadPaused, Sourcefrom hermes_cli.local_runtime.endpoint import _state_endpoint@@ -268,7 +269,7 @@ def _spawn_job(job: Dict[str, Any], name: str, body: Callable[[], None], *, failjob["status"] = "running"job["error"] = Nonetry:- threading.Thread(target=_run, daemon=True, name=name).start()+ spawn_context_thread(_run, name=name).start()except Exception:_RUNNING.pop(job["job_id"], None)if on_exit is not None:@@ -742,8 +743,8 @@ async def local_models_delete(model_id: str):path.unlink(missing_ok=True)# Growth state dies with the model: a re-download starts back at its zero-spill window, not a stale grown one._quiet(lambda: growth.clear_window_override(model_id), None, debug="window-override clear skipped")- threading.Thread(target=_refresh_runtime, args=("post-delete runtime refresh skipped",), daemon=True,- name="lr-post-delete").start()+ spawn_context_thread(_refresh_runtime, args=("post-delete runtime refresh skipped",),+ name="lr-post-delete").start()return {"ok": True}diff --git a/tests/hermes_cli/test_local_runtime.py b/tests/hermes_cli/test_local_runtime.pyindex 18758b99507..f60a8cd6329 100644--- a/tests/hermes_cli/test_local_runtime.py+++ b/tests/hermes_cli/test_local_runtime.py@@ -983,3 +983,43 @@ def test_ensure_local_runtime_proceeds_when_boot_lock_is_unwritable(tmp_path, moassert result is None # no exception escapedassert any("boot lock unavailable" in rec.getMessage() for rec in caplog.records)+++def test_boot_prices_the_engine_it_serves(tmp_path, monkeypatch):+ """The managed server is shared by every profile the process hosts: its budget is priced on the+ engine being booted, never re-read from whichever profile's config the thread happens to see."""+ from types import SimpleNamespace++ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ from hermes_cli.local_runtime import bootstrap, hardware++ monkeypatch.setattr(bootstrap, "_SUPERVISOR", None)+ monkeypatch.setattr(bootstrap, "_SERVING_ENGINE", None)+ models = bootstrap.models_dir()+ models.mkdir(parents=True, exist_ok=True)+ (models / "test.gguf").touch()+ vulkan = SimpleNamespace(backend="vulkan", tag="b1", binary=tmp_path / "llama-server")+ monkeypatch.setattr("hermes_cli.local_runtime.binaries.installed_engine",+ lambda backend="auto": vulkan if backend == "vulkan" else None)+ monkeypatch.setattr("hermes_cli.config.load_config_readonly",+ lambda: {"local_runtime": {"backend": "cpu"}}) # another profile's config+ priced: list = []+ monkeypatch.setattr(bootstrap, "_generate_presets",+ lambda mdir, path: priced.append(hardware._configured_engine()) or path)+ monkeypatch.setattr(bootstrap, "_admitted_models_max", lambda mdir, configured: configured)++ class _NoStart:+ def __init__(self, *a, **k):+ pass++ def start(self):+ raise RuntimeError("health timeout")++ def stop(self):+ pass++ monkeypatch.setattr("hermes_cli.local_runtime.supervisor.LlamaServerSupervisor", _NoStart)++ assert bootstrap.ensure_local_runtime({"local_runtime": {"enabled": True, "backend": "vulkan"}}) is None+ assert priced == [vulkan]+ assert bootstrap.serving_engine() is None # a failed boot serves nothing