Skip to content

The agent that grows with you

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.py
index 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_stem
logger = 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 = None
def _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 when
disabled/unavailable). Never raises into a session start — failures log and return None; chat
falls back to configured providers."""
- global _SUPERVISOR
+ global _SUPERVISOR, _SERVING_ENGINE
section = (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 = engine
mdir = 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 sup
except Exception as exc: # noqa: BLE001 — never break session start
+ _SERVING_ENGINE = None
logger.warning("managed local runtime unavailable: %s", exc)
return None
def shutdown_local_runtime() -> None:
- global _SUPERVISOR
+ global _SUPERVISOR, _SERVING_ENGINE
if _SUPERVISOR is not None:
_SUPERVISOR.stop()
_SUPERVISOR = None
+ _SERVING_ENGINE = None
def 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 = 30
diff --git a/hermes_cli/local_runtime/endpoint.py b/hermes_cli/local_runtime/endpoint.py
index 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.py
index 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_readonly
from 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 engine
section = 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.py
index 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_thread
from pm.downloader import Download, DownloadPaused, Source
from hermes_cli.local_runtime.endpoint import _state_endpoint
@@ -268,7 +269,7 @@ def _spawn_job(job: Dict[str, Any], name: str, body: Callable[[], None], *, fail
job["status"] = "running"
job["error"] = None
try:
- 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.py
index 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, mo
assert result is None # no exception escaped
assert 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