Skip to content

The agent that grows with you

feat(cli): local models in `hermes model`

emozilla400cd6926133
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index adbcd7d8872..79e53a53122 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -788,6 +788,7 @@ from hermes_cli.model_setup_flows import (
_model_flow_plugin_provider,
_is_profile_plugin_flow_provider,
)
+from hermes_cli.model_setup_flows_local import _model_flow_local
logger = logging.getLogger(__name__)
from hermes_cli.main_agent_cmds import (
cmd_acp,
@@ -2020,6 +2021,7 @@ _PROVIDER_MODEL_FLOWS = {
"copilot-acp": lambda c, m, a: _model_flow_copilot_acp(c, m),
"copilot": lambda c, m, a: _model_flow_copilot(c, m),
"custom": lambda c, m, a: _model_flow_custom(c),
+ "llamacpp": lambda c, m, a: _model_flow_local(c, m),
"anthropic": lambda c, m, a: _model_flow_anthropic(c, m),
"kimi-coding": lambda c, m, a: _model_flow_kimi(c, m),
"stepfun": lambda c, m, a: _model_flow_stepfun(c, m),
diff --git a/hermes_cli/main_provider_setup.py b/hermes_cli/main_provider_setup.py
index a1878344d6f..53982c82b4d 100644
--- a/hermes_cli/main_provider_setup.py
+++ b/hermes_cli/main_provider_setup.py
@@ -937,6 +937,11 @@ def _build_provider_picker_rows(config: dict, active: str, provider_labels: dict
_add(key, f"{provider_info['name']} ({_short_url(provider_info['base_url'])}){model_hint}", [],
bool(active) and key == active)
+ from hermes_cli.model_setup_flows_local import local_models_available
+ from hermes_cli.providers import LLAMACPP_ALIASES
+ if not _cli_excluded & set(LLAMACPP_ALIASES) and local_models_available():
+ _add("llamacpp", "Local models (run open models on this machine — no account or API key)", [],
+ active == "llamacpp")
ordered.append(("custom", "Custom endpoint (enter URL manually)", []))
if isinstance(config.get("custom_providers"), list) and config.get("custom_providers"):
ordered.append(("remove-custom", "Remove a saved custom provider", []))
diff --git a/hermes_cli/model_setup_flows_local.py b/hermes_cli/model_setup_flows_local.py
new file mode 100644
index 00000000000..b88bc6807dc
--- /dev/null
+++ b/hermes_cli/model_setup_flows_local.py
@@ -0,0 +1,188 @@
+"""``hermes model`` → Local models: the desktop's Local Models setup, in the terminal.
+
+The flow drives the handlers behind the desktop's Local Models pane
+(``hermes_cli/web_routers/local_models.py``) in-process, so both surfaces run one code path:
+the catalog priced for this machine, quickstart (pinned engine via PM, model download, server
+start, default assignment) and activate for a model already on disk. Progress renders from the
+same job view the desktop polls; Ctrl+C pauses a download, and the next run resumes from the
+bytes already on disk.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import time
+
+_POLL_S = 0.2
+_PAUSE_WAIT_S = 15.0
+
+
+def local_models_available() -> bool:
+ """Whether PM pins an engine for this machine at all. CPU is pinned on every target that has
+ any build, so its absence means no backend can install; GPU detection waits for selection."""
+ try:
+ from hermes_cli.local_runtime.binaries import unavailable_reason
+
+ return unavailable_reason("cpu") is None
+ except Exception:
+ return False
+
+
+def _fmt_eta(seconds: int) -> str:
+ minutes, secs = divmod(int(seconds), 60)
+ return f"{minutes}m{secs:02d}s" if minutes else f"{secs}s"
+
+
+def _rate(bytes_per_sec: float) -> str:
+ mb = bytes_per_sec / (1 << 20)
+ return f"{mb / 1024:.1f} GB/s" if mb >= 1024 else f"{mb:.0f} MB/s" if mb >= 10 else f"{mb:.1f} MB/s"
+
+
+def _progress_line(lm, view: dict) -> str:
+ line = f" {view.get('detail') or 'Starting'}"
+ if view.get("phase") not in lm._DOWNLOAD_PHASES:
+ return line # bytes stay on the job after the transfer; later steps show no counter
+ total = view.get("total_bytes")
+ if total:
+ line += f" {view.get('percent', 0)}% {lm._human_gb(view.get('done_bytes') or 0)} / {lm._human_gb(total)}"
+ if view.get("bytes_per_sec"):
+ line += f" {_rate(view['bytes_per_sec'])}"
+ if view.get("eta_seconds") is not None:
+ line += f" ~{_fmt_eta(view['eta_seconds'])} left"
+ return line
+
+
+def _follow_job(lm, job_id: str) -> str:
+ """Render a job until it settles; returns its terminal status. Ctrl+C pauses a pausable
+ phase (the downloader keeps finished bytes) and stops following anything else."""
+ shown_phase, width = None, 0
+ try:
+ while True:
+ with lm._JOBS_LOCK:
+ view = lm._job_view(lm._JOBS[job_id])
+ if view["status"] != "running":
+ break
+ if view["phase"] != shown_phase:
+ if shown_phase is not None:
+ print()
+ shown_phase, width = view["phase"], 0
+ line = _progress_line(lm, view)
+ print(f"\r{line}{' ' * max(0, width - len(line))}", end="", flush=True)
+ width = len(line)
+ time.sleep(_POLL_S)
+ except KeyboardInterrupt:
+ print()
+ running = lm._RUNNING.get(job_id, {})
+ with lm._JOBS_LOCK:
+ pausable = lm._job_view(lm._JOBS[job_id])["can_pause"]
+ if not pausable or running.get("pause") is None:
+ print(" Stopped following. Setup continues only while this process runs.")
+ return "interrupted"
+ running["pause"].set()
+ deadline = time.monotonic() + _PAUSE_WAIT_S
+ while time.monotonic() < deadline and lm._JOBS[job_id]["status"] == "running":
+ time.sleep(_POLL_S)
+ print(" Paused. Run `hermes model` → Local models again to resume; finished bytes are kept.")
+ return "paused"
+ if shown_phase is not None:
+ print()
+ if view["status"] == "error":
+ print(f" ✗ {view.get('error') or 'Setup failed'}")
+ elif view["status"] == "done":
+ print(f" ✓ {view.get('detail')}")
+ return view["status"]
+
+
+def _start(lm, start) -> str | None:
+ """Run a route handler that starts a job; its HTTP refusal becomes a printed line."""
+ from fastapi import HTTPException
+
+ try:
+ result = start()
+ if asyncio.iscoroutine(result):
+ result = asyncio.run(result)
+ except HTTPException as exc:
+ print(f" ✗ {exc.detail}")
+ return None
+ return result.get("job_id")
+
+
+def _row_label(row: dict, active_id: str | None) -> str:
+ label = f"{'★ ' if row.get('recommended') else ' '}{row['display_name']} ({row['size_label']}"
+ label += ", downloaded)" if row.get("downloaded") else ")"
+ label += f" — {row.get('fit_summary', '')}"
+ if active_id and active_id in (row.get("downloaded_model_id"), row.get("model_id")):
+ label += " ← currently active"
+ return label
+
+
+def _model_flow_local(config, current_model=""):
+ """Pick a catalog model sized for this machine (or one already on disk) and make it the default,
+ installing the pinned engine and downloading the model as needed."""
+ del config, current_model
+ from hermes_cli.main_provider_setup import _prompt_provider_choice
+ from hermes_cli.setup import prompt_yes_no
+ from hermes_cli.web_routers import local_models as lm
+
+ hw = lm.local_models_hardware()
+ status = lm.local_models_status()
+ gpu = f"{hw['gpu_name']} · " if hw.get("gpu_name") else ""
+ print(f" Machine: {gpu}{hw.get('vram_label')} {'unified' if hw.get('uma') else 'GPU'} memory · "
+ f"{lm._human_gb(hw.get('ram_total_bytes') or 0)} RAM")
+ if status["runtime_installed"]:
+ print(f" Engine: llama.cpp {status['tag']} ({status['runtime_backend']})"
+ + (" (update available)" if status.get("update_available") else ""))
+ else:
+ print(f" Engine: not installed; llama.cpp {status['configured_tag']} installs with your first model")
+ print()
+
+ rows = lm.local_models_catalog()["models"]
+ choices = [r for r in rows if r.get("fits") and not r.get("needs_engine")]
+ catalog_ids = {r.get("downloaded_model_id") for r in rows}
+ staged = [m for m in status["models"] if m["id"] not in catalog_ids]
+ active_id = status.get("active_model_id")
+ labels = [_row_label(r, active_id) for r in choices]
+ labels += [f" {m['id']} — {m['size_label']} · on disk" + (" ← currently active" if m["id"] == active_id else "")
+ for m in staged]
+ labels.append("Leave unchanged")
+ skipped = len(rows) - len(choices)
+ if skipped:
+ print(f" {skipped} catalog model(s) need more memory or a newer engine than this machine has.")
+ default = next((i for i, r in enumerate(choices)
+ if active_id and active_id in (r.get("downloaded_model_id"), r.get("model_id"))),
+ next((i for i, r in enumerate(choices) if r.get("recommended")), 0))
+ idx = _prompt_provider_choice(labels, default=default, title="Select a local model (★ recommended for this machine):")
+ if idx is None or idx == len(labels) - 1:
+ print("No change.")
+ return
+
+ if idx < len(choices):
+ row = choices[idx]
+ name, use_downloaded = row["display_name"], row.get("downloaded") and status["runtime_installed"]
+ if not use_downloaded:
+ need = [] if status["runtime_installed"] else [f"the llama.cpp engine ({status['configured_tag']})"]
+ if not row.get("downloaded"):
+ need.append(f"{name} ({row['size_label']})")
+ if need and not prompt_yes_no(f" Download {' and '.join(need)}?", True):
+ print("No change.")
+ return
+ job_id = _start(lm, lambda: lm.local_models_quickstart(lm.QuickstartBody(model_id=row["id"])))
+ if job_id is None or _follow_job(lm, job_id) != "done":
+ return
+ print(f"Default model set to: {name} (via Local models · llama.cpp)")
+ return
+ model_id = row["downloaded_model_id"]
+ else:
+ model_id = staged[idx - len(choices)]["id"]
+ name = model_id
+
+ if not status["runtime_installed"]:
+ if not prompt_yes_no(f" Download the llama.cpp engine ({status['configured_tag']})?", True):
+ print("No change.")
+ return
+ job_id = _start(lm, lambda: lm.local_models_runtime_install(lm.RuntimeInstallBody()))
+ if job_id is None or _follow_job(lm, job_id) != "done":
+ return
+ job_id = _start(lm, lambda: lm.local_models_activate(lm.ModelActivateBody(model_id=model_id)))
+ if job_id is not None and _follow_job(lm, job_id) == "done":
+ print(f"Default model set to: {name} (via Local models · llama.cpp)")
diff --git a/tests/hermes_cli/test_model_flow_local.py b/tests/hermes_cli/test_model_flow_local.py
new file mode 100644
index 00000000000..fdd9c8a6ec3
--- /dev/null
+++ b/tests/hermes_cli/test_model_flow_local.py
@@ -0,0 +1,62 @@
+"""``hermes model`` → Local models runs the desktop's Local Models setup in the terminal."""
+
+from __future__ import annotations
+
+import pytest
+
+
+def _picker_keys(config: dict) -> list[str]:
+ from hermes_cli.main_provider_setup import _build_provider_picker_rows
+
+ return [key for key, _, _ in _build_provider_picker_rows(config, "", {}, {})[0]]
+
+
+def test_local_models_row_follows_the_engine_pin_and_exclusions():
+ from hermes_cli.local_runtime import binaries
+
+ assert ("llamacpp" in _picker_keys({})) == (binaries.unavailable_reason("cpu") is None)
+ assert "llamacpp" not in _picker_keys({"model_catalog": {"excluded_providers": ["llama.cpp"]}})
+
+
[email protected]("outcome", ["done", "error"])
+def test_picked_model_runs_the_quickstart_job_and_reports_how_it_ended(monkeypatch, capsys, outcome):
+ """The CLI starts the same quickstart job the desktop's button does and reports that job's
+ terminal state; only a finished job claims the default changed."""
+ import hermes_cli.main_provider_setup as provider_setup
+ import hermes_cli.setup as setup
+ from hermes_cli.model_setup_flows_local import _model_flow_local
+ from hermes_cli.web_routers import local_models as lm
+
+ row = {"id": "tiny", "display_name": "Tiny", "fits": True, "needs_engine": False, "recommended": True,
+ "downloaded": False, "size_label": "1.0 GB", "fit_summary": "runs fully on your GPU"}
+ monkeypatch.setattr(lm, "local_models_hardware", lambda: {"gpu_name": "GPU", "vram_label": "8.0 GB"})
+ monkeypatch.setattr(lm, "local_models_status", lambda: {
+ "runtime_installed": True, "tag": "b1", "runtime_backend": "cpu", "models": [], "active_model_id": None})
+ monkeypatch.setattr(lm, "local_models_catalog", lambda: {"models": [row]})
+ started = []
+
+ def quickstart(body):
+ started.append(body.model_id)
+ job = lm._job("quickstart", "Tiny", model_id=body.model_id)
+
+ def run():
+ lm._step(job, "downloading", "Downloading Tiny")
+ if outcome == "error":
+ raise RuntimeError("disk full")
+ lm._finish(job, "Tiny is ready — new chats use it")
+
+ lm._spawn_job(job, "test-quickstart", run, resumable=True)
+ return {"job_id": job["job_id"]}
+
+ monkeypatch.setattr(lm, "local_models_quickstart", quickstart)
+ monkeypatch.setattr(provider_setup, "_prompt_provider_choice", lambda labels, default=0, title="": default)
+ monkeypatch.setattr(setup, "prompt_yes_no", lambda question, default=True: True)
+
+ _model_flow_local({}, "")
+
+ out = capsys.readouterr().out
+ assert started == ["tiny"]
+ if outcome == "done":
+ assert "✓ Tiny is ready" in out and "Default model set to: Tiny" in out
+ else:
+ assert "✗ disk full" in out and "Default model set to" not in out
diff --git a/website/docs/user-guide/local-models.md b/website/docs/user-guide/local-models.md
index b66df317e10..330f0a61990 100644
--- a/website/docs/user-guide/local-models.md
+++ b/website/docs/user-guide/local-models.md
@@ -50,6 +50,12 @@ That's the whole flow. The server starts and stops with Hermes, restarts
survive app restarts, and switching back to a cloud provider is one click
in the model picker.
+From a terminal, `hermes model` → **Local models** runs the same setup: it
+lists the catalog priced for your machine (★ marks the recommendation),
+installs the pinned engine, downloads the model with live progress, starts
+the server, and makes the model your default. Models already on disk are
+offered too. Ctrl+C pauses a download; choosing the model again resumes it.
+
## How Hermes picks what to download
Every model in the catalog is priced against **your machine** before you