The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: security + efficiency review fixes for salvaged PR #74379
kshitij8b243dff6226
diff --git a/agent/agent_init.py b/agent/agent_init.pyindex bca13243b88..68fa17b0dff 100644--- a/agent/agent_init.py+++ b/agent/agent_init.py@@ -1784,11 +1784,17 @@ def init_agent(if _mp and _mp.is_available():agent._memory_manager.add_provider(_mp)elif _mp is not None:- try:- _unavailable_reason = _mp.unavailable_reason()- except Exception:- _unavailable_reason = ""- _warn_memory_provider_unavailable(_mem_provider_name, _unavailable_reason)+ # Skip the (potentially expensive) unavailable_reason() call+ # if we've already warned for this provider β the gateway+ # builds a fresh AIAgent per message, so without this guard+ # unavailable_reason() (which reads config from disk and may+ # probe importlib) runs on every turn.+ if _mem_provider_name not in _warned_unavailable_providers:+ try:+ _unavailable_reason = _mp.unavailable_reason()+ except Exception:+ _unavailable_reason = ""+ _warn_memory_provider_unavailable(_mem_provider_name, _unavailable_reason)if agent._memory_manager.providers:_init_kwargs = {"session_id": agent.session_id,diff --git a/agent/memory_manager.py b/agent/memory_manager.pyindex 61a5182b8e4..6db0c60cf3e 100644--- a/agent/memory_manager.py+++ b/agent/memory_manager.py@@ -599,7 +599,7 @@ class MemoryManager:Call right after :meth:`prefetch_all` on the turn thread. Collects eachprovider's :meth:`MemoryProvider.recall_status` and renders a single- status string (e.g. ``"ποΈ Hindsight β recalled 3 memories"``) so the+ status string (e.g. ``"π§ Provider β recalled 3 memories"``) so theuser SEES memory was used regardless of whether the model mentions it.Returns ``""`` when no provider injected memory this turn β callers canemit the result unconditionally.diff --git a/agent/memory_provider.py b/agent/memory_provider.pyindex 6336e98c1d2..317ad73d5ae 100644--- a/agent/memory_provider.py+++ b/agent/memory_provider.py@@ -41,10 +41,9 @@ from typing import Any, Dict, List, Optionallogger = logging.getLogger(__name__)-# Default glyph for the deterministic memory indicators. Hindsight's brand mark-# is an eye (the logo is an eye ringed by graph nodes), so the terminal-safe-# stand-in for the logo is the eye emoji. Providers can override per-status.-INDICATOR_GLYPH = "ποΈ"+# Default glyph for the deterministic memory indicators. Providers override+# per-status with their own brand mark (e.g. Hindsight uses "ποΈ").+INDICATOR_GLYPH = "π§ "@dataclass(frozen=True)diff --git a/plugins/memory/hindsight/__init__.py b/plugins/memory/hindsight/__init__.pyindex 4ca3fed94ce..03632b98da7 100644--- a/plugins/memory/hindsight/__init__.py+++ b/plugins/memory/hindsight/__init__.py@@ -47,7 +47,7 @@ from typing import Any, Callable, Dict, List, Optionalfrom agent.secret_scope import get_secret-from agent.memory_provider import MemoryProvider, RecallStatus, INDICATOR_GLYPH+from agent.memory_provider import MemoryProvider, RecallStatusfrom hermes_constants import get_hermes_homefrom tools.registry import tool_errorfrom hermes_cli.config import cfg_get@@ -79,6 +79,9 @@ _DEFAULT_IDLE_TIMEOUT = 300 # seconds β Hindsight embedded daemon default# generic user-facing opt-in exists, so this stays unset unless the user sets it# via the ``retain_source`` config key or HINDSIGHT_RETAIN_SOURCE (e.g. "hermes")._DEFAULT_RETAIN_SOURCE = ""+# Hindsight brand mark β the logo is an eye ringed by graph nodes. Used for+# the deterministic recall/retain indicators (overrides the generic core default).+_HINDSIGHT_GLYPH = "ποΈ"# Mirrors hindsight-integrations/openclaw β Hindsight 0.5.0 added# `update_mode='append'` semantics on retain (vectorize-io/hindsight#932).# Without it, reusing a stable session-scoped document_id silently@@ -1942,7 +1945,7 @@ class HindsightMemoryProvider(MemoryProvider):"""if not self._recall_indicator or not self._last_recall_returned:return None- return RecallStatus(provider_label="Hindsight", count=self._last_recall_count)+ return RecallStatus(provider_label="Hindsight", count=self._last_recall_count, glyph=_HINDSIGHT_GLYPH)def queue_prefetch(self, query: str, *, session_id: str = "") -> None:# In synchronous mode prefetch() does a live recall each turn, so@@ -2160,7 +2163,7 @@ class HindsightMemoryProvider(MemoryProvider):if not self._retain_indicator or self._status_callback is None:returntry:- self._status_callback(f"{INDICATOR_GLYPH} Hindsight β saving to memoryβ¦")+ self._status_callback(f"{_HINDSIGHT_GLYPH} Hindsight β saving to memoryβ¦")except Exception:logger.debug("Retain indicator emit failed (non-fatal)", exc_info=True)diff --git a/plugins/memory/hindsight/templates.py b/plugins/memory/hindsight/templates.pyindex 5df72280259..f053b34c314 100644--- a/plugins/memory/hindsight/templates.py+++ b/plugins/memory/hindsight/templates.py@@ -18,6 +18,8 @@ import osimport urllib.requestfrom urllib.parse import urljoin+from hermes_cli.urllib_security import open_credentialed_url+logger = logging.getLogger(__name__)# The Bank Templates catalog lives in the Hindsight docs repo and is the same@@ -69,8 +71,8 @@ def apply_template(api_url: str, bank_id: str, api_key: str | None, manifest: diif api_key:headers["Authorization"] = f"Bearer {api_key}"req = urllib.request.Request(endpoint, data=data, headers=headers, method="POST") # noqa: S310- with urllib.request.urlopen(req, timeout=_HTTP_TIMEOUT) as resp: # noqa: S310- resp.read() # drain; urlopen raises HTTPError on non-2xx+ with open_credentialed_url(req, timeout=_HTTP_TIMEOUT) as resp:+ resp.read() # drain; open_credentialed_url raises HTTPError on non-2xxdef probe_existing_customization(api_url: str, bank_id: str, api_key: str | None) -> bool:@@ -86,7 +88,7 @@ def probe_existing_customization(api_url: str, bank_id: str, api_key: str | Noneheaders["Authorization"] = f"Bearer {api_key}"req = urllib.request.Request(endpoint, headers=headers) # noqa: S310try:- with urllib.request.urlopen(req, timeout=_HTTP_TIMEOUT) as resp: # noqa: S310+ with open_credentialed_url(req, timeout=_HTTP_TIMEOUT) as resp:data = json.loads(resp.read().decode("utf-8"))except Exception as e: # missing bank / network β treat as not customizedlogger.debug("Hindsight: bank customization probe skipped: %s", e)diff --git a/tests/agent/test_memory_recall_indicator.py b/tests/agent/test_memory_recall_indicator.pyindex f4f43d30775..4179ea6f2cc 100644--- a/tests/agent/test_memory_recall_indicator.py+++ b/tests/agent/test_memory_recall_indicator.py@@ -1,7 +1,7 @@"""MemoryManager.describe_recall β the deterministic recall indicator.When auto-recall injects memory, Hermes surfaces a model-independent-"ποΈ <provider> β recalled N memories" status line so the user SEES memory+"π§ <provider> β recalled N memories" status line so the user SEES memoryworking regardless of whether the model chooses to mention it. These testslock the formatting (singular/plural/generic) and the aggregation acrossproviders, all deterministically (no LLM, no network).@@ -55,20 +55,20 @@ def test_no_providers_returns_empty_string():def test_single_memory_is_singular():mgr = MemoryManager()mgr.add_provider(_FakeProvider("hindsight", RecallStatus("Hindsight", 1)))- assert mgr.describe_recall() == "ποΈ Hindsight β recalled 1 memory"+ assert mgr.describe_recall() == "π§ Hindsight β recalled 1 memory"def test_multiple_memories_are_plural():mgr = MemoryManager()mgr.add_provider(_FakeProvider("hindsight", RecallStatus("Hindsight", 3)))- assert mgr.describe_recall() == "ποΈ Hindsight β recalled 3 memories"+ assert mgr.describe_recall() == "π§ Hindsight β recalled 3 memories"def test_zero_count_renders_generic():# count 0 = content injected but no discrete count (e.g. reflect synthesis).mgr = MemoryManager()mgr.add_provider(_FakeProvider("hindsight", RecallStatus("Hindsight", 0)))- assert mgr.describe_recall() == "ποΈ Hindsight β recalled relevant memory"+ assert mgr.describe_recall() == "π§ Hindsight β recalled relevant memory"def test_aggregates_multiple_providers():@@ -78,8 +78,8 @@ def test_aggregates_multiple_providers():mgr.add_provider(_FakeProvider("builtin", RecallStatus("Notes", 2)))mgr.add_provider(_FakeProvider("hindsight", RecallStatus("Hindsight", 5)))result = mgr.describe_recall()- assert "ποΈ Notes β recalled 2 memories" in result- assert "ποΈ Hindsight β recalled 5 memories" in result+ assert "π§ Notes β recalled 2 memories" in result+ assert "π§ Hindsight β recalled 5 memories" in resultdef test_failing_provider_is_skipped_not_fatal():@@ -87,4 +87,4 @@ def test_failing_provider_is_skipped_not_fatal():mgr.add_provider(_FakeProvider("builtin", None, raises=True))mgr.add_provider(_FakeProvider("hindsight", RecallStatus("Hindsight", 1)))# The raising provider is swallowed; the healthy one still surfaces.- assert mgr.describe_recall() == "ποΈ Hindsight β recalled 1 memory"+ assert mgr.describe_recall() == "π§ Hindsight β recalled 1 memory"diff --git a/tests/plugins/memory/test_hindsight_templates.py b/tests/plugins/memory/test_hindsight_templates.pyindex 32bc9d3013a..bad225080b7 100644--- a/tests/plugins/memory/test_hindsight_templates.py+++ b/tests/plugins/memory/test_hindsight_templates.py@@ -46,7 +46,7 @@ def test_apply_template_posts_to_import_endpoint(monkeypatch):captured = {}@contextmanager- def _fake_urlopen(req, timeout=None):+ def _fake_open(req, timeout=None):captured["url"] = req.full_urlcaptured["method"] = req.get_method()captured["auth"] = req.get_header("Authorization")@@ -58,7 +58,7 @@ def test_apply_template_posts_to_import_endpoint(monkeypatch):yield _Resp()- monkeypatch.setattr(tpl.urllib.request, "urlopen", _fake_urlopen)+ monkeypatch.setattr(tpl, "open_credentialed_url", _fake_open)tpl.apply_template("https://api.hindsight.vectorize.io/", "hermes", "hsk_abc", {"version": "1"})assert captured["url"] == "https://api.hindsight.vectorize.io/v1/default/banks/hermes/import"@@ -71,7 +71,7 @@ def test_apply_template_omits_auth_when_no_key(monkeypatch):captured = {}@contextmanager- def _fake_urlopen(req, timeout=None):+ def _fake_open(req, timeout=None):captured["auth"] = req.get_header("Authorization")class _Resp:@@ -80,7 +80,7 @@ def test_apply_template_omits_auth_when_no_key(monkeypatch):yield _Resp()- monkeypatch.setattr(tpl.urllib.request, "urlopen", _fake_urlopen)+ monkeypatch.setattr(tpl, "open_credentialed_url", _fake_open)tpl.apply_template("http://localhost:8888", "hermes", None, {"version": "1"})assert captured["auth"] is None@@ -184,7 +184,7 @@ def test_run_template_step_swallows_apply_errors(monkeypatch):assert any("Could not apply" in line for line in logs)-def _fake_urlopen(payload):+def _fake_open(payload):@contextmanagerdef _cm(req, timeout=None):class _Resp:@@ -197,14 +197,14 @@ def _fake_urlopen(payload):def test_probe_existing_customization_true_when_bank_has_config(monkeypatch):- monkeypatch.setattr(tpl.urllib.request, "urlopen",- _fake_urlopen({"version": "1", "bank": {"reflect_mission": "x"}}))+ monkeypatch.setattr(tpl, "open_credentialed_url",+ _fake_open({"version": "1", "bank": {"reflect_mission": "x"}}))assert tpl.probe_existing_customization("https://api", "hermes", "k") is Truedef test_probe_existing_customization_false_when_empty(monkeypatch):- monkeypatch.setattr(tpl.urllib.request, "urlopen",- _fake_urlopen({"version": "1"}))+ monkeypatch.setattr(tpl, "open_credentialed_url",+ _fake_open({"version": "1"}))assert tpl.probe_existing_customization("https://api", "hermes", "k") is False@@ -212,7 +212,7 @@ def test_probe_existing_customization_false_on_error(monkeypatch):def _boom(req, timeout=None):raise OSError("no bank")- monkeypatch.setattr(tpl.urllib.request, "urlopen", _boom)+ monkeypatch.setattr(tpl, "open_credentialed_url", _boom)assert tpl.probe_existing_customization("https://api", "missing", None) is False