Skip to content

The agent that grows with you

fix: an offline machine pays the Home Assistant plugin fetch once an hour, not every start

teknium1c26b88957c3f
diff --git a/hermes_cli/left_core_migration.py b/hermes_cli/left_core_migration.py
index bda2cb2812a..ba46de00f0e 100644
--- a/hermes_cli/left_core_migration.py
+++ b/hermes_cli/left_core_migration.py
@@ -9,6 +9,9 @@ reuses; memory is not a row because its plugin name comes from ``memory.provider
* ``hermes update`` installs the plugin for every profile home sharing the venv that uses the feature.
* Agent start and gateway start retry once per process for the active home (Desktop users update
through the app and never run ``hermes update``), honouring ``security.allow_lazy_installs``.
+* After a failed attempt (catalog miss or unreachable, failed install) starts skip the row for
+ :data:`STARTUP_RETRY_SECONDS`, so an offline machine pays the network round trip once, not on every
+ ``hermes chat``; ``hermes update`` always retries.
* A home gets the plugin automatically at most once (``_left_core_installed`` in its config.yaml):
``hermes plugins remove`` afterwards is the user's choice and sticks.
@@ -21,6 +24,7 @@ Desktop, chat); a gateway-start outcome waits for the home's first agent to deli
from __future__ import annotations
import logging
+import time
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Optional
@@ -213,11 +217,37 @@ def _record_migration(home: Path, feature: LeftCoreFeature) -> None:
atomic_config_write(path, config)
-def _pending(home: Path, *, say: Callable[[str], None], process_env: bool = False) -> list[LeftCoreFeature]:
+STARTUP_RETRY_SECONDS = 3600.0
+
+
+def _failure_stamp(home: Path, feature: LeftCoreFeature) -> Path:
+ """Touched on every failed automatic install; its mtime gates the next startup attempt."""
+ return home / "cache" / f"left-core-{feature.plugin}.failed"
+
+
+def _note_failure(home: Path, feature: LeftCoreFeature) -> None:
+ stamp = _failure_stamp(home, feature)
+ try:
+ stamp.parent.mkdir(parents=True, exist_ok=True)
+ stamp.touch()
+ except OSError as exc:
+ logger.debug("left-core retry stamp not written for %s: %s", home, exc)
+
+
+def _failed_recently(home: Path, feature: LeftCoreFeature) -> bool:
+ try:
+ return time.time() - _failure_stamp(home, feature).stat().st_mtime < STARTUP_RETRY_SECONDS
+ except OSError:
+ return False
+
+
+def _pending(home: Path, *, say: Callable[[str], None], process_env: bool = False,
+ backoff: bool = False) -> list[LeftCoreFeature]:
"""Rows *home* uses whose plugin it never had and that the catalog ships (a catalog miss is
reported through *say*). Converts the toolset scope of every row *home* uses once
(:func:`_record_migration`), installed or not; a row whose scope cannot be recorded is
- reported and skipped, never installed unscoped. A row marked installed is done for good."""
+ reported and skipped, never installed unscoped. A row marked installed is done for good.
+ *backoff* (startup) skips a row whose last attempt failed recently, before any network."""
from hermes_cli.memory_provider_migration import catalog_source
out = []
for feature in LEFT_CORE:
@@ -235,7 +265,12 @@ def _pending(home: Path, *, say: Callable[[str], None], process_env: bool = Fals
continue
if present:
continue
+ if backoff and _failed_recently(home, feature):
+ logger.info("%s plugin install failed recently for %s; retrying after %ds or on `hermes update`",
+ feature.label, home, STARTUP_RETRY_SECONDS)
+ continue
if catalog_source(feature.plugin) is None:
+ _note_failure(home, feature)
say(f" ⚠ {feature.label} moved out of core into the '{feature.plugin}' plugin, which this "
f"Hermes cannot find in the plugin catalog yet. Run `{_install_command(feature.plugin, home)}` "
f"once it is listed.")
@@ -257,6 +292,14 @@ def _install_into(home: Path) -> Callable[[str], dict]:
return _install
+def _first_cause(error: str) -> str:
+ """One line for a notice: git's own ``fatal:`` / ``error:`` line when *error* ends with raw git
+ stderr (a failed clone), else its first non-empty line."""
+ lines = [line.strip() for line in error.splitlines() if line.strip()]
+ cause = next((line.split(":", 1)[1].strip() for line in lines if line.startswith(("fatal:", "error:"))), None)
+ return (cause or (lines[0] if lines else "unknown error")).rstrip(". ")
+
+
def _install_one(home: Path, feature: LeftCoreFeature, *, install: Callable[[str], dict],
say: Callable[[str], None]) -> bool:
try:
@@ -271,7 +314,8 @@ def _install_one(home: Path, feature: LeftCoreFeature, *, install: Callable[[str
say(f" ✓ {feature.label} moved out of core — installed the '{feature.plugin}' plugin from the "
f"catalog ({feature.unchanged}).")
return True
- error = str(result.get("error") or "unknown error").rstrip(". ")
+ _note_failure(home, feature)
+ error = _first_cause(str(result.get("error") or ""))
say(f" ⚠ {feature.label} moved out of core and its '{feature.plugin}' plugin could not be installed "
f"automatically: {error}. Run `{_install_command(feature.plugin, home)}`.")
return False
@@ -373,7 +417,7 @@ def recover_at_startup(*, say: Optional[Callable[[str], None]] = None) -> list[s
deliver(message)
try:
- features = _pending(home, say=report, process_env=True)
+ features = _pending(home, say=report, process_env=True, backoff=True)
if not features:
return []
from pm.install import lazy_installs_allowed
diff --git a/tests/hermes_cli/test_left_core_migration.py b/tests/hermes_cli/test_left_core_migration.py
index c7f865c8961..443e853cc0b 100644
--- a/tests/hermes_cli/test_left_core_migration.py
+++ b/tests/hermes_cli/test_left_core_migration.py
@@ -251,3 +251,30 @@ def test_the_migration_installs_once_so_a_removal_sticks(tmp_path, monkeypatch):
monkeypatch.setattr(lcm, "_install_into", lambda h: install)
assert lcm.recover_at_startup(say=quiet) == []
assert calls == ["homeassistant"] and not plugin.exists()
+
+
+def test_a_failed_startup_install_backs_off_and_reports_one_line(tmp_path, monkeypatch):
+ """With the catalog or git unreachable, only the first agent start in a while pays the network
+ round trip, and its notice is one line naming the cause; `hermes update` always retries."""
+ import hermes_cli.memory_provider_migration as mpm
+ import pm.install
+ home = _home(tmp_path, env="HASS_TOKEN=abc\n")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr(pm.install, "lazy_installs_allowed", lambda: True)
+ lookups = []
+ monkeypatch.setattr(mpm, "catalog_source", lambda name: lookups.append(name) or name)
+ git_error = ("Could not download the plugin from https://github.com/x/y. Check the address.\n"
+ "Details: Cloning into '/h/plugins/.install-1'...\n"
+ "fatal: unable to access 'https://github.com/x/y/': Could not resolve host: github.com\n")
+ failing = lambda name: {"ok": False, "error": git_error} # noqa: E731
+ monkeypatch.setattr(lcm, "_install_into", lambda h: failing)
+ said = []
+ assert lcm.recover_at_startup(say=said.append) == []
+ assert len(said) == 1 and "\n" not in said[0] and "Could not resolve host: github.com" in said[0]
+ assert "plugins install homeassistant" in said[0]
+
+ lcm._attempted.clear() # the next `hermes chat` process
+ assert lcm.recover_at_startup(say=said.append) == []
+ assert lookups == ["homeassistant"] and len(said) == 1
+ assert lcm.migrate_home(home, install=failing, say=said.append) == []
+ assert lookups == ["homeassistant", "homeassistant"]
diff --git a/website/docs/user-guide/messaging/homeassistant.md b/website/docs/user-guide/messaging/homeassistant.md
index eb3f68ab165..de531cd9aae 100644
--- a/website/docs/user-guide/messaging/homeassistant.md
+++ b/website/docs/user-guide/messaging/homeassistant.md
@@ -27,7 +27,7 @@ hermes -p <profile> plugins install homeassistant
The plugin declares its own Python dependency (`aiohttp`), so there is no pip extra to install. The old `hermes-agent[homeassistant]` extra has been removed.
:::info Upgrading from a release that bundled Home Assistant
-Nothing to do. Every profile that was already using Home Assistant — `HASS_TOKEN` in its `.env`, `platforms.homeassistant` enabled (or given a `token`) in `config.yaml`, or the `homeassistant` toolset listed in `platform_toolsets` — gets the plugin installed automatically from the catalog by `hermes update` (for all profiles sharing the install). If that step could not run, Hermes installs it the first time the profile starts (agent or gateway start; this honours `security.allow_lazy_installs`). The outcome is reported in the terminal, the Desktop app and chat. This happens once per profile: if you later remove the plugin (`hermes plugins remove homeassistant`), it stays removed.
+Nothing to do. Every profile that was already using Home Assistant — `HASS_TOKEN` in its `.env`, `platforms.homeassistant` enabled (or given a `token`) in `config.yaml`, or the `homeassistant` toolset listed in `platform_toolsets` — gets the plugin installed automatically from the catalog by `hermes update` (for all profiles sharing the install). If that step could not run, Hermes installs it the first time the profile starts (agent or gateway start; this honours `security.allow_lazy_installs`). After a failed attempt (offline, catalog unreachable) starts retry at most once an hour; `hermes update` always retries. The outcome is reported in the terminal, the Desktop app and chat. This happens once per profile: if you later remove the plugin (`hermes plugins remove homeassistant`), it stays removed.
Your configuration carries over unchanged: the same `HASS_TOKEN` / `HASS_URL` variables, the same `homeassistant` platform name and `platforms.homeassistant` keys, the same `homeassistant` toolset and tool names, and the same cron `deliver: homeassistant:<notify target>` syntax. One difference: like every plugin tool, the `ha_*` tools sit behind [Tool Search](../features/tools.md) (`tool_search` / `tool_call`) when it is on, instead of being listed directly.
:::
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/messaging/homeassistant.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/messaging/homeassistant.md
index cce9db4a91f..5c289e4c401 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/messaging/homeassistant.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/messaging/homeassistant.md
@@ -27,7 +27,7 @@ hermes -p <profile> plugins install homeassistant
插件自行声明其 Python 依赖(`aiohttp`),因此无需安装 pip extra。旧的 `hermes-agent[homeassistant]` extra 已被移除。
:::info 从内置 Home Assistant 的版本升级
-无需任何操作。每个已在使用 Home Assistant 的 profile(`.env` 中有 `HASS_TOKEN`、`config.yaml` 中启用了 `platforms.homeassistant`(或为其设置了 `token`),或 `platform_toolsets` 中列出了 `homeassistant` 工具集)都会在 `hermes update` 时自动从插件目录安装该插件(覆盖共享同一安装的所有 profile)。若该步骤未能执行,Hermes 会在该 profile 首次启动时(agent 启动或 gateway 启动)安装插件,此行为遵循 `security.allow_lazy_installs`。安装结果会显示在终端、Desktop 应用和聊天中。每个 profile 只会自动安装一次:之后若你移除插件(`hermes plugins remove homeassistant`),它将保持移除状态。
+无需任何操作。每个已在使用 Home Assistant 的 profile(`.env` 中有 `HASS_TOKEN`、`config.yaml` 中启用了 `platforms.homeassistant`(或为其设置了 `token`),或 `platform_toolsets` 中列出了 `homeassistant` 工具集)都会在 `hermes update` 时自动从插件目录安装该插件(覆盖共享同一安装的所有 profile)。若该步骤未能执行,Hermes 会在该 profile 首次启动时(agent 启动或 gateway 启动)安装插件,此行为遵循 `security.allow_lazy_installs`。若某次尝试失败(离线、插件目录不可达),启动时最多每小时重试一次;`hermes update` 总会重试。安装结果会显示在终端、Desktop 应用和聊天中。每个 profile 只会自动安装一次:之后若你移除插件(`hermes plugins remove homeassistant`),它将保持移除状态。
您的配置保持不变:相同的 `HASS_TOKEN` / `HASS_URL` 变量、相同的 `homeassistant` 平台名称和 `platforms.homeassistant` 配置键、相同的 `homeassistant` 工具集和工具名称,以及相同的 cron `deliver: homeassistant:<notify target>` 语法。唯一的区别:与所有插件工具一样,启用 [Tool Search](../features/tools.md) 时,`ha_*` 工具通过 `tool_search` / `tool_call` 调用,而不是直接列出。
:::