The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(local_runtime): unify managed-router GET (endpoint.managed_root/managed_get_json) across load_progress+capabilities; shared kv() closure in initial_window; GGUF scalar-type table inlined; compact rationale prose across the package
Tekniuma4a7ab6286bd
diff --git a/hermes_cli/local_runtime/__init__.py b/hermes_cli/local_runtime/__init__.pyindex 31862638401..da81558953a 100644--- a/hermes_cli/local_runtime/__init__.py+++ b/hermes_cli/local_runtime/__init__.py@@ -1,8 +1,8 @@"""Managed llama.cpp runtime.-- ``binaries`` — resolve/download/verify official llama.cpp release zips into-``$HERMES_HOME/runtimes/llamacpp/<tag>/``. - ``supervisor``— spawn and supervise one llama-server in-router mode; readiness is a touch generation, never health-200 alone. - ``detect`` — find an+``binaries`` resolves/downloads/verifies official llama.cpp release zips into+``$HERMES_HOME/runtimes/llamacpp/<tag>/``; ``supervisor`` spawns and supervises one llama-server in+router mode (readiness is a touch generation, never health-200 alone); ``detect`` finds analready-running llama-server (external or ours)."""diff --git a/hermes_cli/local_runtime/capabilities.py b/hermes_cli/local_runtime/capabilities.pyindex 084d7a190a9..895db98ae66 100644--- a/hermes_cli/local_runtime/capabilities.py+++ b/hermes_cli/local_runtime/capabilities.py@@ -8,27 +8,22 @@ screenshot silently leaving the machine).from __future__ import annotations-import jsonimport logging-import urllib.requestlogger = logging.getLogger(__name__)from hermes_cli.local_runtime.endpoint import LLAMACPP_ALIASES as _LLAMACPP_ALIASES-# Image formats the managed server's decoder actually handles. llama.cpp-# decodes with stb_image: PNG/JPEG/GIF/BMP yes, WebP NO — and a WebP part-# fails SILENTLY (no HTTP error, no log line; the model just never sees an-# image and confabulates a description). Anything outside this set must be-# transcoded before the request. Measured against the live server: the-# same red square answered 'Red' as PNG and 'Unseen' as WebP.+# Image formats the managed server's decoder actually handles. llama.cpp decodes with stb_image:+# PNG/JPEG/GIF/BMP yes, WebP NO — and a WebP part fails SILENTLY (no HTTP error, no log line; the+# model just never sees an image and confabulates). Anything outside this set must be transcoded+# before the request. Measured live: the same red square answered 'Red' as PNG, 'Unseen' as WebP.ACCEPTED_IMAGE_MIMES = frozenset({"image/png", "image/jpeg"})def is_managed_provider(provider: str, base_url: str = "") -> bool:- """True when this provider/base_url pair points at the managed server.- ``custom`` only counts when the base_url IS the managed endpoint —- background lookups must never claim someone else's custom server."""+ """True when this provider/base_url pair points at the managed server. ``custom`` only counts+ when the base_url IS the managed endpoint — never claim someone else's custom server."""p = (provider or "").strip().lower()if p in _LLAMACPP_ALIASES:return True@@ -43,21 +38,15 @@ def is_managed_provider(provider: str, base_url: str = "") -> bool:def _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.- """+ """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:- from hermes_cli.local_runtime.endpoint import _state_endpoint+ from hermes_cli.local_runtime.endpoint import managed_get_json, managed_root- state = _state_endpoint()- if state is None:+ ep = managed_root()+ if ep is None:return None- base = state["base_url"].rsplit("/v1", 1)[0]- req = urllib.request.Request(- f"{base}/props?model={model_id}",- headers={"Authorization": f"Bearer {state.get('api_key', '')}"})- with urllib.request.urlopen(req, timeout=3) as r:- props = json.load(r)+ props = managed_get_json(*ep, f"/props?model={model_id}", timeout_s=3)modalities = props.get("modalities")if isinstance(modalities, dict) and "vision" in modalities:return bool(modalities["vision"])@@ -67,8 +56,8 @@ def _props_modalities(model_id: str) -> "bool | None":def managed_model_supports_vision(model_id: str) -> "bool | None":- """Ground-truth vision capability for a staged model, or None when the- model isn't ours / nothing is known (caller keeps falling through)."""+ """Ground-truth vision capability for a staged model, or None when the model isn't ours /+ nothing is known (caller keeps falling through)."""if not model_id:return None@@ -85,8 +74,9 @@ def managed_model_supports_vision(model_id: str) -> "bool | None":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.+ # 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_dirfrom hermes_cli.local_runtime.catalog import find_entry_for_model@@ -97,9 +87,6 @@ def managed_model_supports_vision(model_id: str) -> "bool | None":entry = hit[0]if entry.mmproj is None:return False- # Capability requires the projector to actually be on disk — a- # model downloaded before its mmproj (partial delete, old layout)- # genuinely cannot see.return (assets_dir() / entry.mmproj.local_name).exists()except Exception: # noqa: BLE001return Nonediff --git a/hermes_cli/local_runtime/context_policy.py b/hermes_cli/local_runtime/context_policy.pyindex 682580f8f71..a147c141050 100644--- a/hermes_cli/local_runtime/context_policy.py+++ b/hermes_cli/local_runtime/context_policy.py@@ -1,10 +1,8 @@"""Context policy — the window ladder for managed local models.One contract: any model runs at any window up to its native max; hardware and session depth only-change tokens/s. Constants, not knobs — nothing in this module reads config.--The policy encodes behavior measured on real hardware (llama.cpp, discrete NVIDIA GPUs on-Windows/WDDM, and unified-memory devices):+change tokens/s. Constants, not knobs — nothing in this module reads config. The policy encodes+behavior measured on real hardware (llama.cpp, discrete NVIDIA on Windows/WDDM, unified-memory)."""from __future__ import annotations@@ -25,22 +23,17 @@ _GROW_AT_OCCUPANCY = 0.85 # of the current window, at turn boundarySPEED_FLOOR_TOK_S = 6.0 # deepest measured spill bottomed near this_EARLY_COST_CTX_FRACTION = 0.15 # bounded early cost when weights spill-# TARGET_WINDOW: the smallest ladder rung at which compression becomes the-# exception rather than the routine. Measured over 161 real agentic-# sessions: 66% complete uncompressed in 64K, 82% in 96K, 91% in 144K —-# and the marginal gain past 144K (+6 points for 216K) falls below the-# quality cost of stepping down another quant. Quant selection prefers-# the best build that reaches this; the FLOOR remains the guarantee.+# The smallest ladder rung at which compression becomes the exception rather than the routine.+# Measured over 161 real agentic sessions: 66% complete uncompressed in 64K, 82% in 96K, 91% in+# 144K — and the marginal gain past 144K (+6 points for 216K) falls below the quality cost of+# stepping down another quant. The FLOOR remains the guarantee.TARGET_WINDOW = 144 * 1024-# What a load really costs beyond weights + KV: CUDA contexts and compute-# buffers at the DEFAULT microbatch (-ub 512, no MTP). Measured on a-# 32 GiB card: a model estimated at 29.3 GiB (weights+KV) loaded at-# ~31.2 GiB resident and the server's own fit still shaved a layer to-# CPU. Microbatch/MTP logits buffers are priced separately per model-# (ub_logits_bytes — they scale with the model's vocab and doubled once-# packed a card 3.9 GiB past this constant). Callers add mmproj bytes on-# top.+# What a load really costs beyond weights + KV: CUDA contexts and compute buffers at the DEFAULT+# microbatch (-ub 512, no MTP). Measured on a 32 GiB card: a model estimated at 29.3 GiB loaded at+# ~31.2 GiB resident and fit still shaved a layer to CPU. Microbatch/MTP logits buffers are priced+# separately per model (ub_logits_bytes — they scale with vocab and once packed a card 3.9 GiB+# past this constant). Callers add mmproj bytes on top.RUNTIME_OVERHEAD_BYTES = int(1.5 * (1 << 30))@@ -74,8 +67,8 @@ def initial_window(profile: ModelProfile, budget: HardwareBudget,Zero-spill rung: weights + ctx + overhead fit usable VRAM entirely. Bounded-early-cost rung(weights already exceed VRAM): largest rung whose ctx stays <= ~15% of usable VRAM. Floor- everywhere, capped at native. ``overhead_bytes`` is runtime cost beyond weights+KV; zero- keeps this pure physics for decision-table tests, production callers pass it.+ everywhere, capped at native. ``overhead_bytes`` is runtime cost beyond weights+KV; zero keeps+ this pure physics for decision-table tests, production callers pass it."""refusal = physics_check(profile, budget, FLOOR, flash_attention=flash_attention)if refusal:@@ -84,38 +77,36 @@ def initial_window(profile: ModelProfile, budget: HardwareBudget,native = profile.n_ctx_train or FLOORrungs = ladder(native)- reasons: list[str] = []+ def kv(rung: int) -> int:+ return ctx_bytes(profile, rung, flash_attention=flash_attention)+best_zero_spill: int | None = Nonefor rung in rungs:- need = (profile.weights_bytes + overhead_bytes- + ctx_bytes(profile, rung, flash_attention=flash_attention))- if need <= budget.usable_vram_bytes:- best_zero_spill = rung- else:+ if profile.weights_bytes + overhead_bytes + kv(rung) > budget.usable_vram_bytes:break+ best_zero_spill = rungif best_zero_spill is not None and best_zero_spill >= min(FLOOR, native):window = best_zero_spill- reasons.append(f"largest zero-spill rung ({window // 1024}K)")+ reason = f"largest zero-spill rung ({window // 1024}K)"else:- # Weights spill from turn one (steep-curve model on a small card) —- # hold the floor, bound the early ctx cost.+ # Weights spill from turn one (steep-curve model on a small card) — hold the floor, bound+ # the early ctx cost.cap = int(budget.usable_vram_bytes * _EARLY_COST_CTX_FRACTION)window = min(FLOOR, native)for rung in rungs:if rung < window:continue- if ctx_bytes(profile, rung, flash_attention=flash_attention) <= cap:- window = rung- else:+ if kv(rung) > cap:break- reasons.append(f"floor held at {window // 1024}K; weights spill (deliberate price of the guarantee)")+ window = rung+ reason = f"floor held at {window // 1024}K; weights spill (deliberate price of the guarantee)"- kv = ctx_bytes(profile, window, flash_attention=flash_attention)- spill = max(0, profile.weights_bytes + kv - budget.usable_vram_bytes)+ kv_bytes = kv(window)+ spill = max(0, profile.weights_bytes + kv_bytes - budget.usable_vram_bytes)return WindowDecision(window=window, spill_bytes=spill,- kv_on_gpu=kv <= budget.usable_vram_bytes,- reasons=reasons)+ kv_on_gpu=kv_bytes <= budget.usable_vram_bytes,+ reasons=[reason])@dataclass@@ -134,9 +125,9 @@ def growth_decision(profile: ModelProfile, budget: HardwareBudget, *,"""One growth evaluation, END-OF-TURN ONLY (recurrent state cannot rewind mid-sequence).Gate order: occupancy (~85%) → native cap → idleness (growth only on an otherwise-idle- server) → speed floor (below it compression is the default) → re-fit against LIVE free- memory (the rung must fit NOW, not at launch). ``occupancy_confirmed`` skips gate 1 when the- caller's own compression gate already fired, so two edge definitions can't deadlock into+ server) → speed floor (below it compression is the default) → re-fit against LIVE free memory+ (the rung must fit NOW, not at launch). ``occupancy_confirmed`` skips gate 1 when the caller's+ own compression gate already fired, so two edge definitions can't deadlock intocompress-before-grow."""if not occupancy_confirmed and session_tokens < current_window * _GROW_AT_OCCUPANCY:@@ -159,11 +150,10 @@ def growth_decision(profile: ModelProfile, budget: HardwareBudget, *,next_rung = next((r for r in ladder(native) if r > current_window), native)- # Re-fit against live free memory: allocation beyond residency is the- # slow path, so a rung that no longer fits doesn't get granted.+ # Re-fit against live free memory: allocation beyond residency is the slow path, so a rung+ # that no longer fits doesn't get granted.kv = ctx_bytes(profile, next_rung, flash_attention=flash_attention)- total_need = profile.weights_bytes + kv- if total_need > budget.usable_vram_bytes + budget.ram_available_bytes:+ if profile.weights_bytes + kv > budget.usable_vram_bytes + budget.ram_available_bytes:return GrowthDecision("compress-default",reason="next rung exceeds physics; compression instead")@@ -173,9 +163,8 @@ def growth_decision(profile: ModelProfile, budget: HardwareBudget, *,def spill_overrides(profile: ModelProfile) -> list[str]:"""-ot placement for spilled configs: expert/FFN weights to host so attention + KV stay- GPU-resident. MoE gets the expert pattern; hybrids push recurrent-layer FFNs (their n_head_kv==0- layers carry no KV worth protecting).- """+ GPU-resident. MoE gets the expert pattern; hybrids push recurrent-layer FFNs (their+ n_head_kv==0 layers carry no KV worth protecting)."""if profile.moe:return ["-ot", r"blk\.\d+\.ffn_.*_exps\.weight=CPU"]if profile.recurrent_layer_count:@@ -191,8 +180,7 @@ def launch_args(profile: ModelProfile, decision: WindowDecision, *,mtp_prefill: bool = False) -> list[str]:"""Per-model launch flags from a window decision. Explicit -c puts fit intospill-weights-and-hold-ctx; q8 KV cache wherever flash attention exists; -ot placement on- spilled configs — DISCRETE cards only.- """+ spilled configs — DISCRETE cards only."""args = ["-c", str(decision.window)]if mtp_capable:args += ["--spec-type", "draft-mtp",@@ -211,10 +199,9 @@ def launch_args(profile: ModelProfile, decision: WindowDecision, *,def ub_logits_bytes(n_vocab: int, *, mtp_capable: bool,mtp_prefill: bool = False) -> int:- """GPU logits/compute-buffer cost of the microbatch posture chosen by launch_args, priced from the- model's own vocab and calibrated against measured server RSS (Qwen3.8 Q4, both postures, three- windows):- """+ """GPU logits/compute-buffer cost of the microbatch posture chosen by launch_args, priced from+ the model's own vocab and calibrated against measured server RSS (Qwen3.8 Q4, both postures,+ three windows)."""v = max(0, int(n_vocab))if mtp_capable and mtp_prefill:return int(2048 * v * 4 * 1.5)diff --git a/hermes_cli/local_runtime/detect.py b/hermes_cli/local_runtime/detect.pyindex 376054555ac..5205f9cc8a5 100644--- a/hermes_cli/local_runtime/detect.py+++ b/hermes_cli/local_runtime/detect.py@@ -1,9 +1,8 @@"""Detection of running llama-server instances.Probes well-known local roots and fingerprints genuine llama-server via /props (build_info + model-fields — Ollama and LM Studio answer /v1/models but not /props). The credential is reachability;-detection never needs a key, but honors one if the probed server requires it (401 -> detected,-auth_required=True).+fields — Ollama and LM Studio answer /v1/models but not /props). Detection never needs a key, but+honors one if the probed server requires it (401 -> detected, auth_required=True)."""from __future__ import annotations@@ -51,13 +50,12 @@ def probe_port(port: int) -> DetectedServer | None:if not build:return None # answers /props but isn't llama-serverdgs = props.get("default_generation_settings")- n_ctx = dgs.get("n_ctx") if isinstance(dgs, dict) else Nonemodels_status, models = _get(f"{root}/models")return DetectedServer(base_url=f"{root}/v1",build_info=build,model_path=str(props.get("model_path", "")),- n_ctx=n_ctx,+ n_ctx=dgs.get("n_ctx") if isinstance(dgs, dict) else None,router_mode=(models_status == 200 and isinstance(models, dict)and "data" in models),auth_required=False,diff --git a/hermes_cli/local_runtime/endpoint.py b/hermes_cli/local_runtime/endpoint.pyindex 9ce50c431af..437422bfe80 100644--- a/hermes_cli/local_runtime/endpoint.py+++ b/hermes_cli/local_runtime/endpoint.py@@ -11,6 +11,7 @@ import jsonimport loggingimport threadingimport time+import urllib.requestLLAMACPP_ALIASES = frozenset({"llamacpp", "llama.cpp", "llama-cpp"})@@ -55,6 +56,29 @@ def _state_endpoint() -> dict | None:return {"base_url": base_url, "api_key": state.get("api_key", "")}+def managed_root() -> "tuple[str, str] | None":+ """(base_root, api_key) of the managed router, or None. Resolved through the+ ownership-guarded reader, not a raw state-file read: on the shared stable port a foreign+ install's server answers /health for anyone, and a raw read would attach callers to someone+ else's server."""+ try:+ state = _state_endpoint()+ if state is None:+ return None+ base = 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+++def managed_get_json(base: str, api_key: str, route: str, timeout_s: float) -> object:+ """Authenticated GET against the managed router; raises on any transport/decode failure."""+ req = urllib.request.Request(f"{base}{route}",+ headers={"Authorization": f"Bearer {api_key}"})+ with urllib.request.urlopen(req, timeout=timeout_s) as r:+ return json.loads(r.read())++def resolve_llamacpp_endpoint(config: dict | None = None,wait_for_boot_s: float = 8.0) -> dict | None:"""Managed-first, detection-second endpoint for llamacpp aliases.diff --git a/hermes_cli/local_runtime/estimator.py b/hermes_cli/local_runtime/estimator.pyindex 988a88a2a1c..40c184d4785 100644--- a/hermes_cli/local_runtime/estimator.py+++ b/hermes_cli/local_runtime/estimator.py@@ -15,15 +15,13 @@ from hermes_cli.local_runtime.gguf import GGUFHeader_Q8_BYTES_PER_ELEM = 34 / 32_F16_BYTES_PER_ELEM = 2.0-# Architectures with a known SWA layer pattern: arch -> fraction of layers-# that are sliding-window. Unknown SWA archs conservatively treat every-# layer as full attention (overestimate; safe direction).+# Architectures with a known SWA layer pattern: arch -> fraction of layers that are+# sliding-window. Unknown SWA archs treat every layer as full attention (overestimate; safe)._SWA_LAYER_FRACTION = {"gemma3": 5 / 6, "gemma2": 1 / 2}-# Per-recurrent-layer state allowance (bytes/seq). Deliberately generous —-# Measured: an entire hybrid slot state is ~99 MB including 8K tokens of-# full-attn KV, so tens of MiB total is the right order; unknown SSM shapes-# must never underestimate.+# Per-recurrent-layer state allowance (bytes/seq). Deliberately generous: an entire measured+# hybrid slot state is ~99 MB including 8K tokens of full-attn KV, so tens of MiB total is the+# right order; unknown SSM shapes must never underestimate._RECURRENT_STATE_PER_LAYER = 4 << 20@@ -35,26 +33,22 @@ class LayerKind(Enum):@dataclassclass ModelProfile:- """Everything the policy needs, decoupled from GGUF parsing so the decision-table tests can- construct profiles directly (design's verification plan).- """+ """Everything the policy needs, decoupled from GGUF parsing so decision-table tests can+ construct profiles directly."""name: strweights_bytes: intembd_table_bytes: intn_ctx_train: int- layers: list[tuple[LayerKind, int]] # (kind, kv_bytes_per_token_f16);- # SWA/recurrent reuse the same- # per-token figure, capped/ignored+ layers: list[tuple[LayerKind, int]] # (kind, kv_bytes_per_token_f16); SWA capped, recurrent ignoredswa_window: int = 0moe: bool = Falsearchitecture: str = ""n_vocab: int = 0 # prices logits buffers (ubatch x vocab)- # Context-cost multiplier. MTP spec decode keeps a small draft- # context beside the main one. Calibrated against four measured- # server-RSS points on Qwen3.8 Q4 (128K/221K/256K, both postures):- # the draft adds ~17% to per-token KV; 1.2 rounds up so the error- # stays on the safe side (+250 MiB at 256K, never negative).+ # Context-cost multiplier. MTP spec decode keeps a small draft context beside the main one;+ # calibrated against four measured server-RSS points on Qwen3.8 Q4 (128K/221K/256K, both+ # postures): the draft adds ~17% to per-token KV; 1.2 rounds up so the error stays on the safe+ # side (+250 MiB at 256K, never negative).kv_scale: float = 1.0@property@@ -69,12 +63,9 @@ class ModelProfile:@dataclassclass HardwareBudget:- """Memory the physics check may budget against.-- Budget-source rule: discrete cards may trust the device query (measured honest); unified-memory- devices must budget from OS free physical memory minus headroom — their device queries have been- observed off by 3x. Callers construct this accordingly; the estimator just consumes it.- """+ """Memory the physics check may budget against. Discrete cards may trust the device query;+ unified-memory devices must budget from OS free memory minus headroom (device queries observed+ off by 3x). Callers construct this accordingly; the estimator just consumes it."""usable_vram_bytes: int # live free (discrete) / derived (UMA)total_device_bytes: int@@ -97,8 +88,8 @@ def profile_from_gguf(header: GGUFHeader) -> ModelProfile:layers.append((LayerKind.RECURRENT, 0))continueper_token = round(heads * (dk + dv) * _F16_BYTES_PER_ELEM)- # Distribute the SWA share across the first n_swa attention layers;- # only the full/SWA SPLIT matters to the totals, not which indexes.+ # Distribute the SWA share across the first n_swa attention layers; only the full/SWA+ # SPLIT matters to the totals, not which indexes.kind = LayerKind.SWA if n_attn_seen < n_swa else LayerKind.FULLlayers.append((kind, per_token))n_attn_seen += 1@@ -117,17 +108,15 @@ def profile_from_gguf(header: GGUFHeader) -> ModelProfile:def kv_dtype_factor(flash_attention: bool) -> float:- """q8_0 with FA (every backend we ship); f16 on exotic non-FA fallbacks- — the 64K guarantee stands either way, the physics check just prices- the doubled KV (design: KV dtype is behavior, not config)."""+ """q8_0 with FA (every backend we ship); f16 on exotic non-FA fallbacks — the 64K guarantee+ stands either way, the physics check just prices the doubled KV."""return (_Q8_BYTES_PER_ELEM / _F16_BYTES_PER_ELEM) if flash_attention else 1.0def ctx_bytes(profile: ModelProfile, window: int, *,flash_attention: bool = True) -> int:- """Context memory for one window: full layers linear in T, SWA layers capped at the sliding window,- recurrent layers constant. Scaled by profile.kv_scale (MTP draft context).- """+ """Context memory for one window: full layers linear in T, SWA layers capped at the sliding+ window, recurrent layers constant. Scaled by profile.kv_scale (MTP draft context)."""factor = kv_dtype_factor(flash_attention)total = 0.0for kind, per_token_f16 in profile.layers:@@ -142,8 +131,8 @@ def ctx_bytes(profile: ModelProfile, window: int, *,@dataclassclass PhysicsRefusal:- """The only true refusal: weights + floor-KV + state exceed VRAM + RAM.- The remedy is a smaller quant, never a smaller window."""+ """The only true refusal: weights + floor-KV + state exceed VRAM + RAM. The remedy is a+ smaller quant, never a smaller window."""needed_bytes: intavailable_bytes: intdiff --git a/hermes_cli/local_runtime/gguf.py b/hermes_cli/local_runtime/gguf.pyindex 816c085d64b..e22f1b5d6c9 100644--- a/hermes_cli/local_runtime/gguf.py+++ b/hermes_cli/local_runtime/gguf.py@@ -22,8 +22,9 @@ def model_id_from_stem(stem: str) -> str:"""Model id from a GGUF file stem (split-part suffix stripped)."""return _PART_SUFFIX_RE.sub("", stem)-# ggml tensor type sizes: type_id -> (block_bytes, block_elems).-# IQ-family sizes verified against ggml-common.h.++# ggml tensor type sizes: type_id -> (block_bytes, block_elems). IQ-family verified against+# ggml-common.h._GGML_TYPE_SIZES = {0: (4, 1), 1: (2, 1), 2: (18, 32), 3: (20, 32), 6: (22, 32), 7: (24, 32),8: (34, 32), 9: (36, 32), 10: (84, 256), 11: (110, 256), 12: (144, 256),@@ -33,17 +34,20 @@ _GGML_TYPE_SIZES = {26: (4, 1), 27: (8, 1), 28: (8, 1), 29: (56, 256), 30: (2, 1),}-# GGUF metadata value types.-_V_UINT8, _V_INT8, _V_UINT16, _V_INT16 = 0, 1, 2, 3-_V_UINT32, _V_INT32, _V_FLOAT32, _V_BOOL = 4, 5, 6, 7-_V_STRING, _V_ARRAY, _V_UINT64, _V_INT64, _V_FLOAT64 = 8, 9, 10, 11, 12-+# GGUF metadata value types -> struct format; STRING (8) and ARRAY (9) are variable-length.+_V_STRING, _V_ARRAY = 8, 9_SCALAR_FMT = {- _V_UINT8: "<B", _V_INT8: "<b", _V_UINT16: "<H", _V_INT16: "<h",- _V_UINT32: "<I", _V_INT32: "<i", _V_FLOAT32: "<f", _V_BOOL: "<?",- _V_UINT64: "<Q", _V_INT64: "<q", _V_FLOAT64: "<d",+ 0: "<B", 1: "<b", 2: "<H", 3: "<h", # uint8 int8 uint16 int16+ 4: "<I", 5: "<i", 6: "<f", 7: "<?", # uint32 int32 float32 bool+ 10: "<Q", 11: "<q", 12: "<d", # uint64 int64 float64}+# general.sampling.* metadata key -> preset INI key.+_SAMPLING_INI_KEY = {"temp": "temp", "temperature": "temp", "top_p": "top-p",+ "top_k": "top-k", "min_p": "min-p",+ "repeat_penalty": "repeat-penalty",+ "presence_penalty": "presence-penalty"}+@dataclassclass GGUFHeader:@@ -52,8 +56,7 @@ class GGUFHeader:metadata: dict = field(default_factory=dict)n_tensors: int = 0tensor_bytes: int = 0 # exact sum over the tensor table- embd_table_bytes: int = 0 # token_embd.weight (duplicated host-side- # when fully offloaded)+ embd_table_bytes: int = 0 # token_embd.weight (duplicated host-side when fully offloaded)# ── typed accessors ──────────────────────────────────────@@ -64,15 +67,17 @@ class GGUFHeader:def _arch_key(self, suffix: str):return self.metadata.get(f"{self.architecture}.{suffix}")+ def _arch_int(self, suffix: str) -> int:+ return int(self._arch_key(suffix) or 0)+@propertydef n_layer(self) -> int:- return int(self._arch_key("block_count") or 0)+ return self._arch_int("block_count")@propertydef n_vocab(self) -> int:- """Vocabulary size: prices the GPU logits buffers (they scale ubatch x vocab). vocab_size- metadata when present, else the tokenizer list length.- """+ """Vocabulary size (prices the GPU logits buffers): vocab_size metadata when present, else+ the tokenizer list length."""v = self._arch_key("vocab_size")if v:return int(v)@@ -81,26 +86,21 @@ class GGUFHeader:@propertydef n_ctx_train(self) -> int:- return int(self._arch_key("context_length") or 0)+ return self._arch_int("context_length")@propertydef sampling_defaults(self) -> dict:- """Upstream's recommended sampling, when the file carries it.+ """Upstream's recommended sampling as preset INI keys, when the file carries it.Publishers bake ``general.sampling.*`` keys into the GGUF (llama-server reads them as that- model's defaults), so the file is the source of truth -- it ships with the download and- updates with every re-upload, no catalog needed. Returned as preset INI keys; empty if- absent.+ model's defaults), so the file is the source of truth — it ships with the download and+ updates with every re-upload, no catalog needed. Empty if absent."""- ini_key = {"temp": "temp", "temperature": "temp", "top_p": "top-p",- "top_k": "top-k", "min_p": "min-p",- "repeat_penalty": "repeat-penalty",- "presence_penalty": "presence-penalty"}out = {}for key, value in self.metadata.items():if not key.startswith("general.sampling."):continue- name = ini_key.get(key.rsplit(".", 1)[-1])+ name = _SAMPLING_INI_KEY.get(key.rsplit(".", 1)[-1])if name is not None and isinstance(value, (int, float)):num = round(float(value), 4)out[name] = str(int(num)) if num == int(num) else str(num)@@ -108,7 +108,7 @@ class GGUFHeader:@propertydef n_embd(self) -> int:- return int(self._arch_key("embedding_length") or 0)+ return self._arch_int("embedding_length")@propertydef n_head(self) -> int:@@ -119,16 +119,16 @@ class GGUFHeader:@propertydef full_attention_interval(self) -> int:- """GDN-hybrid discriminator (qwen35 family): every Nth layer is full- attention, the rest are linear/recurrent. 0 = not present."""- return int(self._arch_key("full_attention_interval") or 0)+ """GDN-hybrid discriminator (qwen35 family): every Nth layer is full attention, the rest+ are linear/recurrent. 0 = not present."""+ return self._arch_int("full_attention_interval")def head_counts_kv(self) -> list[int]:"""Per-layer KV head counts; 0 marks a recurrent/linear layer (n_head_kv == 0).Three GGUF shapes: a per-layer array (nemotron_h_moe) is used as-is; a scalar plus``full_attention_interval`` (qwen35) applies to every N-th layer (1-indexed) and is zero- elsewhere -- pricing all layers as attention was a 4x overestimate; a plain scalar (dense)+ elsewhere — pricing all layers as attention was a 4x overestimate; a plain scalar (dense)broadcasts to every layer."""v = self._arch_key("attention.head_count_kv")@@ -157,11 +157,11 @@ class GGUFHeader:@propertydef sliding_window(self) -> int:- return int(self._arch_key("attention.sliding_window") or 0)+ return self._arch_int("attention.sliding_window")@propertydef expert_count(self) -> int:- return int(self._arch_key("expert_count") or 0)+ return self._arch_int("expert_count")def read_gguf_header(path: str | Path) -> GGUFHeader:diff --git a/hermes_cli/local_runtime/growth.py b/hermes_cli/local_runtime/growth.pyindex 43cca00d0bb..d5329b3b76d 100644--- a/hermes_cli/local_runtime/growth.py+++ b/hermes_cli/local_runtime/growth.py@@ -1,7 +1,7 @@"""In-session context growth for the managed llama.cpp runtime.-Scope guard: only a server THIS process supervises grows. Detected external servers and other--process supervisors keep their own policies.+Scope guard: only a server THIS process supervises grows. Detected external servers and+other-process supervisors keep their own policies."""from __future__ import annotations@@ -28,21 +28,24 @@ def load_window_overrides() -> dict:return {}-def save_window_override(model_id: str, window: int) -> None:- overrides = load_window_overrides()- overrides[model_id] = int(window)+def _write_overrides(overrides: dict) -> None:path = window_overrides_path()path.parent.mkdir(parents=True, exist_ok=True)path.write_text(json.dumps(overrides, indent=1), encoding="utf-8")+def save_window_override(model_id: str, window: int) -> None:+ overrides = load_window_overrides()+ overrides[model_id] = int(window)+ _write_overrides(overrides)++def clear_window_override(model_id: str) -> None:"""Drop a model's growth state (delete/re-download paths)."""overrides = load_window_overrides()if model_id in overrides:del overrides[model_id]- window_overrides_path().write_text(- json.dumps(overrides, indent=1), encoding="utf-8")+ _write_overrides(overrides)def is_managed_endpoint(base_url: str) -> bool:@@ -100,18 +103,16 @@ def maybe_grow_window(model_id: str, *, base_url: str, session_tokens: int,server_idle = Falsedecision = growth_decision(- # Capacity budget, not live-free: growth executes via a server- # bounce, so the grown instance loads onto a freed card. Live-free- # here is distorted by the very model being grown — it reads its- # own residency as unavailable and vetoes rungs that fit.+ # Capacity budget, not live-free: growth executes via a server bounce, so the grown+ # instance loads onto a freed card. Live-free is distorted by the very model being grown+ # — it reads its own residency as unavailable and vetoes rungs that fit.profile, probe_budget(planning=True),current_window=current_window,session_tokens=session_tokens,measured_decode_tok_s=measured_decode_tok_s,server_idle=server_idle,- # The caller IS the occupancy signal: this runs from the agent's- # compression gate, which fired on its own threshold. Two- # separately-derived edges must not deadlock into+ # The caller IS the occupancy signal: this runs from the agent's compression gate, which+ # fired on its own threshold. Two separately-derived edges must not deadlock into# compress-before-grow.occupancy_confirmed=True,)@@ -122,8 +123,8 @@ def maybe_grow_window(model_id: str, *, base_url: str, session_tokens: int,logger.info("context growth %s: %s", model_id, decision.reason)save_window_override(model_id, decision.next_window)if not refresh_local_runtime():- # The override still lands at the next boot; report no growth NOW- # so the caller compresses instead of overflowing a stale window.+ # The override still lands at the next boot; report no growth NOW so the caller+ # compresses instead of overflowing a stale window.logger.warning("growth %s: server refresh failed; compression proceeds", model_id)return Nonereturn decision.next_windowdiff --git a/hermes_cli/local_runtime/hf_browse.py b/hermes_cli/local_runtime/hf_browse.pyindex d69e1fbc855..ef02f508f01 100644--- a/hermes_cli/local_runtime/hf_browse.py+++ b/hermes_cli/local_runtime/hf_browse.py@@ -1,11 +1,9 @@"""Browse Hugging Face for GGUF models the user can run.The curated catalog is the front page; this module is the firehose behind it — day-0 models not yet-in the catalog, community quants, anything. Three rules keep it safe and honest:--1. Acquisition only. Nothing here serves a model: a browsed download lands in the machine-scoped-models dir and from that moment the normal machinery owns it — staleness bounce, preset generation-from the real GGUF header, fit policy, placement pills. 2.+in the catalog, community quants, anything. Acquisition only: nothing here serves a model. A browsed+download lands in the machine-scoped models dir and from that moment the normal machinery owns it —+staleness bounce, preset generation from the real GGUF header, fit policy, placement pills."""from __future__ import annotations@@ -22,14 +20,12 @@ logger = logging.getLogger(__name__)_HF = "https://huggingface.co"_TIMEOUT_S = 15-# Rough-fit fill-ins for pre-download pricing: a mid-size model's 64K-floor-# KV plus runtime overhead. Deliberately round numbers — the verdict bands-# are coarse (fits GPU / needs RAM / too big), not window grants.+# Rough-fit fill-in for pre-download pricing: a mid-size model's 64K-floor KV plus runtime+# overhead. Deliberately round — the verdict bands are coarse, not window grants._ROUGH_KV_AND_OVERHEAD = 4 << 30-# Tiny TTL cache: the pane fires a search per keystroke pause and re-opens-# repos the user flips between. Process-local, size-capped, no invalidation-# subtleties — upstream truth changes slowly at this granularity.+# Tiny TTL cache: the pane fires a search per keystroke pause and re-opens repos the user flips+# between. Process-local, size-capped; upstream truth changes slowly at this granularity._CACHE: dict[str, tuple[float, object]] = {}_CACHE_TTL_S = 300_CACHE_MAX = 128@@ -74,8 +70,8 @@ _SPLIT_RE = re.compile(r"-(\d{5})-of-(\d{5})\.gguf$", re.IGNORECASE)def search_models(query: str, limit: int = 20) -> list[HFModelHit]:- """Full-text search over HF models that ship GGUF files, most- downloaded first (the closest public signal to 'trending')."""+ """Full-text search over HF models that ship GGUF files, most downloaded first (the closest+ public signal to 'trending')."""q = urllib.parse.quote(query.strip())url = (f"{_HF}/api/models?search={q}&filter=gguf&sort=downloads"f"&direction=-1&limit={max(1, min(int(limit), 50))}")@@ -93,9 +89,8 @@ def _quant_label(filename: str) -> str:def repo_files(repo: str) -> list[HFFileGroup]:- """The servable GGUFs in a repo, grouped: split parts collapse into one- entry (first part is what llama.cpp loads), mmproj/draft companions are- excluded (they aren't standalone models). Largest quant first."""+ """The servable GGUFs in a repo, grouped: split parts collapse into one entry (first part is+ what llama.cpp loads); mmproj/draft companions are excluded. Largest quant first."""url = f"{_HF}/api/models/{urllib.parse.quote(repo)}/tree/main?recursive=true"files = _get_json(url)@@ -106,13 +101,12 @@ def repo_files(repo: str) -> list[HFFileGroup]:if not path.lower().endswith(".gguf"):continuename = path.rsplit("/", 1)[-1].lower()- if name.startswith("mmproj") or name.startswith("dspark") or "draft" in name:+ if name.startswith(("mmproj", "dspark")) or "draft" in name:continuesize = int(f.get("size") or 0)m = _SPLIT_RE.search(path)if m:- stem = path[: m.start()]- splits.setdefault(stem, []).append((int(m.group(1)), path, size))+ splits.setdefault(path[: m.start()], []).append((int(m.group(1)), path, size))else:singles.append((path, size))@@ -129,9 +123,8 @@ def repo_files(repo: str) -> list[HFFileGroup]:def rough_fit(total_bytes: int, budget) -> str:- """Coarse pre-download verdict from file size alone. The GGUF header refines this after download;- bands match the catalog pills' language. File size ≈ in-memory weights for GGUF (mmap'd as-is).- """+ """Coarse pre-download verdict from file size alone (GGUF file size ≈ in-memory weights);+ the GGUF header refines this after download. Bands match the catalog pills' language."""need = total_bytes + _ROUGH_KV_AND_OVERHEADif need <= budget.usable_vram_bytes:return "fits-gpu"diff --git a/hermes_cli/local_runtime/load_progress.py b/hermes_cli/local_runtime/load_progress.pyindex da86a6ba940..20e1ad4603d 100644--- a/hermes_cli/local_runtime/load_progress.py+++ b/hermes_cli/local_runtime/load_progress.py@@ -1,12 +1,10 @@"""Live model-load progress from the managed llama-server router.-llama-server's child processes emit per-tensor load progress ({stages, current, value}, throttled-upstream to ~200ms) which the router relays ONLY over its /models/sse stream — GET /models carries-just the coarse status string.--The watcher starts on first call, reconnects with backoff (the router bounces on model-download/eject), and never raises into callers — no router, no state file, or no SSE support (older-engines) all read as "nothing loading".+llama-server's children emit per-tensor load progress ({stages, current, value}, throttled upstream+to ~200ms) which the router relays ONLY over its /models/sse stream — GET /models carries just the+coarse status string. The watcher starts on first call, reconnects with backoff (the router bounces+on model download/eject), and never raises into callers — no router, no state file, or no SSE+support (older engines) all read as "nothing loading"."""from __future__ import annotations@@ -22,51 +20,43 @@ logger = logging.getLogger(__name__)_TEXT_STAGE_SHARE = 0.85 # composite range share for the text model_RECONNECT_DELAY_S = 3.0_STALE_ENTRY_TTL_S = 120.0 # a loading entry with no events this long is dead+_LOAD_EVENTS = ("status_change", "model_status")_lock = threading.Lock()_watcher: threading.Thread | None = None_snapshot: dict[str, dict] = {}+def _pct(x: float) -> int:+ return max(0, min(100, round(x * 100)))++def _composite_percent(stages: list[str], current: str, value: float) -> int:"""Map (stage, in-stage value) onto one 0-100 range, text-heavy."""if not stages or current not in stages or len(stages) == 1:- return max(0, min(100, round(value * 100)))+ return _pct(value)extras = [s for s in stages if s != "text_model"]extra_share = (1.0 - _TEXT_STAGE_SHARE) / len(extras) if extras else 0.0offset = 0.0for stage in stages:share = _TEXT_STAGE_SHARE if stage == "text_model" else extra_shareif stage == current:- return max(0, min(100, round((offset + share * value) * 100)))+ return _pct(offset + share * value)offset += share- return max(0, min(100, round(value * 100)))+ return _pct(value)def _endpoint() -> "tuple[str, str] | None":- """(base_root, api_key) of the managed router, or None.-- Resolved through the endpoint module's ownership-guarded reader, not a raw state-file read: on- the shared stable port a foreign install's server answers /health for anyone, and a raw read- would attach this watcher to someone else's SSE stream. The dead-pid check is the ownership- proof.- """- try:- from hermes_cli.local_runtime.endpoint import _state_endpoint+ """(base_root, api_key) of the managed router via the ownership-guarded reader, or None."""+ from hermes_cli.local_runtime.endpoint import managed_root- state = _state_endpoint()- if state is None:- return None- base = 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 managed_root()def _apply_event(model: str, event: str, data: dict) -> None:with _lock:status = str(data.get("status", ""))- if event in ("status_change", "model_status") and status == "loading":+ if event in _LOAD_EVENTS and status == "loading":progress = data.get("progress") or {}stages = [str(s) for s in (progress.get("stages") or [])]current = str(progress.get("current", ""))@@ -78,18 +68,21 @@ def _apply_event(model: str, event: str, data: dict) -> None:entry["stage"] = currententry["value"] = float(value)entry["percent"] = _composite_percent(stages, current, float(value))- elif event in ("status_change", "model_status", "model_remove"):+ elif event in (*_LOAD_EVENTS, "model_remove") and status != "loading":# Any terminal status (loaded/unloaded/failed) ends the load.- if status != "loading":- _snapshot.pop(model, None)+ _snapshot.pop(model, None)+++def _clear_snapshot() -> None:+ with _lock:+ _snapshot.clear()def _watch() -> None:while True:endpoint = _endpoint()if endpoint is None:- with _lock:- _snapshot.clear()+ _clear_snapshot()time.sleep(_RECONNECT_DELAY_S)continuebase, key = endpoint@@ -119,10 +112,9 @@ def _watch() -> None:continueexcept Exception as exc: # noqa: BLE001 — watcher must never die loudlogger.debug("load-progress SSE reconnecting: %s", exc)- # Stream ended (router bounce, timeout, error): loading entries from- # the dead connection are unverifiable — drop rather than freeze.- with _lock:- _snapshot.clear()+ # Stream ended (router bounce, timeout, error): loading entries from the dead connection+ # are unverifiable — drop rather than freeze.+ _clear_snapshot()time.sleep(_RECONNECT_DELAY_S)@@ -136,8 +128,8 @@ def _ensure_watcher() -> None:def get_loading_progress() -> dict[str, dict]:- """{model_id: {"stage", "value", "percent"}} for models loading right- now. Empty when nothing is loading (or nothing is knowable)."""+ """{model_id: {"stage", "value", "percent"}} for models loading right now. Empty when+ nothing is loading (or nothing is knowable)."""_ensure_watcher()now = time.monotonic()with _lock:@@ -151,23 +143,20 @@ def get_prefill_progress(model: str) -> "dict | None":"""{"processed": tokens} while the managed server is prompt-processing for ``model``, or None(idle, decoding, unreachable, or foreign server).- llama-server's /slots exposes ``n_prompt_tokens_processed`` but no total, so callers supply the- denominator. The busiest processing slot wins: a parallel small request freezes its counter- during decode while a live prefill keeps climbing. One HTTP call per poll; every failure reads- as "no prefill" — garnish, never load-bearing.+ /slots exposes ``n_prompt_tokens_processed`` but no total, so callers supply the denominator.+ The busiest processing slot wins: a parallel small request freezes its counter during decode+ while a live prefill keeps climbing. One HTTP call per poll; every failure reads as "no+ prefill" — garnish, never load-bearing."""ep = _endpoint()if ep is None:return None- base, key = eptry:from urllib.parse import quote- req = urllib.request.Request(- f"{base}/slots?model={quote(model)}",- headers={"Authorization": f"Bearer {key}"})- with urllib.request.urlopen(req, timeout=2) as r:- slots = json.loads(r.read())+ from hermes_cli.local_runtime.endpoint import managed_get_json++ slots = managed_get_json(*ep, f"/slots?model={quote(model)}", timeout_s=2)except Exception: # noqa: BLE001return Nonebest = 0