Skip to content

The agent that grows with you

fix: restore branch work three origin/main merges dropped from doctor, photon and voice

ethernet9cfa6e502180
diff --git a/hermes_cli/doctor_state.py b/hermes_cli/doctor_state.py
index d577d97e167..552dc2f0c60 100644
--- a/hermes_cli/doctor_state.py
+++ b/hermes_cli/doctor_state.py
@@ -106,9 +106,84 @@ def _memory_store_flags(hermes_home: Path) -> tuple:
return get_builtin_memory_store_flags({"memory": _doctor_memory_config(hermes_home)})
+def check_legacy_desktop_checkout() -> None:
+ """Report the unused legacy checkout under an embedded desktop install.
+
+ Before the embedded runtime existed, the desktop app installed a git
+ checkout at $HERMES_HOME/hermes-agent. An embedded app never uses it,
+ so it sits on disk (1-2 GB of tree + venv). Doctor only REPORTS the
+ checkout and its size — it never suggests a deletion command, and
+ never deletes anything itself: a pristineness probe cannot prove no
+ other client uses the tree or that every local commit is published,
+ so the review-and-decide step belongs to the user.
+ """
+ from hermes_cli.steward import STEWARD_DESKTOP, sealed_steward
+
+ try:
+ from hermes_cli.main import PROJECT_ROOT
+ except Exception:
+ return
+
+ if sealed_steward(Path(PROJECT_ROOT)) != STEWARD_DESKTOP:
+ return
+
+ from hermes_cli.doctor import HERMES_HOME, _DHH
+
+ checkout = HERMES_HOME / "hermes-agent"
+ if not (checkout / ".git").exists():
+ return
+
+ _section("Legacy Desktop Checkout")
+
+ def _git(*args: str):
+ try:
+ return subprocess.run(
+ ["git", "-C", str(checkout), *args],
+ capture_output=True, text=True, encoding="utf-8", timeout=10,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return None
+
+ status = _git("status", "--porcelain")
+ branch = _git("rev-parse", "--abbrev-ref", "HEAD")
+ stashes = _git("stash", "list")
+
+ # Conservative pristineness: every probe must succeed AND come back
+ # clean. Any probe failure counts as "has local work".
+ pristine = (
+ status is not None and status.returncode == 0 and status.stdout.strip() == ""
+ and branch is not None and branch.returncode == 0 and branch.stdout.strip() == "main"
+ and stashes is not None and stashes.returncode == 0 and stashes.stdout.strip() == ""
+ )
+
+ size_note = ""
+ try:
+ total = sum(f.stat().st_size for f in checkout.rglob("*") if f.is_file())
+ size_note = f" (~{total / 1_000_000_000:.1f} GB)"
+ except OSError:
+ pass
+
+ if pristine:
+ check_warn(
+ f"Unused checkout at {_DHH}/hermes-agent{size_note}",
+ "(the desktop app runs embedded and does not use it; the tree is clean)",
+ )
+ print(" Review it and decide whether to keep or remove it — doctor does not delete anything.")
+ else:
+ check_info(
+ f"A checkout exists at {_DHH}/hermes-agent but holds local work "
+ "(changes, a branch, or stashes). The desktop app does not use "
+ "it; review it before you remove anything."
+ )
+
+
@doctor_check()
def _check_directory_structure(should_fix: bool, f: Finding) -> None:
"""HERMES_HOME, expected subdirs, SOUL.md, and the enabled built-in memory files."""
+ try:
+ check_legacy_desktop_checkout()
+ except Exception:
+ pass # best-effort report; must never break the directory check
from hermes_cli.doctor import HERMES_HOME, _DHH
hermes_home = HERMES_HOME
ensure_dir(f, should_fix, hermes_home, f"{_DHH} directory exists", f"Created {_DHH} directory", f"{_DHH} not found")
@@ -121,7 +196,7 @@ def _check_directory_structure(should_fix: bool, f: Finding) -> None:
# SOUL.md persona file
soul_path = hermes_home / "SOUL.md"
if soul_path.exists():
- lines = soul_path.read_text(encoding="utf-8").strip().splitlines()
+ lines = soul_path.read_text(encoding="utf-8-sig").strip().splitlines()
if any(l.strip() and not l.strip().startswith(("<!--", "-->", "#")) for l in lines):
check_ok(f"{_DHH}/SOUL.md exists (persona configured)")
else: # template comments only (no real content)
@@ -144,7 +219,7 @@ def _check_directory_structure(should_fix: bool, f: Finding) -> None:
f"{_DHH}/memories/ not found")
for fname in [n for on, n in ((_memory_enabled, "MEMORY.md"), (_user_profile_enabled, "USER.md")) if on and existed]:
if (memories_dir / fname).exists():
- check_ok(f"{fname} exists ({len((memories_dir / fname).read_text(encoding='utf-8').strip())} chars)")
+ check_ok(f"{fname} exists ({len((memories_dir / fname).read_text(encoding='utf-8-sig').strip())} chars)")
else:
check_info(f"{fname} not created yet (will be created when the agent first writes a memory)")
@@ -352,17 +427,59 @@ def _check_checkpoint_store(should_fix: bool, f: Finding) -> None:
check_warn(notice)
+def _plugin_provenance_rows(plugins_dir) -> list:
+ """Report local provenance using the update checker's admission rules."""
+ from hermes_cli.plugins_provenance import ProvenanceClass, plugins_provenance
+ from hermes_cli.plugins_updates import check_local_provenance
+
+ if plugins_dir is None or not Path(plugins_dir).is_dir():
+ return [("info", "No plugins directory yet (nothing to check provenance for)", "")]
+ try:
+ provenances = plugins_provenance(Path(plugins_dir))
+ except (OSError, ValueError, RuntimeError) as exc:
+ return [("warn", "Plugin provenance could not be read", str(exc))]
+ rows = []
+ for provenance in provenances:
+ result = check_local_provenance(provenance)
+ detail = result.needs_fixing or result.reason
+ if result.needs_fixing or provenance.klass is ProvenanceClass.DRIFT:
+ rows.append(("warn", f"Plugin '{provenance.name}': {detail}", ""))
+ elif provenance.klass is ProvenanceClass.MANUAL:
+ rows.append(("info", f"Plugin '{provenance.name}' installed manually", detail))
+ elif provenance.klass is ProvenanceClass.SELF_CLONED:
+ rows.append(("info", f"Plugin '{provenance.name}': self-cloned", detail))
+ else:
+ rows.append(("ok", f"Plugin '{provenance.name}': provenance in good standing", detail))
+ return rows or [("info", "No provenanced plugins found", "")]
+
+
+@doctor_check("")
+def _check_update_provenance(should_fix: bool, f: Finding) -> None:
+ """Inspect local plugin update provenance without network or writes."""
+ from hermes_constants import get_hermes_home
+
+ printers = {"warn": check_warn, "ok": check_ok, "info": lambda text, detail: check_info(f"{text} {detail}".rstrip())}
+ for kind, text, detail in _plugin_provenance_rows(get_hermes_home() / "plugins"):
+ printers[kind](text, detail)
+
+
def _gh_authenticated() -> bool:
"""Check if gh CLI is authenticated via token file or device flow.
- Plain ``gh auth status`` (exit code only): gh 2.98+ dropped the
- ``authenticated`` JSON field, so ``--json authenticated`` exits 1 even
- when logged in, and the doctor falsely reported "No GITHUB_TOKEN".
+ Plain ``gh auth status`` (exit code only): gh 2.98+ dropped the ``authenticated`` JSON
+ field, so ``--json authenticated`` exits 1 even when logged in. Availability is resolved
+ through shutil.which (the same probe every other doctor tool check uses); an OS-level
+ launch failure (a Store/MSIX shim, a deleted binary) reads as "not authenticated" rather
+ than crashing the Skills Hub check.
"""
+ from hermes_cli.doctor_tools import _safe_which
+
+ if not _safe_which("gh"):
+ return False
try:
result = subprocess.run(["gh", "auth", "status"], capture_output=True, timeout=10)
return result.returncode == 0
- except (FileNotFoundError, subprocess.TimeoutExpired):
+ except (OSError, subprocess.TimeoutExpired):
return False
@@ -375,7 +492,7 @@ def _check_skills_hub(should_fix: bool, f: Finding) -> None:
if lock_file.exists():
with warn_on_error("Lock file", "(corrupted or unreadable)"):
import json
- count = len(json.loads(lock_file.read_text(encoding="utf-8")).get("installed", {}))
+ count = len(json.loads(lock_file.read_text(encoding="utf-8-sig")).get("installed", {}))
check_ok(f"Lock file OK ({count} hub-installed skill(s))")
quarantine = hub_dir / "quarantine"
q_count = sum(1 for d in quarantine.iterdir() if d.is_dir()) if quarantine.exists() else 0
@@ -426,10 +543,10 @@ def _memory_provider_mem0(issues: list) -> None:
# provider -> (checker, ImportError row, ImportError issue, label for "check failed")
_MEMORY_PROVIDER_CHECKS = {
- "honcho": (_memory_provider_honcho, ("honcho-ai not installed", "pip install honcho-ai"),
- "Honcho is set as memory provider but honcho-ai is not installed", "Honcho"),
- "mem0": (_memory_provider_mem0, ("Mem0 plugin not loadable", "pip install mem0ai"),
- "Mem0 is set as memory provider but mem0ai is not installed", "Mem0"),
+ "honcho": (_memory_provider_honcho, ("honcho-ai not installed", "run hermes memory setup"),
+ "Honcho dependencies missing — run hermes memory setup, then restart Hermes", "Honcho"),
+ "mem0": (_memory_provider_mem0, ("Mem0 plugin not loadable", "run hermes memory setup"),
+ "Mem0 dependencies missing — run hermes memory setup, then restart Hermes", "Mem0"),
}
@@ -486,6 +603,6 @@ def _check_profiles(should_fix: bool, f: Finding) -> None:
if not wrapper.is_file():
continue
with warn_on_error(""):
- _m = _re.search(r"hermes -p (\S+)", wrapper.read_text(encoding="utf-8"))
+ _m = _re.search(r"hermes -p (\S+)", wrapper.read_text(encoding="utf-8-sig"))
if _m and not profile_exists(_m.group(1)):
check_warn(f"Orphan alias: {wrapper.name} → profile '{_m.group(1)}' no longer exists")
diff --git a/plugins/platforms/photon/adapter.py b/plugins/platforms/photon/adapter.py
index 05733baeea7..ee8962fc451 100644
--- a/plugins/platforms/photon/adapter.py
+++ b/plugins/platforms/photon/adapter.py
@@ -14,7 +14,6 @@ import logging
import os
import re
import secrets
-import shutil
import signal
import subprocess
import sys
@@ -52,6 +51,7 @@ from .auth import load_project_credentials
# mirror files. Tests monkeypatch sidecar_paths._SIDECAR_DIR.
from .sidecar_paths import _NPM_ERROR_LOG_MAX_CHARS, _lock_newer_than_install, _npm_error_log, _sidecar_dir
from .sidecar_paths import dir_writable as _dir_writable
+from hermes_constants import find_node_executable, with_hermes_node_path
import contextlib
logger = logging.getLogger(__name__)
@@ -115,7 +115,7 @@ def _write_runtime_record(port: int, token: str, pid: int) -> None:
def _read_runtime_record() -> Optional[Dict[str, Any]]:
try:
- raw = json.loads(_runtime_record_path().read_text(encoding="utf-8"))
+ raw = json.loads(_runtime_record_path().read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
return None
return raw if isinstance(raw, dict) else None
@@ -211,27 +211,52 @@ def _is_timeout_error(exc: BaseException) -> bool:
return "timeout" in type(exc).__name__.lower()
+
def check_requirements() -> bool:
- """Return True when both Python deps and the Node sidecar are available."""
+ """Report readiness or permission to prepare at connect; never provision here."""
+ from pm import lazy_installs_allowed
+
+ can_prepare = lazy_installs_allowed()
if not HTTPX_AVAILABLE:
logger.warning("photon: httpx not installed — pip install httpx")
return False
- node_bin = _get_scoped_secret("PHOTON_NODE_BIN") or "node"
- if not shutil.which(node_bin):
- logger.warning("photon: node binary '%s' not found on PATH", node_bin)
+ if not (_get_scoped_secret("PHOTON_NODE_BIN") or find_node_executable("node") or can_prepare):
+ logger.warning("photon: node binary not found on PATH, in the pm store, or via PHOTON_NODE_BIN")
return False
if not sidecar_deps_installed():
- # Self-install is possible at connect time (npm on PATH + writable sidecar dir):
- # report available so _start_sidecar cold-installs — hosted images have no CLI.
- if bool(shutil.which("npm")) and _dir_writable(_sidecar_dir()):
+ # spectrum-ts not installed yet, or node_modules/ was partially created
+ # by an aborted npm install (ENOSPC, network timeout, EACCES).
+ # Checking spectrum-ts presence — not just node_modules/ existence —
+ # prevents a false positive where an empty/broken node_modules/ dir
+ # causes check_requirements() to return True while the sidecar crashes
+ # at runtime with an unrelated-looking missing-module error.
+ #
+ # NS-606: if we can self-install at connect time — npm on PATH and
+ # the (resolved, possibly mirrored) sidecar dir is writable — report
+ # available so the gateway creates the adapter and ``_start_sidecar``
+ # cold-installs from the committed lockfile (on hosted images the
+ # user has no CLI to run `hermes photon setup`, so the connect path
+ # must self-heal). Otherwise keep returning False so
+ # `hermes setup` / status surface the missing-deps state.
+ if (find_node_executable("npm") or can_prepare) and _dir_writable(_sidecar_dir()):
return True
# DEBUG, not WARNING: normal pre-setup state, and check_fn is polled from hot paths.
npm_error = ""
with contextlib.suppress(OSError):
if _npm_error_log().exists():
- npm_error = _npm_error_log().read_text(encoding="utf-8").strip()[:_NPM_ERROR_LOG_MAX_CHARS]
- hint = f" (last npm error: {npm_error})" if npm_error else ""
- logger.debug("photon: spectrum-ts not installed at %s%s — run: hermes photon setup", _sidecar_dir(), hint)
+ npm_error = _npm_error_log().read_text(encoding="utf-8-sig").strip()[:_NPM_ERROR_LOG_MAX_CHARS]
+ if npm_error:
+ logger.debug(
+ "photon: spectrum-ts not installed at %s "
+ "(last npm error: %s) — run: hermes photon setup",
+ _sidecar_dir(),
+ npm_error,
+ )
+ else:
+ logger.debug(
+ "photon: spectrum-ts not installed at %s — run: hermes photon setup",
+ _sidecar_dir(),
+ )
return False
return True
@@ -243,18 +268,33 @@ def _sidecar_deps_stale() -> bool:
def _reinstall_sidecar_deps() -> None:
- """``npm ci`` (fallback ``npm install``); blocking, best-effort — on failure the stale
- deps stay and the readiness check reports the real error."""
- npm = shutil.which("npm")
- if not npm:
- logger.warning("[photon] cannot reinstall stale sidecar deps: npm not on PATH")
+ """Reinstall the sidecar's node_modules from the lockfile (blocking).
+
+ Mirrors ``hermes photon install-sidecar``: ``npm ci`` for an exact,
+ reproducible install, falling back to ``npm install`` if the lockfile is
+ missing or drifted. Runs the postinstall patch as part of the install.
+ Best-effort — a failure here just leaves the (stale) deps in place and the
+ normal ``_start_sidecar`` readiness check reports the real error.
+ """
+ import pm
+
+ try:
+ npm = find_node_executable("npm")
+ env = with_hermes_node_path()
+ if npm is None:
+ env = pm.ensure("npm").env
+ installed = pm.installed_package("npm")
+ assert installed is not None and installed.binary is not None
+ npm = str(installed.binary)
+ except pm.InstallError as exc:
+ logger.warning("[photon] cannot prepare sidecar dependencies: %s", exc)
return
from hermes_cli._subprocess_compat import windows_hide_flags # no console flash on Windows
def _run(verb: str) -> subprocess.CompletedProcess:
return subprocess.run( # noqa: S603
[npm, verb], cwd=str(_sidecar_dir()), capture_output=True, text=True, encoding="utf-8",
- errors="replace", check=False, timeout=_NPM_REINSTALL_TIMEOUT, creationflags=windows_hide_flags())
+ errors="replace", check=False, env=env, timeout=_NPM_REINSTALL_TIMEOUT, creationflags=windows_hide_flags())
try:
result = _run("ci")
if result.returncode != 0:
@@ -488,7 +528,7 @@ class PhotonAdapter(BasePlatformAdapter):
self._sidecar_token = _get_scoped_secret("PHOTON_SIDECAR_TOKEN") or secrets.token_hex(16)
autostart = str(_get_scoped_secret("PHOTON_SIDECAR_AUTOSTART", "true")).lower()
self._autostart_sidecar = autostart not in ("0", "false", "no")
- self._node_bin = _get_scoped_secret("PHOTON_NODE_BIN") or shutil.which("node") or "node"
+ self._node_bin = _get_scoped_secret("PHOTON_NODE_BIN") or find_node_executable("node")
# Presence watchdog (second layer behind the sidecar's own zombie-stream detection):
# respawns only when the sidecar's HTTP loop hangs; 10-min interval because shared
# lines are quiet for hours. Config key wins, then env; None-aware so 0 disables it.
@@ -908,7 +948,7 @@ class PhotonAdapter(BasePlatformAdapter):
subprocess.run, # noqa: S603
[self._node_bin, str(_sidecar_dir() / "patch-spectrum-mixed-attachments.mjs"), str(_sidecar_dir())],
capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=10, check=False,
- creationflags=hide_flags)
+ creationflags=hide_flags, env=with_hermes_node_path())
if patch.returncode != 0:
raise RuntimeError((patch.stderr or patch.stdout or "").strip())
if patch.stderr.strip():
@@ -917,9 +957,19 @@ class PhotonAdapter(BasePlatformAdapter):
logger.warning("[photon] failed to apply Spectrum mixed attachment patch: %s", exc)
async def _start_sidecar(self) -> None:
+ if self._node_bin is None:
+ import pm
+
+ try:
+ await asyncio.to_thread(pm.ensure, "node")
+ installed = pm.installed_package("node")
+ assert installed is not None and installed.binary is not None
+ self._node_bin = str(installed.binary)
+ except pm.InstallError as exc:
+ raise PhotonSidecarStartupError(str(exc), code="SIDECAR_NODE_MISSING", retryable=False) from exc
await self._ensure_sidecar_deps()
await self._reap_stale_sidecar()
- env = os.environ.copy()
+ env = with_hermes_node_path()
env.update({
"PHOTON_PROJECT_ID": self._project_id, "PHOTON_PROJECT_SECRET": self._project_secret,
"PHOTON_SIDECAR_PORT": str(self._sidecar_port), "PHOTON_SIDECAR_BIND": self._sidecar_bind,
@@ -933,11 +983,21 @@ class PhotonAdapter(BasePlatformAdapter):
[self._node_bin, str(_sidecar_dir() / "index.mjs")],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env,
start_new_session=(sys.platform != "win32"),
- creationflags=windows_hide_flags()) # CREATE_NO_WINDOW only (no DETACHED_PROCESS): pipes stay usable
- except FileNotFoundError as exc: # deterministic: retrying can never fix a missing binary
+ # Windows: run the persistent sidecar headless so it does not open
+ # (or leave) a visible console window. CREATE_NO_WINDOW only (no
+ # DETACHED_PROCESS) so the stdin/stdout pipes above stay usable.
+ creationflags=windows_hide_flags(),
+ )
+ except FileNotFoundError as exc:
+ # Deterministic: node isn't resolvable (pm store or PATH).
+ # Retrying can never fix a missing binary (OOF-153).
raise PhotonSidecarStartupError(
- f"node binary not found ({self._node_bin!r}) — install Node.js or set PHOTON_NODE_BIN: {exc}",
- code="SIDECAR_NODE_MISSING", retryable=False) from exc
+ f"node binary not found ({self._node_bin!r}) — install Node.js "
+ f"18+ or run `hermes pm install`: {exc}",
+ code="SIDECAR_NODE_MISSING",
+ retryable=False,
+ ) from exc
+ # Pump sidecar stderr/stdout into our logger so users see crashes.
loop = asyncio.get_event_loop()
self._sidecar_supervisor_task = loop.create_task(self._supervise_sidecar(self._sidecar_proc))
deadline = time.time() + 15.0 # wait for /healthz — up to 15s on cold start
diff --git a/tools/voice_mode.py b/tools/voice_mode.py
index b420132774f..6ce651b0ed3 100644
--- a/tools/voice_mode.py
+++ b/tools/voice_mode.py
@@ -1,7 +1,8 @@
"""Voice Mode -- push-to-talk recording and playback for the CLI.
Capture via sounddevice, WAV via stdlib wave, STT via tools.transcription_tools,
-playback via sounddevice or system players. Optional deps: ``uv sync --extra voice``.
+playback via sounddevice or system players. Optional deps: the ``audio-io`` / ``stt-whisper``
+extras, installed through PM (``hermes tools`` configures speech-to-text).
"""
import logging
@@ -113,18 +114,11 @@ def _default_input_samplerate(sd) -> int:
# ── Environment detection ──
def _voice_capture_install_hint() -> str:
- # sounddevice imports but PortAudio's shared library is missing — a pip install can't fix that; point at
- # the system package instead of misreporting missing Python packages (#18432).
+ # On Termux PortAudio is a system package a pip install can't provide (#18432); everywhere
+ # else the audio-io extra goes through PM so the install lands in the venv Hermes runs.
if _is_termux_environment():
return "pkg install python-numpy portaudio && python -m pip install sounddevice"
- # Inside a venv a bare `pip install` may hit whichever Python the shell
- # resolves first (macOS: often a Rosetta system Python) — use the venv's pip.
- with suppress(Exception):
- if sys.prefix != getattr(sys, "base_prefix", sys.prefix):
- pip_in_venv = Path(sys.prefix) / "bin" / "pip"
- if pip_in_venv.exists():
- return f"{pip_in_venv} install sounddevice numpy"
- return "pip install sounddevice numpy"
+ return "python -c \"from pm import sync_venv; sync_venv(['audio-io'], explicit=True)\""
def _portaudio_missing_message() -> str:
@@ -760,7 +754,7 @@ class AudioRecorder(_RecorderBase):
except ImportError as e:
raise RuntimeError(
"Voice mode requires sounddevice and numpy.\n"
- f"Install with: {sys.executable} -m pip install sounddevice numpy") from e
+ f"Install with: {_voice_capture_install_hint()}") from e
with self._lock:
if self._recording:
return
@@ -1490,9 +1484,8 @@ def check_voice_requirements() -> Dict[str, Any]:
else f"Audio capture: MISSING ({_voice_capture_install_hint()})",
"STT provider: DISABLED in config (stt.enabled: false)" if not stt_enabled
else f"STT provider: {stt_label}" if stt_label
- else ("STT provider: MISSING (uv pip install faster-whisper — "
- "`pip install faster-whisper` also works if pip is on PATH, "
- "or set GROQ_API_KEY / VOICE_TOOLS_OPENAI_KEY)"),
+ else ("STT provider: MISSING (run `hermes tools` and configure "
+ "Speech-to-Text: Local Whisper or a cloud provider)"),
]
details += [f"Environment: {w}" for w in env_check["warnings"]]
details += [f"Environment: {n}" for n in env_check.get("notices", [])]