The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent/providers): shared ProviderBase/CatalogProviderBase and provider_media; compact contract docs
Teknium8dcb2b6ada7b
diff --git a/agent/browser_provider.py b/agent/browser_provider.pyindex d7c6dae61fb..1ea59a40a35 100644--- a/agent/browser_provider.py+++ b/agent/browser_provider.py@@ -2,25 +2,15 @@Browser Provider ABC====================-Defines the pluggable-backend interface for cloud browser providers-(Browserbase, Browser Use, Firecrawl, …). Providers register instances via-:meth:`PluginContext.register_browser_provider`; the active one (selected via+Pluggable-backend interface for cloud browser providers (Browserbase, Browser+Use, Firecrawl, …). Providers register via+:meth:`PluginContext.register_browser_provider`; the active one (selected by``browser.cloud_provider`` in ``config.yaml``) services every cloud-mode-``browser_*`` tool call.+``browser_*`` tool call. Providers live in ``<repo>/plugins/browser/<name>/``+(built-in) or ``~/.hermes/plugins/browser/<name>/`` (user, opt-in).-Providers live in ``<repo>/plugins/browser/<name>/`` (built-in, auto-loaded as-``kind: backend``) or ``~/.hermes/plugins/browser/<name>/`` (user, opt-in via-``plugins.enabled``).--This ABC mirrors :class:`agent.web_search_provider.WebSearchProvider` (PR-#25182) — same shape, same registration flow, same picker integration. The-legacy in-tree ``tools.browser_providers.base.CloudBrowserProvider`` ABC was-deleted in PR #25214 (this work) along with the per-vendor inline modules in-``tools/browser_providers/``; the lifecycle contract documented below is-preserved bit-for-bit so the tool wrapper (:mod:`tools.browser_tool`) does-not have to translate.--Session metadata contract (preserved from the legacy ``CloudBrowserProvider``)::+Session metadata contract (preserved from the legacy ``CloudBrowserProvider``+so :mod:`tools.browser_tool` needs no translation)::{"session_name": str, # unique name for agent-browser --session@@ -31,79 +21,41 @@ Session metadata contract (preserved from the legacy ``CloudBrowserProvider``)::"external_call_id": str, # optional, managed-gateway billing key}-``bb_session_id`` is a legacy key name kept verbatim for backward compat with-:mod:`tools.browser_tool` — it holds the provider's session ID regardless of-which provider is in use.+``bb_session_id`` is a legacy key name kept verbatim for backward compat — it+holds the provider's session ID regardless of which provider is in use."""from __future__ import annotationsimport abc-from typing import Any, Dict, Optional+from typing import Dict+from agent.provider_base import ProviderBase-# ----------------------------------------------------------------------------# ABC-# -----------------------------------------------------------------------------class BrowserProvider(abc.ABC):+class BrowserProvider(ProviderBase):"""Abstract base class for a cloud browser backend.- Subclasses must implement :meth:`name`, :meth:`is_available`, and the- three lifecycle methods: :meth:`create_session`, :meth:`close_session`,- :meth:`emergency_cleanup`.-- The lifecycle shape preserves the legacy ``CloudBrowserProvider`` contract- bit-for-bit so the dispatcher in :mod:`tools.browser_tool` is a pure- registry lookup — no per-provider conditionals, no shape translation.+ Subclasses implement :attr:`name` (the ``browser.cloud_provider`` value,+ e.g. ``browserbase``, ``browser-use``, ``firecrawl``), :meth:`is_available`,+ and the lifecycle trio :meth:`create_session` / :meth:`close_session` /+ :meth:`emergency_cleanup`. ``get_setup_schema`` may add ``"post_setup"``+ (e.g. ``"agent_browser"``) to trigger the install hook."""- @property- @abc.abstractmethod- def name(self) -> str:- """Stable short identifier used in the ``browser.cloud_provider``- config key.-- Lowercase, hyphens permitted to preserve existing user-visible names.- Examples: ``browserbase``, ``browser-use``, ``firecrawl``.- """-- @property- def display_name(self) -> str:- """Human-readable label shown in ``hermes tools``. Defaults to ``name``."""- return self.name-@abc.abstractmethoddef is_available(self) -> bool:- """Return True when this provider can service calls.-- Typically a cheap check (env var present, managed-gateway token- readable, optional Python dep importable). Must NOT make network- calls — this runs at tool-registration time and on every- ``hermes tools`` paint.+ """True when this provider can service calls.- Mirrors the legacy ``CloudBrowserProvider.is_configured()`` method;- renamed for parity with :class:`agent.web_search_provider.WebSearchProvider`.+ Cheap check only (env var present, managed-gateway token readable, dep+ importable) — must NOT make network calls; runs at tool-registration+ time and on every ``hermes tools`` paint."""@abc.abstractmethoddef create_session(self, task_id: str) -> Dict[str, object]:- """Create a cloud browser session and return session metadata.-- Must return a dict with at least::-- {- "session_name": str, # unique name for agent-browser --session- "bb_session_id": str, # provider session ID (for close/cleanup)- "cdp_url": str, # CDP websocket URL- "expires_at": str, # optional provider-authoritative ISO timestamp- "features": dict, # feature flags that were enabled- }-- ``bb_session_id`` is a legacy key name kept for backward compat with- the rest of :mod:`tools.browser_tool` — it holds the provider's- session ID regardless of which provider is in use.+ """Create a cloud browser session and return the session metadata dict+ described in the module docstring.May raise ``ValueError`` (missing credentials) or ``RuntimeError``(network / API failure); the dispatcher surfaces these to the user.@@ -111,62 +63,19 @@ class BrowserProvider(abc.ABC):@abc.abstractmethoddef close_session(self, session_id: str) -> bool:- """Release / terminate a cloud session by its provider session ID.+ """Release a cloud session by provider session ID.Returns True on success, False on failure. Should not raise — log and- return False on any exception so the dispatcher's cleanup loop keeps- moving across sessions.+ return False so the dispatcher's cleanup loop keeps moving."""@abc.abstractmethoddef emergency_cleanup(self, session_id: str) -> None:- """Best-effort session teardown during process exit.-- Called from atexit / signal handlers. Must tolerate missing- credentials, network errors, etc. — log and move on. Must not raise.- """+ """Best-effort teardown from atexit / signal handlers. Must tolerate+ missing credentials and network errors; must not raise."""- def get_setup_schema(self) -> Optional[Dict[str, Any]]:- """Return provider metadata for the ``hermes tools`` picker.-- Used by :mod:`hermes_cli.tools_config` to inject this provider as a- row in the Browser Automation picker. Shape mirrors the existing- hardcoded entries in ``TOOL_CATEGORIES["browser"]``::-- {- "name": "Browserbase",- "badge": "paid",- "tag": "Cloud browser with stealth and proxies",- "env_vars": [- {"key": "BROWSERBASE_API_KEY",- "prompt": "Browserbase API key",- "url": "https://browserbase.com"},- ],- "post_setup": "agent_browser",- }-- Default: minimal entry derived from :attr:`display_name`. Override to- expose API key prompts, badges, managed-Nous gating, and the- ``post_setup`` install hook.- """- return {- "name": self.display_name,- "badge": "",- "tag": "",- "env_vars": [],- }-- # ------------------------------------------------------------------- # Backward-compat shims for the legacy CloudBrowserProvider API- # ------------------------------------------------------------------- #- # The pre-PR-#25214 ABC exposed ``is_configured()`` and ``provider_name()``;- # ``tools.browser_tool`` has ~6 callers that still use those names. Rather- # than churn every callsite (and break out-of-tree downstream code that- # subclassed CloudBrowserProvider), we expose the old names as thin- # delegations to the new API. Subclasses MUST implement :meth:`is_available`- # and :attr:`name`; they may override ``is_configured`` / ``provider_name``- # for compatibility with the legacy ABC but it is not required.+ # Legacy ``CloudBrowserProvider`` names still used by ``tools.browser_tool``+ # and out-of-tree subclasses; thin delegations to the current API.def is_configured(self) -> bool:"""Backward-compat alias for :meth:`is_available`."""diff --git a/agent/context_engine.py b/agent/context_engine.pyindex b772125c0cb..ff153fa2f90 100644--- a/agent/context_engine.py+++ b/agent/context_engine.py@@ -1,28 +1,14 @@"""Abstract base class for pluggable context engines.-A context engine controls how conversation context is managed when-approaching the model's token limit. The built-in ContextCompressor-is the default implementation. Third-party engines (e.g. LCM) can-replace it via the plugin system or by being placed in the-``plugins/context_engine/<name>/`` directory.--Selection is config-driven: ``context.engine`` in config.yaml.-Default is ``"compressor"`` (the built-in). Only one engine is active.--The engine is responsible for:- - Deciding when compaction should fire- - Performing compaction (summarization, DAG construction, etc.)- - Optionally exposing tools the agent can call (e.g. lcm_grep)- - Tracking token usage from API responses--Lifecycle:- 1. Engine is instantiated and registered (plugin register() or default)- 2. on_session_start() called when a conversation begins- 3. update_from_response() called after each API response with usage data- 4. should_compress() checked after each turn- 5. compress() called when should_compress() returns True- 6. on_session_end() called at real session boundaries (CLI exit, /reset,- gateway session expiry) — NOT per-turn+A context engine decides when and how conversation context is compacted near+the model's token limit, tracks token usage, and may expose tools. The+built-in ContextCompressor is the default; ``context.engine`` in config.yaml+selects a plugin engine (``plugins/context_engine/<name>/``). One engine is+active at a time.++Lifecycle: on_session_start() -> per API response update_from_response() ->+per turn should_compress() / compress() -> on_session_end() at real session+boundaries only (CLI exit, /reset, gateway expiry), never per-turn."""from abc import ABC, abstractmethod@@ -60,12 +46,10 @@ def automatic_compaction_status_message(default_message: str,**context: Any,) -> str | None:- """Resolve host-visible status for an automatic compaction event.+ """Host-visible status for an automatic compaction event; ``None`` = emit nothing.- Engines can suppress routine automatic status with- ``emit_automatic_compaction_status = False`` or customize it by defining- ``get_automatic_compaction_status_message(...)``. Empty strings and- ``None`` mean "do not emit a lifecycle status".+ Engines suppress via ``emit_automatic_compaction_status = False`` or+ customize via ``get_automatic_compaction_status_message(...)``."""if not getattr(engine, "emit_automatic_compaction_status", True):return None@@ -96,9 +80,7 @@ class ContextEngine(ABC):def name(self) -> str:"""Short identifier (e.g. 'compressor', 'lcm')."""- # -- Token state (read by run_agent.py for display/logging) ------------- #- # Engines MUST maintain these. run_agent.py reads them directly.+ # -- Token state: engines MUST maintain these; run_agent.py reads them directly.last_prompt_tokens: int = 0last_completion_tokens: int = 0@@ -107,39 +89,28 @@ class ContextEngine(ABC):context_length: int = 0compression_count: int = 0- # -- Compaction parameters (read by run_agent.py for preflight) --------- #- # These control the preflight compression check. Subclasses may- # override via __init__ or property; defaults are sensible for most- # engines.- #- # protect_first_n semantics (since PR #13754): count of non-system head- # messages always preserved verbatim, IN ADDITION to the system prompt- # which is always implicitly protected. Default 3 keeps the- # historical "system + first 3 non-system messages" head shape.+ # -- Compaction parameters (read by run_agent.py for preflight). protect_first_n+ # counts non-system head messages kept verbatim IN ADDITION to the always-+ # protected system prompt (3 keeps the historical head shape).threshold_percent: float = 0.75protect_first_n: int = 3protect_last_n: int = 6- # User-visible lifecycle status for automatic host-triggered compaction.- # Alternative engines that treat compaction as routine background- # maintenance can set this false to keep successful automatic passes silent;- # warnings, errors, and explicit manual commands should still surface.+ # False keeps successful automatic compaction passes silent (routine+ # background maintenance); warnings, errors and manual /compress still surface.emit_automatic_compaction_status: bool = True# -- Core interface ----------------------------------------------------@abstractmethoddef update_from_response(self, usage: Dict[str, Any]) -> None:- """Update tracked token usage from an API response.-- Called after every LLM call with a normalized usage dict. The legacy- keys ``prompt_tokens``, ``completion_tokens``, and ``total_tokens``- are always present. Newer hosts also include canonical buckets:- ``input_tokens``, ``output_tokens``, ``cache_read_tokens``,- ``cache_write_tokens``, and ``reasoning_tokens``. Engines should- treat those fields as optional for compatibility with older hosts.+ """Update tracked token usage after every LLM call.++ ``prompt_tokens``/``completion_tokens``/``total_tokens`` are always+ present; the canonical buckets (``input_tokens``, ``output_tokens``,+ ``cache_read_tokens``, ``cache_write_tokens``, ``reasoning_tokens``)+ are optional on older hosts."""@abstractmethod@@ -149,13 +120,9 @@ class ContextEngine(ABC):def should_compress_info(self, prompt_tokens: int = None) -> "tuple[bool, str | None]":"""Return ``(should_compress, reason)``.- The base implementation is backward-compatible: engines that only- implement ``should_compress`` get ``(should_compress(prompt_tokens),- None)``. Concrete engines with richer block reasons (e.g. a- summary-LLM cooldown or an anti-thrashing guard) override this to- surface a human-readable reason so callers can warn the user instead- of silently skipping compression. Added for the silent-overflow- warning fix (#62625) so plugin engines don't raise AttributeError.+ Engines with block reasons (summary-LLM cooldown, anti-thrashing guard)+ override this so callers can warn the user instead of silently skipping+ compression. The default keeps plugin engines from raising AttributeError."""return self.should_compress(prompt_tokens), None@@ -168,25 +135,14 @@ class ContextEngine(ABC):force: bool = False,memory_context: str = "",) -> List[Dict[str, Any]]:- """Compact the message list and return the new message list.-- This is the main entry point. The engine receives the full message- list and returns a (possibly shorter) list that fits within the- context budget. The implementation is free to summarize, build a- DAG, or do anything else — as long as the returned list is a valid- OpenAI-format message sequence.-- Args:- focus_topic: Optional topic string from manual ``/compress <focus>``.- Engines that support guided compression should prioritise- preserving information related to this topic. Engines that- don't support it may simply ignore this argument.- force: Whether a user-requested compression should bypass an- engine-owned cooldown. Engines without cooldowns may ignore it.- memory_context: Text returned by memory providers immediately before- compaction. Summarizing engines should include non-empty text in- their handoff prompt. Older engines may omit this parameter; the- host filters unsupported optional arguments by signature.+ """Compact ``messages`` and return a valid OpenAI-format message list+ that fits the context budget (summarize, build a DAG, anything).++ ``focus_topic`` comes from manual ``/compress <focus>`` (prioritise that+ topic); ``force`` asks to bypass an engine-owned cooldown;+ ``memory_context`` is provider text to include in the handoff prompt.+ Older engines may omit optional parameters — the host filters them by+ signature."""# -- Optional: proactive tool-result prune -----------------------------@@ -199,14 +155,9 @@ class ContextEngine(ABC):"""Deterministically trim old tool-result payloads without an LLM call.Runs on a low, cost-oriented trigger independent of ``should_compress``- so large-window engines can reclaim re-sent tool output long before full- compaction would fire. Returns ``(messages, n_pruned)``.-- Default is a safe no-op: the list is returned unchanged with ``0``- pruned. Engines that don't implement a cheap prune — and any engine that- predates this hook — inherit this default, so the agent loop's- post-tool-call prune path never raises ``AttributeError`` on them. The- built-in ContextCompressor overrides this with the real implementation.+ so large-window engines reclaim re-sent tool output long before full+ compaction. Returns ``(messages, n_pruned)``; default is a no-op so+ engines predating this hook never raise in the post-tool-call prune path."""return messages, 0@@ -220,61 +171,27 @@ class ContextEngine(ABC):incoming_message: Dict[str, Any] = None,budget_tokens: int = 0,) -> List[Dict[str, Any]]:- """Optionally choose/replace the context for THIS request, pre-generation.-- Called every turn after the request message list is assembled and- before it is dispatched to the provider — independent of- ``should_compress()``. This lets an engine *select* which context- enters the prompt (retrieval, topic routing, role/branch switching)- rather than *shrink* context that is already there. The two verbs are- orthogonal:-- - ``compress()`` : context is too long -> make it shorter.- - ``select_context()``: this turn belongs to a different context- -> use that one instead.-- Without this hook, engines that need per-turn access to the message- list have to force ``should_compress()`` to return ``True`` so that- ``compress()`` is invoked every turn purely as a callback — which- conflates selection with compression and degrades behaviour when the- engine's backend is unavailable. ``select_context()`` removes the need- for that workaround.-- The returned list is request-only: it replaces the messages sent to- the provider for this single call and MUST NOT be treated as persisted- transcript state. The conversation history in the session DB is left- untouched, so nothing leaks across turns. Return ``None`` to leave the- request unchanged.-- Unlike the ``pre_llm_call`` plugin hook (which appends to the user- message and intentionally never rewrites the list, to preserve the- cache prefix), ``select_context()`` may *replace* the message list.-- Ordering / cache contract: the host runs this hook **before** prompt- cache-control and **before** every request sanitizer (orphaned-tool- cleanup, thinking-only/role normalization, whitespace/JSON- normalization). So (a) whatever the hook returns still passes through- the same validation as any request — a malformed replacement cannot- reach the provider — and (b) prompt-cache stability (an AGENTS.md- invariant) is preserved: the default no-op leaves the request- byte-identical, so cache behaviour is unchanged for the built-in- compressor and any non-implementing engine. An engine that *does*- replace the list changes its own cache prefix by definition; that is- the engine's concern, and cache-control breakpoints are re-derived on- the selected list. The hook is evaluated per provider request (so it- re-runs on retries within a turn), consistent with "select the context- for THIS request".-- Args:- request_messages: The assembled request message list (system- prompt + history + any ephemeral prefill), in OpenAI format.- conversation_messages: The unmodified persisted conversation- history, for reference only (do not mutate).- incoming_message: The current turn's user message, if available.- budget_tokens: The active model's context length, or 0 if unknown.-- Default returns ``None`` (no-op) — zero impact on the built-in- compressor or any existing engine.+ """Optionally *select* (replace) the context for THIS request, pre-generation.++ Runs every provider request (so also on retries), independent of+ ``should_compress()``: ``compress()`` shrinks context that is too long,+ ``select_context()`` swaps in a different context (retrieval, topic+ routing, branch switching) without abusing ``compress()`` as a per-turn+ callback. Return ``None`` to leave the request unchanged.++ The returned list is request-only — it MUST NOT be treated as persisted+ transcript state; the session DB history is untouched. Unlike the+ ``pre_llm_call`` hook it may replace the list. The host runs it before+ prompt cache-control and before every request sanitizer, so a malformed+ replacement never reaches the provider and the default no-op keeps the+ request byte-identical (prompt-cache stability preserved). An engine that+ replaces the list changes its own cache prefix; breakpoints are+ re-derived on the selected list.++ ``request_messages`` is the assembled request (system prompt + history ++ ephemeral prefill); ``conversation_messages`` is the persisted history+ for reference only (do not mutate); ``budget_tokens`` is the model's+ context length or 0 if unknown."""return None@@ -284,66 +201,29 @@ class ContextEngine(ABC):usage: Dict[str, Any] = None,**kwargs: Any,) -> None:- """Observe a finished user turn (post-turn ingestion / observation).-- Called from the standard turn-finalization path once the assistant/tool- loop completes, with the finalized in-memory transcript snapshot. This- is the complement to ``select_context()``: selection happens *before*- the request, while observation happens *after* the turn. It lets an- engine ingest, index, summarize, or update routing / topic / session- state from what actually happened — so the next ``select_context()``- can act on it.-- Coverage: this fires from the normal finalization seam. Some abnormal- early-return paths in the loop (e.g. a content-policy block or a- provider terminal failure) persist and return without routing through- finalization, and therefore do not currently emit this hook. Treat it- as a best-effort post-turn observation for completed turns, not a- guaranteed callback for every possible early exit; unifying all- terminal paths behind one finalization seam is a separate follow-up.-- Together the two hooks remove the need to abuse ``should_compress()`` /- ``compress()`` as a generic per-turn callback just to observe history,- and they cover the case where a turn finishes and there may be no next- request from which to infer the previous turn.-- ``messages`` is a shallow copy and should be treated as read-only:- return values are ignored and this hook must not rely on transcript- mutation for persistence. ``kwargs`` may include ``turn_id``,- ``task_id``, ``api_call_count``, ``interrupted``, ``failed``, and- ``turn_exit_reason``.-- ``usage`` carries the completed turn's canonical token usage (the same- dict shape passed to ``update_from_response`` — ``prompt_tokens`` /- ``completion_tokens`` / ``total_tokens`` plus the canonical- ``input_tokens`` / ``output_tokens`` / ``cache_read_tokens`` /- ``cache_write_tokens`` / ``reasoning_tokens`` buckets) so an engine can- weigh how large/expensive the selected context actually was when- deciding the next ``select_context()``. It is ``None`` on finalized- turns that never reached a provider response (e.g. interrupt); engines- must treat it as optional.-- Default is a no-op.+ """Observe a finished turn (complement of ``select_context()``) so the+ engine can ingest/index/update routing state for the next request.++ Fires from the normal finalization seam only; some abnormal early+ returns (content-policy block, provider terminal failure) do not emit+ it — treat it as best-effort, not guaranteed. ``messages`` is a+ read-only shallow copy (return value ignored; never rely on transcript+ mutation). ``usage`` has the ``update_from_response`` dict shape and is+ ``None`` when the turn never reached a provider response (interrupt).+ ``kwargs`` may include ``turn_id``, ``task_id``, ``api_call_count``,+ ``interrupted``, ``failed``, ``turn_exit_reason``."""return None# -- Optional: pre-flight check ----------------------------------------def should_compress_preflight(self, messages: List[Dict[str, Any]]) -> bool:- """Quick rough check before the API call (no real token count yet).-- Default returns False (skip pre-flight). Override if your engine- can do a cheap estimate.- """+ """Cheap rough check before the API call (no real token count yet); default skips."""return Falsedef should_defer_preflight_to_real_usage(self, rough_tokens: int) -> bool:- """Return True when preflight should trust recent real usage instead.-- Built-in compression uses this to avoid re-compacting from known-noisy- rough estimates after a compressed request has already fit. Third-party- engines can ignore it safely.- """+ """True when preflight should trust recent real usage over the noisy rough+ estimate (avoids re-compacting after a compressed request already fit)."""return Falsedef get_automatic_compaction_status_message(@@ -353,15 +233,11 @@ class ContextEngine(ABC):default_message: str,**context: Any,) -> str | None:- """Return user-visible status for automatic host-triggered compaction.-- Return ``None`` to suppress successful automatic lifecycle status for- this compaction event. ``phase`` identifies the host call site (for- example ``"preflight"`` or ``"compress"``). ``context`` contains- best-effort fields such as ``approx_tokens`` and ``threshold_tokens``.+ """User-visible status for automatic compaction, or ``None`` to suppress it.- This hook does not control warning/error messages or explicit manual- commands such as ``/compress``.+ ``phase`` is the host call site (``"preflight"`` / ``"compress"``);+ ``context`` carries best-effort ``approx_tokens`` / ``threshold_tokens``.+ Warnings, errors and manual ``/compress`` are not governed by this hook."""if not self.emit_automatic_compaction_status:return None@@ -370,39 +246,20 @@ class ContextEngine(ABC):# -- Optional: manual /compress preflight ------------------------------def has_content_to_compress(self, messages: List[Dict[str, Any]]) -> bool:- """Quick check: is there anything in ``messages`` that can be compacted?-- Used by the gateway ``/compress`` command as a preflight guard —- returning False lets the gateway report "nothing to compress yet"- without making an LLM call.-- Default returns True (always attempt). Engines with a cheap way- to introspect their own head/tail boundaries should override this- to return False when the transcript is still entirely protected.- """+ """Preflight guard for gateway ``/compress``: False reports "nothing to+ compress yet" without an LLM call (e.g. transcript entirely protected)."""return True# -- Optional: session lifecycle ---------------------------------------def on_session_start(self, session_id: str, **kwargs) -> None:- """Called when a new conversation session begins.-- Use this to load persisted state (DAG, store) for the session.- kwargs may include hermes_home, platform, model, etc.- """+ """Session begins: load persisted state. kwargs may include hermes_home, platform, model."""def on_session_end(self, session_id: str, messages: List[Dict[str, Any]]) -> None:- """Called at real session boundaries (CLI exit, /reset, gateway expiry).-- Use this to flush state, close DB connections, etc.- NOT called per-turn — only when the session truly ends.- """+ """Real session boundary (CLI exit, /reset, gateway expiry) — never per-turn."""def on_session_reset(self) -> None:- """Called on /new or /reset. Reset per-session state.-- Default resets compression_count and token tracking.- """+ """/new or /reset: reset per-session state (default: counters and token tracking)."""self.last_prompt_tokens = 0self.last_completion_tokens = 0self.last_total_tokens = 0@@ -411,36 +268,21 @@ class ContextEngine(ABC):# -- Optional: tools ---------------------------------------------------def get_tool_schemas(self) -> List[Dict[str, Any]]:- """Return tool schemas this engine provides to the agent.-- Default returns empty list (no tools). LCM would return schemas- for lcm_grep, lcm_describe, lcm_expand here.- """+ """Tool schemas this engine exposes to the agent (default: none)."""return []def handle_tool_call(self, name: str, args: Dict[str, Any], **kwargs) -> str:- """Handle a tool call from the agent.-- Only called for tool names returned by get_tool_schemas().- Must return a JSON string.-- kwargs may include:- messages: the current in-memory message list (for live ingestion)- """+ """Handle a call to one of this engine's tools; must return a JSON string.+ kwargs may include ``messages`` (live in-memory list)."""import jsonreturn json.dumps({"error": f"Unknown context engine tool: {name}"})# -- Optional: status / display ----------------------------------------def get_status(self) -> Dict[str, Any]:- """Return status dict for display/logging.-- Default returns the standard fields run_agent.py expects.- """- # Clamp the -1 "compression just ran, awaiting real usage" sentinel- # (set by conversation_compression) to 0 so status readers don't see a- # raw -1 or a negative usage_percent on the transitional turn. Mirrors- # the CLI/gateway status-bar paths (cli.py, tui_gateway/server.py).+ """Status dict with the standard fields run_agent.py expects."""+ # Clamp the -1 "compression just ran, awaiting real usage" sentinel to 0+ # so no reader sees a negative usage_percent on the transitional turn.last_prompt = self.last_prompt_tokens if self.last_prompt_tokens > 0 else 0return {"last_prompt_tokens": last_prompt,@@ -464,22 +306,13 @@ class ContextEngine(ABC):provider: str = "",api_mode: str = "",) -> None:- """Called when the user switches models or on fallback activation.-- Default updates context_length and recalculates threshold_tokens- from threshold_percent. Override if your engine needs more- (e.g. recalculate DAG budgets, switch summary models).- """+ """Model switch / fallback: recompute threshold_tokens (override for more)."""self.context_length = context_length- # Apply per-model threshold overrides if set (longest substring match).- # Falls back to _config_threshold_percent (the raw config value) when- # no override matches. Plugin engines that override update_model() can- # call resolve_model_threshold() for the same logic.+ # Per-model threshold override (longest substring match), else the raw+ # config percent. Snapshot that percent ONCE so repeated switches fall+ # back to the configured value, not the previous model's override.from agent.context_compressor import resolve_model_thresholdif not hasattr(self, "_config_threshold_percent"):- # Snapshot the pre-override percent ONCE so repeated model- # switches fall back to the engine's configured value, not the- # previous model's override.self._config_threshold_percent = self.threshold_percentself._base_threshold_percent = resolve_model_threshold(model, getattr(self, "model_thresholds", {}),diff --git a/agent/image_gen_provider.py b/agent/image_gen_provider.pyindex b76bc8c01a7..86857eed510 100644--- a/agent/image_gen_provider.py+++ b/agent/image_gen_provider.py@@ -2,31 +2,18 @@Image Generation Provider ABC=============================-Defines the pluggable-backend interface for image generation. Providers register-instances via ``PluginContext.register_image_gen_provider()``; the active one-(selected via ``image_gen.provider`` in ``config.yaml``) services every-``image_generate`` tool call.--Providers live in ``<repo>/plugins/image_gen/<name>/`` (built-in, auto-loaded-as ``kind: backend``) or ``~/.hermes/plugins/image_gen/<name>/`` (user, opt-in-via ``plugins.enabled``).--Unified surface-----------------One tool — ``image_generate`` — covers **text-to-image** and-**image-to-image / image editing**. The router is the presence of-``image_url`` (and/or ``reference_image_urls``): if any source image is-provided, the provider routes to its image-to-image / edit endpoint; if-omitted, the provider routes to text-to-image. Users pick one **model**-(e.g. nano-banana-pro, gpt-image-2, grok-imagine-image); the provider-handles which underlying endpoint to hit. This mirrors the ``video_gen``-provider design (``agent/video_gen_provider.py``) so the two surfaces-stay learnable together.--Response shape----------------All providers return a dict that :func:`success_response` / :func:`error_response`-produce. The tool wrapper JSON-serializes it. Keys:+Pluggable-backend interface for image generation. Providers register via+``PluginContext.register_image_gen_provider()``; the one selected by+``image_gen.provider`` services every ``image_generate`` call. Providers live in+``<repo>/plugins/image_gen/<name>/`` (built-in) or+``~/.hermes/plugins/image_gen/<name>/`` (user, opt-in).++One tool covers text-to-image and image-to-image/editing: the presence of+``image_url`` (and/or ``reference_image_urls``) routes to the provider's edit+endpoint, otherwise text-to-image. Users pick one model; the provider picks the+endpoint. Mirrors ``agent/video_gen_provider.py`` so the two stay learnable.++Response shape (built by :func:`success_response` / :func:`error_response`)::success boolimage str | None URL or absolute file path@@ -42,13 +29,13 @@ produce. The tool wrapper JSON-serializes it. Keys:from __future__ import annotationsimport abc-import base64-import datetimeimport logging-import uuidfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuple+from agent import provider_media+from agent.provider_base import CatalogProviderBase+logger = logging.getLogger(__name__)@@ -56,106 +43,21 @@ VALID_ASPECT_RATIOS: Tuple[str, ...] = ("landscape", "square", "portrait")DEFAULT_ASPECT_RATIO = "landscape"-# ----------------------------------------------------------------------------# ABC-# ------------------------------------------------------------------------------class ImageGenProvider(abc.ABC):+class ImageGenProvider(CatalogProviderBase):"""Abstract base class for an image generation backend.- Subclasses must implement :meth:`generate`. Everything else has sane- defaults — override only what your provider needs.+ Subclasses must implement :attr:`name` and :meth:`generate`; everything else+ has defaults. ``list_models`` entries may add ``speed`` / ``strengths`` /+ ``price`` for the picker."""- @property- @abc.abstractmethod- def name(self) -> str:- """Stable short identifier used in ``image_gen.provider`` config.-- Lowercase, no spaces. Examples: ``fal``, ``openai``, ``replicate``.- """-- @property- def display_name(self) -> str:- """Human-readable label shown in ``hermes tools``. Defaults to ``name.title()``."""- return self.name.title()-- def is_available(self) -> bool:- """Return True when this provider can service calls.-- Typically checks for a required API key. Default: True- (providers with no external dependencies are always available).- """- return True-- def list_models(self) -> List[Dict[str, Any]]:- """Return catalog entries for ``hermes tools`` model picker.-- Each entry::-- {- "id": "gpt-image-1.5", # required- "display": "GPT Image 1.5", # optional; defaults to id- "speed": "~10s", # optional- "strengths": "...", # optional- "price": "$...", # optional- }-- Default: empty list (provider has no user-selectable models).- """- return []-- def get_setup_schema(self) -> Dict[str, Any]:- """Return provider metadata for the ``hermes tools`` picker.-- Used by ``tools_config.py`` to inject this provider as a row in- the Image Generation provider list. Shape::-- {- "name": "OpenAI", # picker label- "badge": "paid", # optional short tag- "tag": "One-line description...", # optional subtitle- "env_vars": [ # keys to prompt for- {"key": "OPENAI_API_KEY",- "prompt": "OpenAI API key",- "url": "https://platform.openai.com/api-keys"},- ],- }-- Default: minimal entry derived from ``display_name``. Override to- expose API key prompts and custom badges.- """- return {- "name": self.display_name,- "badge": "",- "tag": "",- "env_vars": [],- }-- def default_model(self) -> Optional[str]:- """Return the default model id, or None if not applicable."""- models = self.list_models()- if models:- return models[0].get("id")- return None-def capabilities(self) -> Dict[str, Any]:- """Return what this provider supports.-- Returned dict (all keys optional)::-- {- "modalities": ["text", "image"], # which inputs the backend accepts- "max_reference_images": 9, # cap for reference_image_urls- }+ """What this provider supports: ``modalities`` (``"text"`` and/or+ ``"image"``) and ``max_reference_images``.- ``modalities`` declares whether the active backend/model supports- text-to-image (``"text"``), image-to-image / editing (``"image"``),- or both. The tool layer surfaces this in the dynamic schema so the- model knows when ``image_url`` is honored. Used by ``hermes tools``- for the picker too. Default: text-only (backward compatible — a- provider that doesn't override this advertises text-to-image only).+ The tool layer surfaces this in the dynamic schema so the model knows+ when ``image_url`` is honored. Default is text-only so a provider that+ doesn't override advertises only text-to-image (backward compatible)."""return {"modalities": ["text"],@@ -172,25 +74,15 @@ class ImageGenProvider(abc.ABC):reference_image_urls: Optional[List[str]] = None,**kwargs: Any,) -> Dict[str, Any]:- """Generate an image from a text prompt, or edit/transform a source image.-- Routing: if ``image_url`` (or any ``reference_image_urls``) is- provided, the provider should route to its image-to-image / edit- endpoint; otherwise text-to-image. ``image_url`` is the primary- source image to edit; ``reference_image_urls`` are additional- style/composition references (provider clamps to its declared- ``max_reference_images``).-- Implementations should return the dict from :func:`success_response`- or :func:`error_response`. ``kwargs`` may contain forward-compat- parameters future versions of the schema will expose —- implementations MUST ignore unknown keys (no TypeError).-- Known optional kwarg: ``upscale`` (bool) — when true, the caller- requests a post-generation high-resolution pass through the- backend's upscaler/enhancer. Providers without an upscaler simply- ignore it; providers that honor it should report ``upscaled: True``- in the response ``extra``.+ """Generate an image, or edit/transform a source image.++ ``image_url`` is the primary source to edit; ``reference_image_urls``+ are extra style/composition references (clamp to ``max_reference_images``).+ Any source image routes to the edit endpoint, otherwise text-to-image.+ Return :func:`success_response` / :func:`error_response`. Unknown+ ``kwargs`` MUST be ignored (forward compat). Known optional kwarg:+ ``upscale`` (bool) — a post-generation high-res pass; providers that+ honor it report ``upscaled: True`` in ``extra``."""@@ -200,11 +92,8 @@ class ImageGenProvider(abc.ABC):def resolve_aspect_ratio(value: Optional[str]) -> str:- """Clamp an aspect_ratio value to the valid set, defaulting to landscape.-- Invalid values are coerced rather than rejected so the tool surface is- forgiving of agent mistakes.- """+ """Clamp to :data:`VALID_ASPECT_RATIOS`; invalid values coerce to landscape so+ the tool surface forgives agent mistakes instead of rejecting them."""if not isinstance(value, str):return DEFAULT_ASPECT_RATIOv = value.strip().lower()@@ -214,12 +103,8 @@ def resolve_aspect_ratio(value: Optional[str]) -> str:def normalize_reference_images(value: Any) -> Optional[List[str]]:- """Coerce a reference-image argument into a clean list of URL/path strings.-- Accepts a single string or a list; strips blanks and whitespace. Returns- ``None`` when nothing usable remains so providers can treat "no refs" as a- single sentinel.- """+ """Coerce a str or list into a clean list of non-blank strings; ``None`` when+ nothing usable remains so providers treat "no refs" as one sentinel."""if value is None:return Noneif isinstance(value, str):@@ -235,11 +120,7 @@ def normalize_reference_images(value: Any) -> Optional[List[str]]:def _images_cache_dir() -> Path:"""Return ``$HERMES_HOME/cache/images/``, creating parents as needed."""- from hermes_constants import get_hermes_home-- path = get_hermes_home() / "cache" / "images"- path.mkdir(parents=True, exist_ok=True)- return path+ return provider_media.cache_dir("images")def save_b64_image(@@ -248,24 +129,10 @@ def save_b64_image(prefix: str = "image",extension: str = "png",) -> Path:- """Decode base64 image data and write it under ``$HERMES_HOME/cache/images/``.+ """Decode base64 image data into ``$HERMES_HOME/cache/images/``; return the path."""+ return provider_media.save_b64("images", b64_data, prefix=prefix, extension=extension)- Returns the absolute :class:`Path` to the saved file.- Filename format: ``<prefix>_<YYYYMMDD_HHMMSS>_<short-uuid>.<ext>``.- """- raw = base64.b64decode(b64_data)- ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")- short = uuid.uuid4().hex[:8]- path = _images_cache_dir() / f"{prefix}_{ts}_{short}.{extension}"- path.write_bytes(raw)- return path---# Extension inference for save_url_image — keep small and explicit. We don't-# want to import mimetypes for a handful of formats every image_gen provider-# actually returns, and we never want to inherit a content-type that points-# at HTML or JSON when the API gives us a degenerate response._URL_IMAGE_CONTENT_TYPES = {"image/png": "png","image/jpeg": "jpg",@@ -282,66 +149,17 @@ def save_url_image(timeout: float = 60.0,max_bytes: int = 25 * 1024 * 1024,) -> Path:- """Download an image URL and write it under ``$HERMES_HOME/cache/images/``.-- Used by providers (xAI, fallback OpenAI) whose API returns an *ephemeral*- URL instead of inline base64 — those URLs frequently expire before a- downstream consumer (Telegram ``send_photo``, browser fetch) can resolve- them, so we materialise the bytes locally at tool-completion time.- Mirrors :func:`save_b64_image`'s shape so providers can swap in one line.+ """Download an (often ephemeral) image URL into ``$HERMES_HOME/cache/images/``.- Returns the absolute :class:`Path` to the saved file. Raises on any- network / HTTP / oversize / non-image-content-type error so callers can- fall back to returning the bare URL with a clear error message.+ Raises on network / HTTP / oversize / empty errors so callers can fall back+ to returning the bare URL with a clear message. See :mod:`agent.provider_media`."""- import requests-- response = requests.get(url, timeout=timeout, stream=True)- response.raise_for_status()-- # Infer extension from the response content-type, falling back to the- # URL suffix when xAI / OpenAI omit a precise type (some CDNs return- # ``application/octet-stream``). Defaults to ``png``.- content_type = (response.headers.get("Content-Type") or "").split(";", 1)[0].strip().lower()- extension = _URL_IMAGE_CONTENT_TYPES.get(content_type)- if extension is None:- url_path = url.split("?", 1)[0].lower()- for ext in ("png", "jpg", "jpeg", "webp", "gif"):- if url_path.endswith(f".{ext}"):- extension = "jpg" if ext == "jpeg" else ext- break- if extension is None:- extension = "png"-- ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")- short = uuid.uuid4().hex[:8]- path = _images_cache_dir() / f"{prefix}_{ts}_{short}.{extension}"-- bytes_written = 0- with path.open("wb") as fh:- for chunk in response.iter_content(chunk_size=64 * 1024):- if not chunk:- continue- bytes_written += len(chunk)- if bytes_written > max_bytes:- fh.close()- try:- path.unlink()- except OSError:- pass- raise ValueError(- f"Image at {url} exceeds {max_bytes // (1024 * 1024)}MB cap; refusing to cache."- )- fh.write(chunk)-- if bytes_written == 0:- try:- path.unlink()- except OSError:- pass- raise ValueError(f"Image at {url} returned 0 bytes; refusing to cache.")-- return path+ return provider_media.save_url(+ "images", url, prefix=prefix, timeout=timeout, max_bytes=max_bytes,+ chunk_size=64 * 1024, content_types=_URL_IMAGE_CONTENT_TYPES,+ url_extensions=("png", "jpg", "jpeg", "webp", "gif"), default_extension="png",+ label="Image", empty_error="Image at {url} returned 0 bytes; refusing to cache.",+ )def success_response(@@ -354,14 +172,7 @@ def success_response(modality: str = "text",extra: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:- """Build a uniform success response dict.-- ``image`` may be an HTTP URL or an absolute filesystem path (for b64- providers like OpenAI). ``modality`` is ``"text"`` (text-to-image) or- ``"image"`` (image-to-image / editing) — indicates which endpoint was- actually hit, useful for diagnostics. Callers that need to pass through- additional backend-specific fields can supply ``extra``.- """+ """Uniform success dict; ``extra`` keys are added without overriding standard ones."""payload: Dict[str, Any] = {"success": True,"image": image,diff --git a/agent/image_routing.py b/agent/image_routing.pyindex a861cd29bfe..02c21b9ef64 100644--- a/agent/image_routing.py+++ b/agent/image_routing.py@@ -3,38 +3,25 @@Two modes:native — attach images as OpenAI-style ``image_url`` content parts on the- user turn. Provider adapters (Anthropic, Gemini, Bedrock, Codex,- OpenAI chat.completions) already translate these into their- vendor-specific multimodal formats.-+ user turn; provider adapters translate these to vendor formats.text — run ``vision_analyze`` on each image up-front and prepend the- description to the user's text. The model never sees the pixels;- it only sees a lossy text summary. This is the pre-existing- behaviour and still the right choice for non-vision models.--The decision is made once per message turn by :func:`decide_image_input_mode`.-It reads ``agent.image_input_mode`` from config.yaml (``auto`` | ``native``-| ``text``, default ``auto``) and the active model's capability metadata.--In ``auto`` mode:- - If the user has explicitly configured ``auxiliary.vision``- (provider/model/base_url not ``auto``/empty), images route through- that backend — the DE-FACTO choice: a user who named a dedicated- vision model wants it used, even when the main model has native- vision (maintainer decision 2026-08-28, reversing #29135's- fallback-only posture).- - Otherwise, if the active model reports ``supports_vision=True`` (via- config override or models.dev metadata), we attach natively.- - Otherwise (non-vision model, no aux backend), text via the default- vision_analyze flow.- ``agent.image_input_mode: native`` remains the absolute override for- users who want native attach despite a configured aux backend.--This keeps ``vision_analyze`` surfaced as a tool in every session — skills-and agent flows that chain it (browser screenshots, deeper inspection of-URL-referenced images, style-gating loops) keep working. The routing only-affects *how user-attached images on the current turn* are presented to the-main model.+ (lossy) description to the user's text. Still the right choice+ for non-vision models.++:func:`decide_image_input_mode` decides once per message turn from+``agent.image_input_mode`` (``auto`` | ``native`` | ``text``, default ``auto``)+plus the active model's capability metadata. In ``auto`` mode:++ - An explicitly configured ``auxiliary.vision`` backend is the DE-FACTO route+ (``text``): a user who named a dedicated vision model wants it used even+ when the main model has native vision. ``image_input_mode: native`` is the+ absolute override.+ - Otherwise, ``supports_vision=True`` (config override or catalog) → native.+ - Otherwise text via the default vision_analyze flow.++``vision_analyze`` stays surfaced as a tool in every session so skills that+chain it keep working; routing only affects how *user-attached images on the+current turn* are presented to the main model."""from __future__ import annotations@@ -45,7 +32,7 @@ import mimetypesimport osimport refrom pathlib import Path-from typing import Any, Dict, List, Optional, Tuple+from typing import Any, Callable, Dict, Iterable, List, Optional, Tuplelogger = logging.getLogger(__name__)@@ -53,27 +40,24 @@ logger = logging.getLogger(__name__)_VALID_MODES = frozenset({"auto", "native", "text"})-# Image extensions used by extract_image_refs(). Kept tight on purpose — we-# only auto-attach things the model can actually see. Documents/archives are-# excluded because the gateway's broader extract_local_files() also routes-# them differently (send_document), and we don't want to attach a PDF as a-# vision part.+# Extensions extract_image_refs() auto-attaches. Kept tight: documents/archives+# are excluded because the gateway routes them via send_document, and we never+# want a PDF attached as a vision part._IMAGE_EXTS = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".tif", ".heic",)_IMAGE_EXT_PATTERN = "|".join(e.lstrip(".") for e in _IMAGE_EXTS)-# Absolute / home-relative local image path. Matches the same shape gateway's-# extract_local_files() uses: anchors to ``~/`` or ``/``, ignores matches inside-# URLs (the ``(?<![/:\w.])`` lookbehind), and case-insensitive on the extension.+# Absolute / home-relative local image path — same shape as gateway's+# extract_local_files(): anchored to ``~/`` or ``/``, the lookbehind skips+# matches inside URLs, case-insensitive extension._LOCAL_IMAGE_PATH_RE = re.compile(r"(?<![/:\w.])(?:~/|/)(?:[\w.\-]+/)*[\w.\-]+\.(?:" + _IMAGE_EXT_PATTERN + r")\b",re.IGNORECASE,)-# http(s) URL ending in an image extension (optionally followed by a-# query string). Case-insensitive on the extension. Strict ``http(s)://``-# scheme so we don't accidentally grab ``file://`` URLs or other shapes.+# http(s) URL ending in an image extension, optional query string. Strict+# ``http(s)://`` so ``file://`` and other schemes are not grabbed._IMAGE_URL_RE = re.compile(r"https?://[^\s<>\"']+?\.(?:" + _IMAGE_EXT_PATTERN + r")(?:\?[^\s<>\"']*)?",re.IGNORECASE,@@ -83,80 +67,55 @@ _IMAGE_URL_RE = re.compile(def extract_image_refs(text: str) -> Tuple[List[str], List[str]]:"""Scan free-form text for image references the model should see.- Returns ``(local_paths, urls)``:-- * ``local_paths`` — absolute (``/``) or home-relative (``~/``) paths- whose suffix is an image extension AND whose expanded form exists- on disk as a file. Order-preserving, deduplicated.- * ``urls`` — ``http(s)://…`` URLs whose path ends in an image- extension (a ``?query`` is allowed after the extension).- Order-preserving, deduplicated.-- Matches inside fenced code blocks (``` ``` ```) and inline backticks- (`` `…` ``) are skipped so that snippets pasted into a task body for- reference aren't mistaken for live attachments. This mirrors the- behaviour of ``gateway.platforms.base.BaseAdapter.extract_local_files``.-- Local paths are validated against the filesystem; URLs are not- (the provider fetches them at request time).+ Returns ``(local_paths, urls)``, each order-preserving and deduplicated.+ Local paths (``/`` or ``~/``) must exist on disk as files; URLs are not+ validated (the provider fetches them). Matches inside fenced code blocks+ and inline backticks are skipped so pasted example snippets aren't treated+ as live attachments (mirrors ``BaseAdapter.extract_local_files``)."""if not isinstance(text, str) or not text:return [], []- # Build spans covered by fenced code blocks and inline code so we can- # ignore references the author embedded purely as example text.- code_spans: list[tuple[int, int]] = []- for m in re.finditer(r"```[^\n]*\n.*?```", text, re.DOTALL):- code_spans.append((m.start(), m.end()))- for m in re.finditer(r"`[^`\n]+`", text):- code_spans.append((m.start(), m.end()))+ code_spans: list[tuple[int, int]] = [+ (m.start(), m.end())+ for pattern, flags in ((r"```[^\n]*\n.*?```", re.DOTALL), (r"`[^`\n]+`", 0))+ for m in re.finditer(pattern, text, flags)+ ]def _in_code(pos: int) -> bool:return any(s <= pos < e for s, e in code_spans)local_paths: list[str] = []- seen_paths: set[str] = set()for match in _LOCAL_IMAGE_PATH_RE.finditer(text):if _in_code(match.start()):continue- raw = match.group(0)- expanded = os.path.expanduser(raw)+ expanded = os.path.expanduser(match.group(0))try:if not os.path.isfile(expanded):continueexcept OSError:# ENAMETOOLONG / EINVAL on pathological inputs — skip rather than crash.continue- if expanded in seen_paths:- continue- seen_paths.add(expanded)- local_paths.append(expanded)+ if expanded not in local_paths:+ local_paths.append(expanded)urls: list[str] = []- seen_urls: set[str] = set()for match in _IMAGE_URL_RE.finditer(text):if _in_code(match.start()):continue- url = match.group(0)- # Strip trailing punctuation that's almost certainly prose, not part- # of the URL (e.g. "see https://x.com/a.png." or "/a.png)").- url = url.rstrip(".,;:!?)]>")- if url in seen_urls:- continue- seen_urls.add(url)- urls.append(url)+ # Trailing punctuation is almost certainly prose ("see https://x/a.png.").+ url = match.group(0).rstrip(".,;:!?)]>")+ if url not in urls:+ urls.append(url)return local_paths, urls-# Strict YAML/JSON boolean coercion for capability overrides.-#-# ``bool("false")`` is True in Python because non-empty strings are truthy, so-# a user writing ``supports_vision: "false"`` (quoted — a common YAML mistake)-# would silently enable native vision routing on a model that can't actually-# handle it. Accept only the values YAML 1.1 / 1.2 treat as booleans, plus-# real ``bool`` and integer 0/1. Anything else returns None so the caller-# falls through to models.dev rather than honouring garbage.+# Strict YAML/JSON boolean coercion for capability overrides. ``bool("false")``+# is True, so a quoted ``supports_vision: "false"`` would silently enable native+# routing on a model that can't handle it. Accept only YAML boolean tokens,+# real bools and 0/1; anything else is None so the caller falls through to+# models.dev rather than honouring garbage._TRUE_TOKENS = frozenset({"true", "yes", "on", "1"})_FALSE_TOKENS = frozenset({"false", "no", "off", "0"})@@ -166,9 +125,7 @@ def _coerce_capability_bool(raw: Any) -> Optional[bool]:if isinstance(raw, bool):return rawif isinstance(raw, int):- if raw in (0, 1):- return bool(raw)- return None+ return bool(raw) if raw in (0, 1) else Noneif isinstance(raw, str):s = raw.strip().lower()if s in _TRUE_TOKENS:@@ -178,6 +135,47 @@ def _coerce_capability_bool(raw: Any) -> Optional[bool]:return None+def _dict_or_empty(raw: Any) -> Dict[str, Any]:+ return raw if isinstance(raw, dict) else {}+++def _clean_str(raw: Any) -> str:+ return str(raw or "").strip()+++def _runtime_main(key: str) -> str:+ """Stripped context-local main-runtime value, or "" when unavailable."""+ try:+ from agent.auxiliary_client import _runtime_main_value++ return _clean_str(_runtime_main_value(key))+ except Exception:+ return ""+++def _model_supports_vision_override(models_cfg: Any, model: str) -> Optional[bool]:+ """Per-model ``supports_vision`` (or ``vision`` alias) from a ``models`` mapping."""+ per_model = _dict_or_empty(_dict_or_empty(models_cfg).get(model))+ return _coerce_capability_bool(per_model.get("supports_vision", per_model.get("vision")))+++def _custom_provider_entries(cfg: Dict[str, Any], names: Iterable[str]) -> Iterable[Dict[str, Any]]:+ """Yield legacy ``custom_providers`` list entries whose ``name`` matches ``names``.++ Iterates ``names`` in the given priority order (outer loop) so list order+ cannot let a persisted default shadow the live route.+ """+ custom_providers = cfg.get("custom_providers")+ if not isinstance(custom_providers, list):+ return+ entries = [e for e in custom_providers if isinstance(e, dict)]+ for name in names:+ wanted = name.strip().lower()+ for entry in entries:+ if _clean_str(entry.get("name")).lower() == wanted:+ yield entry++def _supports_vision_override(cfg: Optional[Dict[str, Any]],provider: str,@@ -185,123 +183,72 @@ def _supports_vision_override(*,requested_provider: str = "",) -> Optional[bool]:- """Resolve user-declared vision capability from config.yaml.-- Resolution order, first hit wins:- 1. ``model.supports_vision`` (top-level shortcut for the active model)- 2. ``providers.<provider>.models.<model>.supports_vision``- (named custom providers — ``provider`` may be the runtime-resolved- value ``"custom"``, the runtime's originally requested provider,- and/or the user-declared name under ``model.provider``; all are- tried. For ``custom:<name>`` syntax, the stripped ``<name>`` is also- tried as a provider key.)- 2b. ``custom_providers`` (legacy list form) ``.models.<model>``-- Under (2) and (2b), the per-model capability key may be written as- either ``supports_vision`` or the shorter ``vision`` alias; both work.-- Returns None when no override is set, so the caller falls through to- models.dev. Returns False explicitly only when the user wrote a- recognised boolean false token.+ """Resolve user-declared vision capability from config.yaml; None when unset.++ First hit wins: ``model.supports_vision`` → ``providers.<p>.models.<model>``+ → legacy ``custom_providers[].models.<model>``. Named custom providers are+ rewritten to ``provider="custom"`` at runtime while config keeps the user's+ name under ``model.provider``, so the requested, runtime and config+ identities are all tried, plus the bare ``<name>`` of any ``custom:<name>``."""if not isinstance(cfg, dict):return None- # 1. Top-level shortcut- model_cfg_raw = cfg.get("model")- model_cfg: Dict[str, Any] = model_cfg_raw if isinstance(model_cfg_raw, dict) else {}+ model_cfg = _dict_or_empty(cfg.get("model"))top = _coerce_capability_bool(model_cfg.get("supports_vision"))if top is not None:return top- # 2. Per-provider, per-model. Named custom providers (e.g. "my-vllm")- # get rewritten to provider="custom" at runtime- # (hermes_cli/runtime_provider.py:_resolve_named_custom_runtime), so the- # config still holds the user-declared name under model.provider. Try- # both as candidate provider keys. Either identity may use the- # "custom:<name>" form while providers: is keyed by bare <name>.- config_provider = str(model_cfg.get("provider") or "").strip()provider_candidates: List[str] = []- for candidate in (requested_provider, provider, config_provider):- if not candidate:- continue- provider_candidates.append(candidate)- if candidate.startswith("custom:"):- stripped_candidate = candidate[len("custom:"):]- if stripped_candidate:- provider_candidates.append(stripped_candidate)- providers_raw = cfg.get("providers")- providers_cfg: Dict[str, Any] = providers_raw if isinstance(providers_raw, dict) else {}- for p in dict.fromkeys(provider_candidates):- entry_raw = providers_cfg.get(p)- entry: Dict[str, Any] = entry_raw if isinstance(entry_raw, dict) else {}- models_raw = entry.get("models")- models_cfg: Dict[str, Any] = models_raw if isinstance(models_raw, dict) else {}- per_model_raw = models_cfg.get(model)- per_model: Dict[str, Any] = per_model_raw if isinstance(per_model_raw, dict) else {}- coerced = _coerce_capability_bool(- per_model.get("supports_vision", per_model.get("vision"))- )+ for candidate in (requested_provider, provider, _clean_str(model_cfg.get("provider"))):+ if candidate:+ provider_candidates.append(candidate)+ if candidate.startswith("custom:") and candidate[len("custom:"):]:+ provider_candidates.append(candidate[len("custom:"):])+ provider_candidates = list(dict.fromkeys(provider_candidates))++ providers_cfg = _dict_or_empty(cfg.get("providers"))+ for p in provider_candidates:+ coerced = _model_supports_vision_override(_dict_or_empty(providers_cfg.get(p)).get("models"), model)if coerced is not None:return coerced- # 2b. Legacy list-style custom_providers. Entries are dicts with a- # "name" key and a nested "models" dict. Match by provider name (which- # may appear as the raw name or "custom:<name>" at runtime).- custom_providers = cfg.get("custom_providers")- if isinstance(custom_providers, list):- # Candidate priority matters when the CLI-selected provider differs- # from model.provider. Walk identities first, then config entries, so- # list order cannot let the persisted default shadow the live route.- for candidate in dict.fromkeys(provider_candidates):- candidate_name = candidate.strip().lower()- for entry_raw in custom_providers:- if not isinstance(entry_raw, dict):- continue- entry_name = str(entry_raw.get("name") or "").strip().lower()- if entry_name != candidate_name:- continue- models_raw = entry_raw.get("models")- models_cfg = models_raw if isinstance(models_raw, dict) else {}- per_model_raw = models_cfg.get(model)- per_model = per_model_raw if isinstance(per_model_raw, dict) else {}- coerced = _coerce_capability_bool(- per_model.get("supports_vision", per_model.get("vision"))- )- if coerced is not None:- return coerced+ for entry in _custom_provider_entries(cfg, provider_candidates):+ coerced = _model_supports_vision_override(entry.get("models"), model)+ if coerced is not None:+ return coercedreturn None-def _resolve_inference_base_url(+def _resolve_inference_value(cfg: Optional[Dict[str, Any]],provider: str,+ key: str,+ *,+ runtime_ok: Callable[[str], bool],) -> str:- """Best-effort base URL for the active inference provider."""- try:- from agent.auxiliary_client import _runtime_main_value+ """Shared resolution for ``base_url`` / ``api_key`` of the active inference provider.- runtime = str(_runtime_main_value("base_url") or "").strip()- runtime_provider = str(_runtime_main_value("provider") or "").strip().lower()- requested_provider = str(provider or "").strip().lower()- if runtime and (not requested_provider or requested_provider == runtime_provider):- return runtime- except Exception:- pass+ Order: context-local runtime value (when ``runtime_ok`` accepts it) →+ ``model.<key>`` → ``providers.<name>.<key>`` → ``custom_providers[].<key>``,+ where ``<name>`` covers the provider and ``model.provider`` in both bare+ and ``custom:``-prefixed forms.+ """+ runtime = _runtime_main(key)+ if runtime and runtime_ok(runtime):+ return runtimeif not isinstance(cfg, dict):return ""- model_cfg_raw = cfg.get("model")- model_cfg: Dict[str, Any] = model_cfg_raw if isinstance(model_cfg_raw, dict) else {}- base_url = str(model_cfg.get("base_url") or "").strip()- if base_url:- return base_url+ model_cfg = _dict_or_empty(cfg.get("model"))+ value = _clean_str(model_cfg.get(key))+ if value:+ return value- config_provider = str(model_cfg.get("provider") or "").strip()candidate_names: set[str] = set()- for p in filter(None, (provider, config_provider)):+ for p in filter(None, (provider, _clean_str(model_cfg.get("provider")))):candidate_names.add(p)if p.lower().startswith("custom:"):candidate_names.add(p.split(":", 1)[1])@@ -313,9 +260,9 @@ def _resolve_inference_base_url(for name in candidate_names:entry = providers_cfg.get(name)if isinstance(entry, dict):- bu = str(entry.get("base_url") or "").strip()- if bu:- return bu+ value = _clean_str(entry.get(key))+ if value:+ return valuecustom_providers = cfg.get("custom_providers")if isinstance(custom_providers, list):@@ -323,79 +270,44 @@ def _resolve_inference_base_url(for entry_raw in custom_providers:if not isinstance(entry_raw, dict):continue- entry_name = str(entry_raw.get("name") or "").strip()+ entry_name = _clean_str(entry_raw.get("name"))if entry_name not in candidate_names and entry_name.lower() not in lowered:continue- bu = str(entry_raw.get("base_url") or "").strip()- if bu:- return bu+ value = _clean_str(entry_raw.get(key))+ if value:+ return valuereturn ""-def _resolve_inference_api_key(+def _resolve_inference_base_url(cfg: Optional[Dict[str, Any]],provider: str,) -> str:- """Best-effort API key for the active inference provider.+ """Best-effort base URL for the active inference provider.- Mirrors :func:`_resolve_inference_base_url`'s resolution order (runtime- value, then ``model.api_key``, then the providers blocks) so the key- matches the base URL actually being probed. Without this, the local- server-type probe fires at a remote API-keyed endpoint without an- Authorization header — 5×401 per image-bearing turn on a keyed- sglang/vLLM deployment (#89863).+ The runtime base_url is only trusted when it belongs to the requested+ provider (or no provider was requested)."""- try:- from agent.auxiliary_client import _runtime_main_value+ requested_provider = _clean_str(provider).lower()- runtime_key = str(_runtime_main_value("api_key") or "").strip()- if runtime_key:- return runtime_key- except Exception:- pass+ def _runtime_ok(_: str) -> bool:+ return not requested_provider or requested_provider == _runtime_main("provider").lower()- if not isinstance(cfg, dict):- return ""+ return _resolve_inference_value(cfg, provider, "base_url", runtime_ok=_runtime_ok)- model_cfg_raw = cfg.get("model")- model_cfg: Dict[str, Any] = model_cfg_raw if isinstance(model_cfg_raw, dict) else {}- key = str(model_cfg.get("api_key") or "").strip()- if key:- return key- config_provider = str(model_cfg.get("provider") or "").strip()- candidate_names: set[str] = set()- for p in filter(None, (provider, config_provider)):- candidate_names.add(p)- if p.lower().startswith("custom:"):- candidate_names.add(p.split(":", 1)[1])- else:- candidate_names.add(f"custom:{p}")-- providers_cfg = cfg.get("providers")- if isinstance(providers_cfg, dict):- for name in candidate_names:- entry = providers_cfg.get(name)- if isinstance(entry, dict):- k = str(entry.get("api_key") or "").strip()- if k:- return k-- custom_providers = cfg.get("custom_providers")- if isinstance(custom_providers, list):- lowered = {n.lower() for n in candidate_names}- for entry_raw in custom_providers:- if not isinstance(entry_raw, dict):- continue- entry_name = str(entry_raw.get("name") or "").strip()- if entry_name not in candidate_names and entry_name.lower() not in lowered:- continue- k = str(entry_raw.get("api_key") or "").strip()- if k:- return k+def _resolve_inference_api_key(+ cfg: Optional[Dict[str, Any]],+ provider: str,+) -> str:+ """Best-effort API key for the active inference provider.- return ""+ Mirrors :func:`_resolve_inference_base_url` so the key matches the base URL+ actually probed; otherwise the local server-type probe hits a keyed remote+ endpoint without Authorization and sprays 401s on every image turn.+ """+ return _resolve_inference_value(cfg, provider, "api_key", runtime_ok=lambda _: True)def _should_probe_ollama_vision(@@ -403,57 +315,38 @@ def _should_probe_ollama_vision() -> bool:"""True when the active provider likely fronts a local Ollama server.- Server-fingerprint probing is only meaningful for *local* endpoints —- remote OpenAI-compatible APIs (sglang, vLLM, etc.) should never be probed,- and probing them without an api_key sprays 401s at the inference backend- (issue #89863).+ Server-fingerprint probing is only valid for LOCAL endpoints: remote+ OpenAI-compatible APIs (sglang, vLLM) expose Ollama-compat routes that can+ misidentify, and probing them without an api_key returns 401 on every leg."""- p = (provider or "").strip().lower()- if p == "ollama":+ if (provider or "").strip().lower() == "ollama":return Trueif not base_url:return False- # Remote endpoints must never be fingerprinted: the probe waterfall is- # only valid for local/LM-Studio/Ollama boxes. Non-Ollama remotes (sglang,- # vLLM, OpenAI-compat) expose Ollama-compat endpoints that can misidentify- # and, without an api_key, return 401 on every leg (issue #89863).- if p != "ollama":- try:- from agent.model_metadata import is_local_endpoint-- if not is_local_endpoint(base_url):- return False- except Exception:- return Falsetry:- from agent.model_metadata import detect_local_server_type+ from agent.model_metadata import detect_local_server_type, is_local_endpoint- # Forward the API key: a remote API-keyed endpoint answers the- # probe waterfall with 401s without it, and an unauthorized probe- # can never produce a positive verdict (#89863).+ if not is_local_endpoint(base_url):+ return False+ # Forward the key: an unauthorized probe can never produce a positive verdict.return detect_local_server_type(base_url, api_key=api_key) == "ollama"except Exception:return Falsedef _coerce_mode(raw: Any) -> str:- """Normalize a config value into one of the valid modes."""- if not isinstance(raw, str):- return "auto"- val = raw.strip().lower()- if val in _VALID_MODES:- return val+ """Normalize a config value into one of the valid modes (default ``auto``)."""+ if isinstance(raw, str) and raw.strip().lower() in _VALID_MODES:+ return raw.strip().lower()return "auto"def _explicit_aux_vision_override(cfg: Optional[Dict[str, Any]]) -> bool:- """True when the user configured a specific auxiliary vision backend.+ """True when the user configured a specific ``auxiliary.vision`` backend.- An explicit backend is the DE-FACTO image route in ``auto`` mode —- the user named a dedicated vision model, so images go through it even- when the main model could take them natively (maintainer decision,- reversing #29135). ``agent.image_input_mode: native`` still forces- native; unset/auto aux config leaves native as the default.+ An explicit backend is the DE-FACTO image route in ``auto`` mode even when+ the main model could take images natively. ``auto``/empty provider with no+ model and no base_url is not explicit."""if not isinstance(cfg, dict):return False@@ -464,14 +357,12 @@ def _explicit_aux_vision_override(cfg: Optional[Dict[str, Any]]) -> bool:if not isinstance(vision, dict):return False- provider = str(vision.get("provider") or "").strip().lower()- model = str(vision.get("model") or "").strip()- base_url = str(vision.get("base_url") or "").strip()-- # "auto" / "" / blank = not explicit- if provider in {"", "auto"} and not model and not base_url:- return False- return True+ provider = _clean_str(vision.get("provider")).lower()+ return not (+ provider in {"", "auto"}+ and not _clean_str(vision.get("model"))+ and not _clean_str(vision.get("base_url"))+ )def _lookup_supports_vision(@@ -481,33 +372,21 @@ def _lookup_supports_vision(*,requested_provider: str = "",) -> Optional[bool]:- """Return True/False if we can resolve caps, None if unknown.+ """Return True/False if vision capability can be resolved, None if unknown.- Consults the user's ``supports_vision`` override in config.yaml first- (so custom/local models declared as vision-capable don't fall through to- text routing in ``auto`` mode), then falls back to models.dev.+ Order: config ``supports_vision`` override → managed local runtime →+ models.dev catalog → Ollama probe for local endpoints."""- # Named custom providers are canonicalized to ``provider="custom"`` by- # runtime resolution. The original CLI/config name is carried in the- # context-local main runtime so capability lookup can still select the- # exact custom_providers entry. Require an exact provider+model match:- # background/auxiliary lookups must never borrow another turn's identity.+ # Named custom providers are canonicalized to ``provider="custom"``; the+ # original name lives in the context-local main runtime. Borrow it only on an+ # exact provider+model match so background/auxiliary lookups never take+ # another turn's identity.if not requested_provider:- try:- from agent.auxiliary_client import _runtime_main_value-- runtime_provider = str(- _runtime_main_value("provider") or ""- ).strip().lower()- runtime_model = str(_runtime_main_value("model") or "").strip()- lookup_provider = str(provider or "").strip().lower()- lookup_model = str(model or "").strip()- if runtime_provider == lookup_provider and runtime_model == lookup_model:- requested_provider = str(- _runtime_main_value("requested_provider") or ""- ).strip()- except Exception:- pass+ if (+ _runtime_main("provider").lower() == _clean_str(provider).lower()+ and _runtime_main("model") == _clean_str(model)+ ):+ requested_provider = _runtime_main("requested_provider")override = _supports_vision_override(cfg,@@ -520,13 +399,10 @@ def _lookup_supports_vision(if not provider or not model:return None- # Managed local runtime: the server that would receive the image is- # the authority on whether it can see (its /props reports modalities- # when a vision projector is loaded; the catalog covers staged-but-- # unloaded models). Cloud catalogs have never heard of a local GGUF,- # so without this answer every local model reads as text-only and- # images detour to a cloud auxiliary — wrong twice for a local-first- # user (broken feature, and a screenshot leaving the machine).+ # Managed local runtime: the server receiving the image is the authority on+ # whether it can see (its /props reports modalities). Cloud catalogs have+ # never heard of a local GGUF, so without this every local model reads as+ # text-only and screenshots detour to a cloud auxiliary.try:from hermes_cli.local_runtime.capabilities import (is_managed_provider,@@ -544,13 +420,10 @@ def _lookup_supports_vision(caps = Nonetry:from agent.models_dev import get_model_capabilities- # allow_network=True on purpose: vision-capability lookup runs when- # an image actually needs routing (not per turn), and the #31179- # text-only-main guard depends on catalog data — a cold cache- # returning "unknown" would fall back to attempting the call and- # reintroduce the bug. This preserves the historical- # network-on-cold-cache behavior for this one path; the fetch is- # cached (4h TTL) and backoff-limited after failures.+ # allow_network=True on purpose: this runs only when an image needs+ # routing, and the text-only-main guard depends on catalog data — a cold+ # cache returning "unknown" would reintroduce attempting the call. The+ # fetch is cached (4h TTL) and backoff-limited.caps = get_model_capabilities(provider, model, allow_network=True)except Exception as exc: # pragma: no cover - defensivelogger.debug("image_routing: caps lookup failed for %s:%s — %s", provider, model, exc)@@ -561,8 +434,6 @@ def _lookup_supports_vision(if not base_url and (provider or "").strip().lower() == "ollama":base_url = "http://localhost:11434/v1"- # Resolve the provider's API key so probe requests at keyed endpoints- # carry Authorization and don't spray 401s (issue #89863).resolved_api_key = _resolve_inference_api_key(cfg, provider)if _should_probe_ollama_vision(provider, base_url, api_key=resolved_api_key):@@ -594,9 +465,9 @@ def decide_image_input_mode("""Return ``"native"`` or ``"text"`` for the given turn.Args:- provider: active inference provider ID (e.g. ``"anthropic"``, ``"openrouter"``).- model: active model slug as it would be sent to the provider.- cfg: loaded config.yaml dict, or None. When None, behaves as auto.+ provider: active inference provider ID (e.g. ``"anthropic"``).+ model: active model slug as sent to the provider.+ cfg: loaded config.yaml dict, or None (behaves as auto).requested_provider: provider identity before runtime canonicalization."""mode_cfg = "auto"@@ -605,19 +476,11 @@ def decide_image_input_mode(if isinstance(agent_cfg, dict):mode_cfg = _coerce_mode(agent_cfg.get("image_input_mode"))- if mode_cfg == "native":- return "native"- if mode_cfg == "text":- return "text"+ if mode_cfg != "auto":+ return mode_cfg- # auto: an explicitly configured auxiliary.vision backend is the- # DE-FACTO choice — the user named a dedicated vision model, so that's- # what they want images to go through, even when the main model has- # native vision (maintainer decision, 2026-08-28, reversing #29135's- # fallback-only posture: config that only takes effect when the main- # model gets worse is a trap, not a setting). Native vision remains- # the default for unconfigured installs, and the fallback when the- # aux backend is unset.+ # auto: an explicit auxiliary.vision backend wins (see module docstring);+ # native remains the default for unconfigured installs.if _explicit_aux_vision_override(cfg):return "text"if requested_provider:@@ -628,107 +491,80 @@ def decide_image_input_mode(requested_provider=requested_provider,)else:- # Keep the long-standing three-argument call contract for callers and- # tests that replace the capability lookup hook.+ # Keep the three-argument call contract for callers/tests that replace+ # the capability lookup hook.supports = _lookup_supports_vision(provider, model, cfg)- if supports is True:- return "native"- return "text"---# Image size handling is REACTIVE rather than proactive: we attempt native-# attachment at full size regardless of provider, and rely on-# ``run_agent._try_shrink_image_parts_in_messages`` to shrink + retry if-# the provider rejects the request (e.g. Anthropic's hard 5 MB per-image-# ceiling returned as HTTP 400 "image exceeds 5 MB maximum").-#-# Why reactive: our knowledge of provider ceilings is partial and evolving-# (OpenAI accepts 49 MB+, Anthropic 5 MB, Gemini 100 MB, others unknown).-# A proactive per-provider table would be stale the moment a provider raises-# or lowers its limit, and silently degrading quality for users on providers-# that would have accepted the full image is the worse failure mode.-# The shrink-on-reject path loses 1 API call + maybe 1s of Pillow work when-# it fires, which is cheaper than permanent quality loss.+ return "native" if supports is True else "text"+++# Image size handling is REACTIVE: attach at full size regardless of provider+# and let ``run_agent._try_shrink_image_parts_in_messages`` shrink + retry on+# rejection (e.g. Anthropic's 5 MB ceiling as HTTP 400). Provider ceilings are+# partial and evolving (OpenAI 49 MB+, Anthropic 5 MB, Gemini 100 MB); a+# proactive table would go stale and silently degrade quality for providers+# that would have accepted the full image — worse than one extra API call.+++# Magic-byte signatures, checked in order. Filename-based detection is+# unreliable when platforms lie about content-type (Discord serves PNG as+# ``image/webp`` for proxied stickers); Anthropic rejects a media_type that+# does not match the bytes with HTTP 400, so we sniff.+_HEIC_BRANDS = frozenset({+ b"heic", b"heix", b"hevc", b"hevx", b"mif1", b"msf1", b"heim", b"heis",+})+_MAGIC_PREFIXES: Tuple[Tuple[bytes, str], ...] = (+ (b"\x89PNG\r\n\x1a\n", "image/png"),+ (b"\xff\xd8\xff", "image/jpeg"),+ (b"GIF87a", "image/gif"),+ (b"GIF89a", "image/gif"),+)def _sniff_mime_from_bytes(raw: bytes) -> Optional[str]:- """Detect image MIME from magic bytes. Returns None if unrecognised.-- Filename-based detection (``mimetypes.guess_type``) is unreliable when- upstream platforms lie about content-type. Discord, for example, can- serve a PNG with ``content_type=image/webp`` for proxied/animated- stickers, custom emoji previews, or images uploaded via certain bots.- Anthropic strictly validates that declared media_type matches the- actual bytes and returns HTTP 400 on mismatch, so we sniff to be safe.- """+ """Detect image MIME from magic bytes; None if unrecognised."""if not raw:return None- # PNG: 89 50 4E 47 0D 0A 1A 0A- if raw.startswith(b"\x89PNG\r\n\x1a\n"):- return "image/png"- # JPEG: FF D8 FF- if raw.startswith(b"\xff\xd8\xff"):- return "image/jpeg"- # GIF87a / GIF89a- if raw[:6] in {b"GIF87a", b"GIF89a"}:- return "image/gif"- # WEBP: "RIFF" .... "WEBP"+ for prefix, mime in _MAGIC_PREFIXES:+ if raw.startswith(prefix):+ return mimeif len(raw) >= 12 and raw[:4] == b"RIFF" and raw[8:12] == b"WEBP":return "image/webp"- # BMP: "BM"if raw.startswith(b"BM"):return "image/bmp"- # ISO-BMFF family (HEIC/HEIF/AVIF): bytes 4..8 == 'ftyp', major brand at 8..12+ # ISO-BMFF family (HEIC/HEIF/AVIF): 'ftyp' at 4..8, major brand at 8..12.if len(raw) >= 12 and raw[4:8] == b"ftyp":brand = raw[8:12]if brand in {b"avif", b"avis"}:return "image/avif"- if brand in {- b"heic", b"heix", b"hevc", b"hevx",- b"mif1", b"msf1", b"heim", b"heis",- }:+ if brand in _HEIC_BRANDS:return "image/heic"- # TIFF: II*\0 (little-endian) or MM\0* (big-endian)if raw[:4] in {b"II*\x00", b"MM\x00*"}:return "image/tiff"- # ICO: 00 00 01 00 (reserved=0, type=1=icon)if raw[:4] == b"\x00\x00\x01\x00":return "image/x-icon"- # SVG: text-based, look for an <svg tag near the start (skip BOM/whitespace)+ # SVG is text: look for an <svg tag near the start (skip BOM/whitespace).head = raw[:512].lstrip().lower()- if head.startswith(b"<?xml") or head.startswith(b"<svg"):- if b"<svg" in head:- return "image/svg+xml"+ if (head.startswith(b"<?xml") or head.startswith(b"<svg")) and b"<svg" in head:+ return "image/svg+xml"return None-# Formats every major vision provider (Anthropic, OpenAI, Gemini, Bedrock)-# accepts natively. Anything outside this set has to be transcoded to PNG-# before we declare media_type, otherwise the provider returns HTTP 400-# ("Could not process image" / "Unsupported image media type") and the-# whole turn fails with no salvage path.-#-# Discord (and a few other chat platforms) freely accept attachments in-# formats outside this set -- AVIF screenshots from Chromium, HEIC from-# iPhones, TIFF from scanners, BMP from old Windows tools, ICO -- so users-# do hit this in practice. SVG is vector and Pillow cannot rasterize it;-# it is skipped (logged) rather than transcoded.+# Formats every major vision provider accepts natively. Anything else must be+# transcoded to PNG before declaring media_type or the provider returns HTTP+# 400 and the whole turn fails. Chat platforms freely accept AVIF (Chromium+# screenshots), HEIC (iPhone), TIFF, BMP and ICO, so users do hit this. SVG is+# vector — Pillow cannot rasterize it — and is skipped (logged) instead._UNIVERSALLY_SUPPORTED_MIMES = frozenset({"image/png", "image/jpeg", "image/gif", "image/webp",})def _transcode_to_png(raw: bytes) -> Optional[bytes]:- """Decode arbitrary image bytes with Pillow and re-encode as PNG.+ """Decode image bytes with Pillow and re-encode as PNG; None when impossible.- Returns None if Pillow isn't installed or can't decode the input- (rare formats, corrupted bytes, missing optional decoder plugin for- HEIC/AVIF, or vector formats like SVG). Caller falls back to skipping- the image so the rest of the turn still works.-- HEIC/HEIF and AVIF need optional Pillow plugins; we try to register- them on demand and swallow ImportError so a missing plugin just- looks like 'Pillow can't decode this' rather than crashing.+ HEIC/HEIF and AVIF need optional Pillow plugins, registered on demand; a+ missing plugin just looks like "Pillow can't decode this" so the caller+ skips the image and the rest of the turn proceeds."""try:from PIL import Image@@ -739,8 +575,6 @@ def _transcode_to_png(raw: bytes) -> Optional[bytes]:"(and `pillow-heif` / `pillow-avif-plugin` for those formats).")return None- # Optional plugin registration. Silent on failure: an unsupported- # format will just fall through to Image.open raising below.try:import pillow_heif # type: ignore@@ -755,9 +589,8 @@ def _transcode_to_png(raw: bytes) -> Optional[bytes]:from io import BytesIOwith Image.open(BytesIO(raw)) as im:- # Pick an output mode PNG can serialise. Anything other than- # the standard set gets normalised to RGBA so transparency is- # preserved where the source had it.+ # Normalise exotic modes to RGBA so PNG can serialise and any+ # source transparency survives.if im.mode not in {"RGB", "RGBA", "L", "LA", "P"}:im = im.convert("RGBA")buf = BytesIO()@@ -770,12 +603,18 @@ def _transcode_to_png(raw: bytes) -> Optional[bytes]:return None-def _guess_mime(path: Path, raw: Optional[bytes] = None) -> str:- """Return image MIME type for *path*.+_SUFFIX_MIMES = {+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".png": "image/png",+ ".gif": "image/gif",+ ".webp": "image/webp",+ ".bmp": "image/bmp",+}- If *raw* bytes are provided, magic-byte sniffing wins (authoritative).- Otherwise we fall back to ``mimetypes`` then suffix-based defaults.- """++def _guess_mime(path: Path, raw: Optional[bytes] = None) -> str:+ """Image MIME for *path*: magic bytes (authoritative) → ``mimetypes`` → suffix → jpeg."""if raw is not None:sniffed = _sniff_mime_from_bytes(raw)if sniffed:@@ -783,40 +622,18 @@ def _guess_mime(path: Path, raw: Optional[bytes] = None) -> str:mime, _ = mimetypes.guess_type(str(path))if mime and mime.startswith("image/"):return mime- # mimetypes on some Linux distros mis-maps .jpg; default to jpeg when- # the suffix looks imagey.- suffix = path.suffix.lower()- return {- ".jpg": "image/jpeg",- ".jpeg": "image/jpeg",- ".png": "image/png",- ".gif": "image/gif",- ".webp": "image/webp",- ".bmp": "image/bmp",- }.get(suffix, "image/jpeg")+ # mimetypes on some Linux distros mis-maps .jpg; default to jpeg.+ return _SUFFIX_MIMES.get(path.suffix.lower(), "image/jpeg")def _file_to_data_url(path: Path) -> Optional[str]:"""Encode a local image as a base64 data URL at its native size.- Size limits are NOT enforced here — the agent retry loop- (``run_agent._try_shrink_image_parts_in_messages``) shrinks on the- provider's first rejection. Keeping this simple means providers that- accept large images (OpenAI 49 MB+, Gemini 100 MB) don't pay a silent- quality tax just because one other provider is stricter.-- Format compatibility IS handled here: if the sniffed MIME isn't one- of ``_UNIVERSALLY_SUPPORTED_MIMES`` (i.e. it's something like AVIF,- HEIC, BMP, TIFF, or ICO that some providers reject outright), we- transcode to PNG with Pillow before declaring media_type. This fixes- the user-visible "Could not process image" HTTP 400 from Anthropic on- Discord-attached AVIF/HEIC/BMP files.-- Returns None if the file can't be read OR if the format isn't- universally supported AND Pillow can't transcode it (Pillow missing,- HEIC/AVIF plugin missing, vector format like SVG, corrupt bytes). The- caller reports those paths in ``skipped`` and the rest of the turn- proceeds.+ Size is NOT limited here (the agent retry loop shrinks on the provider's+ first rejection, so lenient providers pay no silent quality tax). Format+ compatibility IS handled: MIMEs outside the accepted set are transcoded to+ PNG. Returns None when the file can't be read, is blocked by the read+ guard, or can't be transcoded — the caller reports it in ``skipped``."""try:from agent.file_safety import raise_if_read_blocked@@ -836,11 +653,9 @@ def _file_to_data_url(path: Path) -> Optional[str]:return Nonemime = _guess_mime(path, raw=raw)accepted = _UNIVERSALLY_SUPPORTED_MIMES- # The managed local server decodes fewer formats than cloud providers- # (no WebP — and a WebP part fails SILENTLY: the model never sees an- # image and confabulates a description). When the active main model is- # served by the managed runtime, narrow the accepted set so those- # formats transcode to PNG here instead of vanishing server-side.+ # The managed local server decodes fewer formats (no WebP — and a WebP part+ # fails SILENTLY: the model confabulates a description). Narrow the accepted+ # set so those formats transcode here instead of vanishing server-side.try:from agent.auxiliary_client import _runtime_main_valuefrom hermes_cli.local_runtime.capabilities import (@@ -881,86 +696,45 @@ def build_native_content_parts() -> Tuple[List[Dict[str, Any]], List[str]]:"""Build an OpenAI-style ``content`` list for a user turn.- Shape:- [{"type": "text", "text": "...\\n\\n[Image attached at: /local/path]"},- {"type": "image_url", "image_url": {"url": "data:image/png;base64,..."}},- {"type": "image_url", "image_url": {"url": "https://example.com/a.png"}},- ...]-- Local paths are read from disk and embedded as base64 ``data:`` URLs.- Remote URLs (``http(s)://``) are passed through verbatim — the provider- fetches them server-side. The model still sees the pixels either way.-- For each successfully attached image, a hint is appended to the text- part:+ Local paths are embedded as base64 ``data:`` URLs; remote URLs pass through+ verbatim. When at least one image attaches, a single text part combines the+ caption (or a neutral default) with one hint per image —+ ``[Image attached at: <path>]`` / ``[Image attached: <url>]`` — giving the+ model a string handle for tools that take an image path/URL, mirroring the+ text-mode hint from ``Runner._enrich_message_with_vision``.- * local path → ``[Image attached at: <path>]``- * URL → ``[Image attached: <url>]``-- The hint gives the model a string handle so MCP/skill tools that take- an image path or URL argument can be invoked on the same image without- an extra round-trip. This parallels the text-mode hint produced by- ``Runner._enrich_message_with_vision`` (``vision_analyze using image_url:- <path>``) so behaviour is consistent across both image input modes.-- Images are attached at their native size. If a provider rejects the- request because an image is too large (e.g. Anthropic's 5 MB per-image- ceiling), the agent's retry loop transparently shrinks and retries- once — see ``run_agent._try_shrink_image_parts_in_messages``.-- Returns (content_parts, skipped). Skipped entries are local paths- that couldn't be read from disk; URLs are never skipped (they're- not validated here).+ Returns ``(content_parts, skipped)``; ``skipped`` holds local paths that+ could not be read. URLs are never skipped (not validated here)."""skipped: List[str] = []image_parts: List[Dict[str, Any]] = []- attached_paths: List[str] = []- attached_urls: List[str] = []+ hint_lines: List[str] = []for raw_path in image_paths:p = Path(raw_path)- if not p.exists() or not p.is_file():- skipped.append(str(raw_path))- continue- data_url = _file_to_data_url(p)+ data_url = _file_to_data_url(p) if p.exists() and p.is_file() else Noneif not data_url:skipped.append(str(raw_path))continue- image_parts.append({- "type": "image_url",- "image_url": {"url": data_url},- })- attached_paths.append(str(raw_path))+ image_parts.append({"type": "image_url", "image_url": {"url": data_url}})+ hint_lines.append(f"[Image attached at: {raw_path}]")for url in image_urls or []:url = (url or "").strip()if not url:continue- image_parts.append({- "type": "image_url",- "image_url": {"url": url},- })- attached_urls.append(url)+ image_parts.append({"type": "image_url", "image_url": {"url": url}})+ hint_lines.append(f"[Image attached: {url}]")text = (user_text or "").strip()- # If at least one image attached, build a single text part that combines- # the user's caption (or a neutral default) with one hint per image.- if attached_paths or attached_urls:+ if image_parts:base_text = text or "What do you see in this image?"- hint_lines: List[str] = []- hint_lines.extend(f"[Image attached at: {p}]" for p in attached_paths)- hint_lines.extend(f"[Image attached: {u}]" for u in attached_urls)combined_text = f"{base_text}\n\n" + "\n".join(hint_lines)- parts: List[Dict[str, Any]] = [{"type": "text", "text": combined_text}]- parts.extend(image_parts)- return parts, skipped-- # No images successfully attached — fall back to plain text-only behaviour.- parts = []- if text:- parts.append({"type": "text", "text": text})- return parts, skipped+ return [{"type": "text", "text": combined_text}, *image_parts], skipped++ # No images attached — plain text-only behaviour.+ return ([{"type": "text", "text": text}] if text else []), skipped__all__ = [diff --git a/agent/memory_manager.py b/agent/memory_manager.pyindex 496562c2e87..abb56410a48 100644--- a/agent/memory_manager.py+++ b/agent/memory_manager.py@@ -1,113 +1,116 @@"""MemoryManager — orchestrates memory providers for the agent.-Single integration point in run_agent.py. Replaces scattered per-backend-code with one manager that delegates to registered providers.--Only ONE external plugin provider is allowed at a time — attempting to-register a second external provider is rejected with a warning. This-prevents tool schema bloat and conflicting memory backends.+Single integration point (run_agent.py) that fans out to registered providers.+The builtin provider is always allowed; only ONE external plugin provider may be+registered at a time — a second is rejected with a warning to prevent tool+schema bloat and conflicting memory backends.Usage in run_agent.py:self._memory_manager = MemoryManager()- # Only ONE of these:- self._memory_manager.add_provider(plugin_provider)-- # System prompt+ self._memory_manager.add_provider(plugin_provider) # at most one externalprompt_parts.append(self._memory_manager.build_system_prompt())-- # Pre-turn- context = self._memory_manager.prefetch_all(user_message)-- # Post-turn- self._memory_manager.sync_all(user_msg, assistant_response)+ context = self._memory_manager.prefetch_all(user_message) # pre-turn+ self._memory_manager.sync_all(user_msg, assistant_response) # post-turnself._memory_manager.queue_prefetch_all(user_msg)"""from __future__ import annotations+import contextvars+import inspectimport jsonimport loggingimport re-import inspectimport threadingfrom concurrent.futures import Future, ThreadPoolExecutor, wait+from functools import partialfrom typing import Any, Callable, Dict, List, Optionalfrom agent.memory_provider import MemoryProvider, PRE_COMPRESS_CHECKPOINT_API_VERSIONfrom agent.skill_commands import extract_user_instruction_from_skill_messagefrom tools.registry import tool_error+logger = logging.getLogger(__name__)+# Providers that predate the checkpoint-API attribute are implicitly on the# historical best-effort contract (API v1)._LEGACY_PRE_COMPRESS_API_VERSION = 1+# How long shutdown_all() waits for in-flight background sync/prefetch work to+# drain before abandoning it. Worker threads are daemon, so a wedged provider+# never blocks interpreter exit — it dies with the process past this window.+_SYNC_DRAIN_TIMEOUT_S = 5.0+_EXTERNAL_PREFETCH_TIMEOUT_S = 8.0++_VAR_KEYWORD = inspect.Parameter.VAR_KEYWORD+++# ---------------------------------------------------------------------------+# Signature introspection (providers are duck-typed; call shapes vary)+# ---------------------------------------------------------------------------++def _signature_params(fn: Callable[..., Any]):+ """Return ``fn``'s parameter mapping, or None when uninspectable (C callables, exotic proxies)."""+ try:+ return inspect.signature(fn).parameters+ except (TypeError, ValueError):+ return None+++def _has_var_kwargs(params) -> bool:+ return any(p.kind is _VAR_KEYWORD for p in params.values())+def _accepts_require_checkpoint(fn: Callable[..., Any]) -> bool:"""True if ``fn`` can receive the ``require_checkpoint`` keyword.- Checkpoint (v2) providers written against the original docs example use- the bare ``on_pre_compress(self, messages)`` signature; calling them with- the keyword would raise ``TypeError`` — which, under- ``require_checkpoint=True``, the host would re-raise as a checkpoint- failure even though the provider's durable write succeeded. Inspect the- signature and fall back to the legacy call shape when the keyword (or a- ``**kwargs`` catch-all) is absent. Unreadable signatures (C callables,- exotic proxies) conservatively report False.+ Checkpoint (v2) providers written against the original docs example use the+ bare ``on_pre_compress(self, messages)`` shape; passing the keyword would+ raise TypeError, which under ``require_checkpoint=True`` the host would+ re-raise as a checkpoint failure even though the durable write succeeded.+ Unreadable signatures conservatively report False."""- try:- sig = inspect.signature(fn)- except (TypeError, ValueError):+ params = _signature_params(fn)+ if params is None:return False- for param in sig.parameters.values():- if param.kind is inspect.Parameter.VAR_KEYWORD:- return True- if (- param.name == "require_checkpoint"- and param.kind in (- inspect.Parameter.KEYWORD_ONLY,- inspect.Parameter.POSITIONAL_OR_KEYWORD,- )- ):- return True- return False+ if _has_var_kwargs(params):+ return True+ param = params.get("require_checkpoint")+ return param is not None and param.kind in (+ inspect.Parameter.KEYWORD_ONLY,+ inspect.Parameter.POSITIONAL_OR_KEYWORD,+ )-logger = logging.getLogger(__name__)-# How long shutdown_all() waits for in-flight background sync/prefetch work-# to drain before abandoning it. A wedged provider must never block process-# teardown indefinitely — the worker threads are daemon, so anything still-# running past this window dies with the interpreter.-_SYNC_DRAIN_TIMEOUT_S = 5.0-_EXTERNAL_PREFETCH_TIMEOUT_S = 8.0+def _ctx_bound(fn: Callable[[], Any]) -> Callable[[], Any]:+ """Bind ``fn`` to the CALLER's contextvars for execution on another thread.++ Profile isolation in multi-profile processes (gateway multiplexer, dashboard,+ cron) is a ContextVar-scoped HERMES_HOME override; worker threads start with+ empty contexts, so an unbound provider resolving config paths or secrets+ from a worker would silently land on the default profile.+ """+ return partial(contextvars.copy_context().run, fn)+# ---------------------------------------------------------------------------+# Tool-schema plumbing+# ---------------------------------------------------------------------------+def normalize_tool_schema(schema: Any) -> Optional[Dict[str, Any]]:- """Return a function-tool dict with a resolvable top-level ``name``.-- Context engines and memory providers expose tool schemas via- ``get_tool_schemas()``. The expected shape is a bare function schema- (``{"name": ..., "description": ..., "parameters": ...}``) which callers- wrap as ``{"type": "function", "function": schema}``.-- Some providers instead return an entry that is *already* in OpenAI tool- form (``{"type": "function", "function": {"name": ...}}``). Wrapping that- a second time produces ``{"type": "function", "function": {"type":- "function", "function": {...}}}`` whose ``function`` has no top-level- ``name``. Strict providers (e.g. DeepSeek) reject the *entire* request- with ``tools[N].function: missing field name`` (HTTP 400), so one bad- schema disables the whole toolset and breaks every turn (#47707).-- This helper normalizes both shapes to the bare function schema and- returns ``None`` for anything without a resolvable name, so callers can- skip-with-warning rather than appending a nameless tool.+ """Return a bare function-tool dict with a resolvable top-level ``name``, else None.++ Providers should return ``{"name", "description", "parameters"}`` which callers+ wrap as ``{"type": "function", "function": schema}``. Some return the already+ wrapped OpenAI form; wrapping that twice yields a ``function`` with no ``name``+ and strict providers (e.g. DeepSeek) reject the ENTIRE request (HTTP 400),+ disabling every tool. Both shapes are normalized here so callers can skip+ nameless entries with a warning instead of poisoning the request."""if not isinstance(schema, dict):return None- # Unwrap an already-wrapped OpenAI tool entry.if schema.get("type") == "function" and isinstance(schema.get("function"), dict):schema = schema["function"]- if not isinstance(schema, dict):- return Nonename = schema.get("name", "")if not name or not isinstance(name, str):return None@@ -123,9 +126,7 @@ def memory_provider_tools_enabled("""Return whether external memory-provider tools should be exposed."""if disabled_toolsets and "memory" in disabled_toolsets:return False- if memory_tool_present:- return True- if enabled_toolsets is None:+ if memory_tool_present or enabled_toolsets is None:return Trueif not enabled_toolsets:return False@@ -144,19 +145,15 @@ def memory_provider_tools_enabled(def memory_provider_tools_exposed(agent: Any) -> bool:"""Whether external memory-provider tools are exposed on ``agent``.- Same gate as ``inject_memory_provider_tools`` so the provider's- ``system_prompt_block()`` and its tool schemas are presented to the- model together — otherwise the system prompt would advertise tools- that don't exist in the tool surface (#81014).+ Same gate as ``inject_memory_provider_tools`` so a provider's+ ``system_prompt_block()`` and its tool schemas are presented together —+ the system prompt must never advertise tools absent from the tool surface."""tools = getattr(agent, "tools", None)- if isinstance(tools, (list, tuple)):- memory_tool_present = any(- isinstance(tool, dict) and tool.get("function", {}).get("name") == "memory"- for tool in tools- )- else:- memory_tool_present = False+ memory_tool_present = isinstance(tools, (list, tuple)) and any(+ isinstance(tool, dict) and tool.get("function", {}).get("name") == "memory"+ for tool in tools+ )return memory_provider_tools_enabled(getattr(agent, "enabled_toolsets", None),getattr(agent, "disabled_toolsets", None),@@ -165,7 +162,7 @@ def memory_provider_tools_exposed(agent: Any) -> bool:def inject_memory_provider_tools(agent: Any) -> int:- """Append external memory-provider tool schemas to an agent tool surface."""+ """Append external memory-provider tool schemas to an agent tool surface; return count added."""memory_manager = getattr(agent, "_memory_manager", None)tools = getattr(agent, "tools", None)if not memory_manager or tools is None:@@ -177,10 +174,8 @@ def inject_memory_provider_tools(agent: Any) -> int:if isinstance(tool, dict)}if not memory_provider_tools_exposed(agent):- # A provider is configured but the memory toolset is gated off- # (platform_toolsets / disabled_toolsets). Say so once — a silent- # return 0 here made #81014 undiagnosable: the provider looked- # "half on" with no clue which config key suppressed its tools.+ # Say so once: a silent 0 leaves the provider looking "half on" with no+ # clue which config key (platform_toolsets / disabled_toolsets) gated it._providers = [p for p in (getattr(memory_manager, "providers", None) or [])if getattr(p, "name", "") != "builtin"@@ -244,56 +239,33 @@ def sanitize_context(text: str) -> str:"""Strip fence tags, injected context blocks, and system notes from provider output."""text = _INTERNAL_CONTEXT_RE.sub('', text)text = _INTERNAL_NOTE_RE.sub('', text)- text = _FENCE_TAG_RE.sub('', text)- return text+ return _FENCE_TAG_RE.sub('', text)class StreamingContextScrubber:- """Stateful scrubber for streaming text that may contain split memory-context spans.-- The one-shot ``sanitize_context`` regex cannot survive chunk boundaries:- a ``<memory-context>`` opened in one delta and closed in a later delta- leaks its payload to the UI because the non-greedy block regex needs- both tags in one string. This scrubber runs a small state machine- across deltas, holding back partial-tag tails and discarding- everything inside a span (including the system-note line).-- Usage::-- scrubber = StreamingContextScrubber()- for delta in stream:- visible = scrubber.feed(delta)- if visible:- emit(visible)- trailing = scrubber.flush() # at end of stream- if trailing:- emit(trailing)-- The scrubber is re-entrant per agent instance. Callers building new- top-level responses (new turn) should create a fresh scrubber or call- ``reset()``.+ """Stateful scrubber for streaming text whose memory-context spans may straddle deltas.++ The one-shot ``sanitize_context`` regex needs both tags in one string, so a+ span opened in one delta and closed in a later one would leak to the UI.+ This state machine holds back partial-tag tails between ``feed()`` calls and+ drops everything inside a span (including the system-note line). Create a+ fresh scrubber (or ``reset()``) per top-level response; call ``flush()`` at+ end of stream."""_OPEN_TAG = "<memory-context>"_CLOSE_TAG = "</memory-context>"def __init__(self) -> None:+ self.reset()++ def reset(self) -> None:self._in_span: bool = Falseself._buf: str = ""self._at_block_boundary: bool = True- def reset(self) -> None:- self._in_span = False- self._buf = ""- self._at_block_boundary = True-def feed(self, text: str) -> str:- """Return the visible portion of ``text`` after scrubbing.-- Any trailing fragment that could be the start of an open/close tag- is held back in the internal buffer and surfaced on the next- ``feed()`` call or discarded/emitted by ``flush()``.- """+ """Return the visible portion of ``text``; a possible partial tag tail is held for the next call."""if not text:return ""buf = self._buf + text@@ -304,28 +276,23 @@ class StreamingContextScrubber:if self._in_span:idx = buf.lower().find(self._CLOSE_TAG)if idx == -1:- # Hold back a potential partial close tag; drop the rest+ # Hold back a potential partial close tag; drop the rest.held = self._max_partial_suffix(buf, self._CLOSE_TAG)self._buf = buf[-held:] if held else ""return "".join(out)- # Found close — skip span content + tag, continuebuf = buf[idx + len(self._CLOSE_TAG):]self._in_span = Falseelse:idx = self._find_boundary_open_tag(buf)if idx == -1:- # No open tag — hold back a potential partial open tagheld = (self._max_pending_open_suffix(buf)or self._max_partial_suffix(buf, self._OPEN_TAG))+ self._append_visible(out, buf[:-held] if held else buf)if held:- self._append_visible(out, buf[:-held])self._buf = buf[-held:]- else:- self._append_visible(out, buf)return "".join(out)- # Emit text before the tag, enter spanif idx > 0:self._append_visible(out, buf[:idx])buf = buf[idx + len(self._OPEN_TAG):]@@ -334,12 +301,11 @@ class StreamingContextScrubber:return "".join(out)def flush(self) -> str:- """Emit any held-back buffer at end-of-stream.+ """Emit the held-back tail at end-of-stream.- If we're still inside an unterminated span the remaining content is- discarded (safer: leaking partial memory context is worse than a- truncated answer). Otherwise the held-back partial-tag tail is- emitted verbatim (it turned out not to be a real tag).+ Inside an unterminated span the remainder is discarded — leaking partial+ memory context is worse than a truncated answer. Otherwise the held tail+ was not a real tag and is emitted verbatim."""if self._in_span:self._buf = ""@@ -351,20 +317,16 @@ class StreamingContextScrubber:@staticmethoddef _max_partial_suffix(buf: str, tag: str) -> int:- """Return the length of the longest buf-suffix that is a tag-prefix.-- Case-insensitive. Returns 0 if no suffix could start the tag.- """+ """Length of the longest buf-suffix that is a (case-insensitive) prefix of ``tag``, else 0."""tag_lower = tag.lower()buf_lower = buf.lower()- max_check = min(len(buf_lower), len(tag_lower) - 1)- for i in range(max_check, 0, -1):+ for i in range(min(len(buf_lower), len(tag_lower) - 1), 0, -1):if tag_lower.startswith(buf_lower[-i:]):return ireturn 0def _find_boundary_open_tag(self, buf: str) -> int:- """Find an opening fence only when it starts a block-like span."""+ """Find an opening fence only when it starts a block-like span (own line, newline after)."""buf_lower = buf.lower()search_start = 0while True:@@ -376,19 +338,16 @@ class StreamingContextScrubber:search_start = idx + 1def _max_pending_open_suffix(self, buf: str) -> int:- """Hold a complete boundary tag until the following char confirms it."""+ """Hold a complete boundary tag at the buffer end until the following char confirms it."""if not buf.lower().endswith(self._OPEN_TAG):return 0- idx = len(buf) - len(self._OPEN_TAG)- if not self._is_block_boundary(buf, idx):+ if not self._is_block_boundary(buf, len(buf) - len(self._OPEN_TAG)):return 0return len(self._OPEN_TAG)def _has_block_opener_suffix(self, buf: str, idx: int) -> bool:after_idx = idx + len(self._OPEN_TAG)- if after_idx >= len(buf):- return False- return buf[after_idx] in "\r\n"+ return after_idx < len(buf) and buf[after_idx] in "\r\n"def _is_block_boundary(self, buf: str, idx: int) -> bool:if idx == 0:@@ -403,9 +362,6 @@ class StreamingContextScrubber:if not text:returnout.append(text)- self._update_block_boundary(text)-- def _update_block_boundary(self, text: str) -> None:last_newline = text.rfind("\n")if last_newline != -1:self._at_block_boundary = text[last_newline + 1:].strip() == ""@@ -430,17 +386,22 @@ def build_memory_context_block(raw_context: str) -> str:)+def _nonblank(text: Any) -> Any:+ """Return ``text`` when it has non-whitespace content, else None."""+ return text if text and text.strip() else None++class MemoryManager:"""Orchestrates the built-in provider plus at most one external provider.- The builtin provider is always first. Only one non-builtin (external)- provider is allowed. Failures in one provider never block the other.+ The builtin provider is always first. Failures in one provider never block+ the other: every fan-out hook logs and swallows per-provider exceptions."""def __init__(self, *, external_prefetch_timeout: Optional[float] = None) -> None:self._providers: List[MemoryProvider] = []self._tool_to_provider: Dict[str, MemoryProvider] = {}- self._has_external: bool = False # True once a non-builtin provider is added+ self._has_external: bool = Falseself._external_prefetch_timeout = (_EXTERNAL_PREFETCH_TIMEOUT_Sif external_prefetch_timeout is None@@ -450,15 +411,13 @@ class MemoryManager:raise ValueError("external_prefetch_timeout must be positive")self._external_prefetch_threads: Dict[str, threading.Thread] = {}self._external_prefetch_lock = threading.Lock()- # Background executor for end-of-turn sync/prefetch. Lazily created on- # first use so the common builtin-only path spawns no extra threads.- # A single worker serializes a provider's writes (turn N must land- # before turn N+1) and caps thread growth at one per manager. See- # _submit_background() and the sync_all/queue_prefetch_all rationale.+ # Single-worker background executor for end-of-turn sync/prefetch,+ # created lazily so the builtin-only path spawns no threads. One worker+ # serializes a provider's writes (turn N lands before turn N+1).self._sync_executor: Optional[ThreadPoolExecutor] = Noneself._sync_executor_lock = threading.Lock()- # Futures are tracked by durability class so shutdown can give writes- # a bounded FIFO drain, then explicitly report anything abandoned.+ # Futures tracked by durability class ("write" / "prefetch") so shutdown+ # can drain FIFO within a bound, then report exactly what it abandoned.self._background_futures: Dict[Future, str] = {}self._shutting_down = Falseself._shutdown_drain_state: Dict[str, Any] = {@@ -468,18 +427,38 @@ class MemoryManager:"active_tasks": 0,}- # -- Registration ---------------------------------------------------------- def add_provider(self, provider: MemoryProvider) -> None:- """Register a memory provider.+ # -- Fan-out helper ------------------------------------------------------- Built-in provider (name ``"builtin"``) is always accepted.- Only **one** external (non-builtin) provider is allowed — a second- attempt is rejected with a warning.+ def _each_provider(+ self,+ label: str,+ call: Callable[[MemoryProvider], Any],+ *,+ level: int = logging.DEBUG,+ providers: Optional[List[MemoryProvider]] = None,+ exc_info: bool = False,+ ) -> List[Any]:+ """Call ``call(provider)`` for each provider, logging and swallowing failures.++ ``label`` completes the log line ``Memory provider '<name>' <label>: <exc>``.+ Returns the successful results in provider order."""- is_builtin = provider.name == "builtin"+ results: List[Any] = []+ for provider in self._providers if providers is None else providers:+ try:+ results.append(call(provider))+ except Exception as e:+ logger.log(+ level, "Memory provider '%s' %s: %s", provider.name, label, e,+ exc_info=exc_info,+ )+ return results++ # -- Registration --------------------------------------------------------- if not is_builtin:+ def add_provider(self, provider: MemoryProvider) -> None:+ """Register a provider; builtin always accepted, only ONE external allowed."""+ if provider.name != "builtin":if self._has_external:existing = next((p.name for p in self._providers if p.name != "builtin"), "unknown"@@ -496,18 +475,14 @@ class MemoryManager:self._providers.append(provider)- # Core tool names are reserved — a memory provider must never register- # a tool that shadows a built-in (e.g. ``clarify``, ``delegate_task``).- # Built-ins always win, so such a tool is dropped at agent init and- # would otherwise linger in ``_tool_to_provider`` and hijack dispatch- # (#40466). Reject it here, at the door, so it never enters the routing- # table at all — matching the built-ins-always-win invariant used by- # the TTS/browser/search provider registries.+ # Core tool names are reserved: built-ins always win at agent init, so a+ # shadowing provider tool would linger in ``_tool_to_provider`` and+ # hijack dispatch. Reject it at the door, like the TTS/browser/search+ # provider registries do.from toolsets import _HERMES_CORE_TOOLS_core_tool_names = set(_HERMES_CORE_TOOLS)- # Index tool names → provider for routingfor raw_schema in provider.get_tool_schemas():schema = normalize_tool_schema(raw_schema)if schema is None:@@ -520,9 +495,6 @@ class MemoryManager:"rename the provider's tool to something unique.",provider.name, tool_name,)- continue- if tool_name and tool_name not in self._tool_to_provider:- self._tool_to_provider[tool_name] = providerelif tool_name in self._tool_to_provider:logger.warning("Memory tool name conflict: '%s' already registered by %s, "@@ -531,6 +503,8 @@ class MemoryManager:self._tool_to_provider[tool_name].name,provider.name,)+ else:+ self._tool_to_provider[tool_name] = providerlogger.info("Memory provider '%s' registered (%d tools)",@@ -545,31 +519,18 @@ class MemoryManager:def get_provider(self, name: str) -> Optional[MemoryProvider]:"""Get a provider by name, or None if not registered."""- for p in self._providers:- if p.name == name:- return p- return None+ return next((p for p in self._providers if p.name == name), None)# -- System prompt -------------------------------------------------------def build_system_prompt(self) -> str:- """Collect system prompt blocks from all providers.-- Returns combined text, or empty string if no providers contribute.- Each non-empty block is labeled with the provider name.- """- blocks = []- for provider in self._providers:- try:- block = provider.system_prompt_block()- if block and block.strip():- blocks.append(block)- except Exception as e:- logger.warning(- "Memory provider '%s' system_prompt_block() failed: %s",- provider.name, e,- )- return "\n\n".join(blocks)+ """Join every provider's non-empty ``system_prompt_block()`` with blank lines."""+ blocks = self._each_provider(+ "system_prompt_block() failed",+ lambda p: _nonblank(p.system_prompt_block()),+ level=logging.WARNING,+ )+ return "\n\n".join(b for b in blocks if b)# -- Prefetch / recall ---------------------------------------------------@@ -577,45 +538,33 @@ class MemoryManager:def _strip_skill_scaffolding(text: str) -> Optional[str]:"""Return memory-worthy user text, or None to skip the turn.- When a user invokes a /skill or /bundle, Hermes expands the turn into- a model-facing message that embeds the entire skill body. Feeding that- verbatim to memory providers pollutes their stores/embeddings with- prompt scaffolding instead of what the user actually asked. We recover- just the user's instruction here, once, for every provider — so this- is fixed for the whole provider fan-out, not per backend.-- - Non-skill messages pass through unchanged.- - Skill turns with a user instruction return that instruction.- - Bare skill invocations (no instruction) return None → callers skip- the turn, since there is no user content worth remembering.+ A /skill or /bundle turn expands into a model-facing message embedding the+ whole skill body; feeding that to providers pollutes stores/embeddings with+ prompt scaffolding. Recover just the user's instruction once, for the whole+ fan-out. Non-skill text passes through; a bare invocation (no instruction)+ yields None since there is nothing worth remembering."""return extract_user_instruction_from_skill_message(text)def prefetch_all(self, query: str, *, session_id: str = "") -> str:- """Collect prefetch context from all providers.-- Returns merged context text labeled by provider. Empty providers- are skipped. Failures in one provider don't block others.- """+ """Merge non-empty prefetch context from all providers (failures are non-fatal)."""clean_query = self._strip_skill_scaffolding(query)if not clean_query:return ""- parts = []- for provider in self._providers:- try:- result = self._prefetch_provider(provider, clean_query, session_id=session_id)- if result and result.strip():- parts.append(result)- except Exception as e:- logger.debug(- "Memory provider '%s' prefetch failed (non-fatal): %s",- provider.name, e,- )- return "\n\n".join(parts)+ parts = self._each_provider(+ "prefetch failed (non-fatal)",+ lambda p: _nonblank(self._prefetch_provider(p, clean_query, session_id=session_id)),+ )+ return "\n\n".join(p for p in parts if p)def _prefetch_provider(self, provider: MemoryProvider, query: str, *, session_id: str = "") -> str:+ """Run one provider's prefetch; external providers are bounded by a timeout.++ A stuck external call is left running on its daemon thread and the+ provider is skipped on subsequent turns until that call returns.+ """if provider.name == "builtin":return provider.prefetch(query, session_id=session_id)@@ -628,13 +577,8 @@ class MemoryManager:except Exception as exc: # pragma: no cover - re-raised by callererror_box["value"] = exc- # Propagate the caller's contextvars (profile HERMES_HOME override)- # to the prefetch thread — see _submit_background.- import contextvars- from functools import partial-thread = threading.Thread(- target=partial(contextvars.copy_context().run, _run),+ target=_ctx_bound(_run),daemon=True,name=f"memory-prefetch-{provider.name}",)@@ -669,25 +613,16 @@ class MemoryManager:return result_box.get("value", "")def describe_recall(self) -> str:- """Build a deterministic, model-independent recall indicator line.-- Call right after :meth:`prefetch_all` on the turn thread. Collects each- provider's :meth:`MemoryProvider.recall_status` and renders a single- status string (e.g. ``"🧠 Provider — recalled 3 memories"``) so the- user SEES memory was used regardless of whether the model mentions it.- Returns ``""`` when no provider injected memory this turn — callers can- emit the result unconditionally.+ """Deterministic recall indicator line (e.g. ``"🧠 Provider — recalled 3 memories"``).++ Call right after :meth:`prefetch_all` so the user SEES memory was used+ regardless of whether the model mentions it. Returns ``""`` when no+ provider injected memory this turn, so callers can emit unconditionally."""segments: List[str] = []- for provider in self._providers:- try:- status = provider.recall_status()- except Exception as e:- logger.debug(- "Memory provider '%s' recall_status failed (non-fatal): %s",- provider.name, e,- )- continue+ for status in self._each_provider(+ "recall_status failed (non-fatal)", lambda p: p.recall_status()+ ):if status is None:continueif status.count == 1:@@ -701,12 +636,7 @@ class MemoryManager:return " ".join(segments)def queue_prefetch_all(self, query: str, *, session_id: str = "") -> None:- """Queue background prefetch on all providers for the next turn.-- Provider work is dispatched to a background worker so a slow or- wedged provider can never block the caller. See ``sync_all`` for- the full rationale (agent stuck "running" minutes after a turn).- """+ """Queue background prefetch on all providers for the next turn (see ``sync_all``)."""providers = list(self._providers)if not providers:return@@ -715,31 +645,22 @@ class MemoryManager:if not clean_query:return- def _run() -> None:- for provider in providers:- try:- provider.queue_prefetch(clean_query, session_id=session_id)- except Exception as e:- logger.debug(- "Memory provider '%s' queue_prefetch failed (non-fatal): %s",- provider.name, e,- )-- self._submit_background(_run, kind="prefetch")+ self._submit_background(+ lambda: self._each_provider(+ "queue_prefetch failed (non-fatal)",+ lambda p: p.queue_prefetch(clean_query, session_id=session_id),+ providers=providers,+ ),+ kind="prefetch",+ )# -- Sync ----------------------------------------------------------------@staticmethoddef _provider_sync_accepts_messages(provider: MemoryProvider) -> bool:- """Return whether sync_turn accepts a messages keyword."""- try:- signature = inspect.signature(provider.sync_turn)- except (TypeError, ValueError):- return True- params = list(signature.parameters.values())- if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params):- return True- return "messages" in signature.parameters+ """Whether ``sync_turn`` accepts a ``messages`` keyword (uninspectable → assume yes)."""+ params = _signature_params(provider.sync_turn)+ return params is None or _has_var_kwargs(params) or "messages" in paramsdef sync_all(self,@@ -749,22 +670,13 @@ class MemoryManager:session_id: str = "",messages: Optional[List[Dict[str, Any]]] = None,) -> None:- """Sync a completed turn to all providers.-- Runs on a background worker thread, NOT inline on the- turn-completion path. A provider's ``sync_turn`` may make a- blocking network/daemon call (a misconfigured Hindsight daemon- was observed blocking ~298s before failing); doing that inline- held ``run_conversation`` open long after the user saw their- response, so every interface (CLI, TUI, gateway) kept the agent- marked "running" for minutes and any follow-up message triggered- an aggressive interrupt. Dispatching off-thread means a slow or- broken provider can never stall the turn — the sync simply- completes (or fails, logged) in the background.-- Writes are serialized through a single worker so turn N lands- before turn N+1; provider implementations don't need their own- ordering guarantees.+ """Sync a completed turn to all providers on the background worker.++ Never inline: a provider's ``sync_turn`` may block on a network/daemon+ call for minutes, which kept ``run_conversation`` open after the user saw+ the response, so every interface showed the agent "running" and follow-up+ messages triggered interrupts. The single worker also serializes writes so+ turn N lands before turn N+1 without provider-side ordering logic."""providers = list(self._providers)if not providers:@@ -773,65 +685,47 @@ class MemoryManager:clean_user_content = self._strip_skill_scaffolding(user_content)if not clean_user_content:return- user_content = clean_user_content- def _run() -> None:- for provider in providers:- try:- if messages is not None and self._provider_sync_accepts_messages(provider):- provider.sync_turn(- user_content,- assistant_content,- session_id=session_id,- messages=messages,- )- else:- provider.sync_turn(- user_content,- assistant_content,- session_id=session_id,- )- except Exception as e:- logger.warning(- "Memory provider '%s' sync_turn failed: %s",- provider.name, e,- )+ def _sync(provider: MemoryProvider) -> None:+ kwargs: Dict[str, Any] = {"session_id": session_id}+ if messages is not None and self._provider_sync_accepts_messages(provider):+ kwargs["messages"] = messages+ provider.sync_turn(clean_user_content, assistant_content, **kwargs)- self._submit_background(_run)+ self._submit_background(+ lambda: self._each_provider(+ "sync_turn failed", _sync, level=logging.WARNING, providers=providers+ )+ )# -- Background dispatch -------------------------------------------------def _submit_background(self, fn, *, kind: str = "write") -> None:"""Queue ``fn`` on the serialized worker and track its durability class.- The submitted callable is wrapped with the CALLER's contextvars:- profile isolation in multi-profile processes (gateway multiplexer,- dashboard, cron) is a ContextVar-scoped HERMES_HOME override, and- executor worker threads start with empty contexts — without the- wrap, a provider resolving ambient state (config paths, secrets)- from the worker would silently land on the default profile.+ The callable runs under the caller's contextvars (see ``_ctx_bound``).+ If the executor is unavailable outside shutdown, fall back to running+ inline — the historical fail-safe (slow but correct)."""- import contextvars- from functools import partial+ fn = _ctx_bound(fn)++ def _run_inline() -> None:+ try:+ fn()+ except Exception as e: # pragma: no cover - fn guards internally+ logger.debug("Inline memory background task failed: %s", e)- ctx = contextvars.copy_context()- fn = partial(ctx.run, fn)executor = self._get_sync_executor()if executor is None:if self._shutting_down:logger.warning("Memory manager is shutting down; rejecting late %s task", kind)return- # Creation failure outside shutdown: preserve the historical- # fail-safe behavior and run the operation inline.- try:- fn()- except Exception as e: # pragma: no cover - fn guards internally- logger.debug("Inline memory background task failed: %s", e)+ _run_inline()returntry:- # Make submit+tracking atomic with the shutdown snapshot. The- # callback is attached after releasing the lock because an already- # completed future invokes callbacks synchronously.+ # Submit+track atomically with the shutdown snapshot. The callback is+ # attached outside the lock: an already-completed future invokes+ # callbacks synchronously.with self._sync_executor_lock:if self._shutting_down:logger.warning("Memory manager is shutting down; rejecting late %s task", kind)@@ -843,17 +737,14 @@ class MemoryManager:if self._shutting_down:logger.warning("Memory manager shut down during %s submission; task rejected", kind)return- try:- fn()- except Exception as e: # pragma: no cover - fn guards internally- logger.debug("Inline memory background task failed: %s", e)+ _run_inline()def _forget_background_future(self, future: Future) -> None:with self._sync_executor_lock:self._background_futures.pop(future, None)def _get_sync_executor(self) -> Optional[ThreadPoolExecutor]:- """Lazily create the single-worker background executor."""+ """Lazily create the single-worker background executor (None once shutting down)."""if self._shutting_down:return Noneif self._sync_executor is not None:@@ -863,8 +754,8 @@ class MemoryManager:return Noneif self._sync_executor is None:try:- # Daemon workers (see tools.daemon_pool): a provider wedged- # on a network call must never block interpreter exit.+ # Daemon workers: a provider wedged on a network call must+ # never block interpreter exit.from tools.daemon_pool import DaemonThreadPoolExecutorself._sync_executor = DaemonThreadPoolExecutor(max_workers=1,@@ -878,11 +769,9 @@ class MemoryManager:def flush_pending(self, timeout: Optional[float] = None) -> bool:"""Block until queued sync/prefetch work has drained.- Single-worker executor means submitting a sentinel and waiting on- it guarantees every previously-submitted task has run. Returns- True if the barrier completed within ``timeout`` (or no executor- exists), False on timeout. Used at real session boundaries and by- tests that need to assert provider state deterministically.+ With a single worker, a sentinel task completing proves every earlier+ task ran. Returns True when drained within ``timeout`` (or no executor+ exists), False on timeout."""executor = self._sync_executorif executor is None:@@ -901,40 +790,33 @@ class MemoryManager:# -- Tools ---------------------------------------------------------------def get_all_tool_schemas(self) -> List[Dict[str, Any]]:- """Collect tool schemas from all providers.+ """Collect deduplicated tool schemas from all providers.- Reserved core tool names (``clarify``, ``delegate_task``, etc.) are- skipped — they are rejected from the routing table in- :meth:`add_provider`, so the manager must not advertise a schema it- will never route. Built-ins always win (#40466).+ Reserved core tool names are skipped: :meth:`add_provider` refuses to+ route them, so the manager must not advertise a schema it never routes."""from toolsets import _HERMES_CORE_TOOLS_core_tool_names = set(_HERMES_CORE_TOOLS)- schemas = []+ schemas: List[Dict[str, Any]] = []seen = set()- for provider in self._providers:- try:- for raw_schema in provider.get_tool_schemas():- schema = normalize_tool_schema(raw_schema)- if schema is None:- logger.warning(- "Memory provider '%s' returned a tool schema with "- "no resolvable name; skipping (%r)",- provider.name, raw_schema,- )- continue- name = schema["name"]- if name in _core_tool_names:- continue- if name not in seen:- schemas.append(schema)- seen.add(name)- except Exception as e:- logger.warning(- "Memory provider '%s' get_tool_schemas() failed: %s",- provider.name, e,- )++ def _collect(provider: MemoryProvider) -> None:+ for raw_schema in provider.get_tool_schemas():+ schema = normalize_tool_schema(raw_schema)+ if schema is None:+ logger.warning(+ "Memory provider '%s' returned a tool schema with "+ "no resolvable name; skipping (%r)",+ provider.name, raw_schema,+ )+ continue+ name = schema["name"]+ if name not in _core_tool_names and name not in seen:+ schemas.append(schema)+ seen.add(name)++ self._each_provider("get_tool_schemas() failed", _collect, level=logging.WARNING)return schemasdef get_all_tool_names(self) -> set:@@ -948,11 +830,7 @@ class MemoryManager:def handle_tool_call(self, tool_name: str, args: Dict[str, Any], **kwargs) -> str:- """Route a tool call to the correct provider.-- Returns JSON string result. Raises ValueError if no provider- handles the tool.- """+ """Route a tool call to its provider; returns a JSON string (tool_error on failure)."""provider = self._tool_to_provider.get(tool_name)if provider is None:return tool_error(f"No memory provider handles tool '{tool_name}'")@@ -968,30 +846,20 @@ class MemoryManager:# -- Lifecycle hooks -----------------------------------------------------def on_turn_start(self, turn_number: int, message: str, **kwargs) -> None:- """Notify all providers of a new turn.-- kwargs may include: remaining_tokens, model, platform, tool_count.- """- for provider in self._providers:- try:- provider.on_turn_start(turn_number, message, **kwargs)- except Exception as e:- logger.debug(- "Memory provider '%s' on_turn_start failed: %s",- provider.name, e,- )+ """Notify all providers of a new turn (kwargs: remaining_tokens, model, platform, tool_count)."""+ self._each_provider(+ "on_turn_start failed",+ lambda p: p.on_turn_start(turn_number, message, **kwargs),+ )def on_session_end(self, messages: List[Dict[str, Any]]) -> None:"""Notify all providers of session end."""- for provider in self._providers:- try:- provider.on_session_end(messages)- except Exception as e:- logger.warning(- "Memory provider '%s' on_session_end failed: %s",- provider.name, e,- exc_info=True,- )+ self._each_provider(+ "on_session_end failed",+ lambda p: p.on_session_end(messages),+ level=logging.WARNING,+ exc_info=True,+ )def commit_session_boundary_async(self,@@ -1003,23 +871,12 @@ class MemoryManager:) -> None:"""Queue old-session extraction + provider rebinding as ONE serialized task.- Session rotation (/new) must deliver ``on_session_end`` (end-of-session- extraction — an LLM-bound call that can take seconds) strictly BEFORE- ``on_session_switch`` (which rebinds provider-internal ``_session_id`` /- turn buffers to the new session). Running extraction inline blocked the- /new command for the whole LLM round-trip (#16454); running it on an- ad-hoc thread raced the inline switch — providers key off internal- state, so a late ``on_session_end`` ran against post-switch bindings- (transcript misattributed to the new session id, double-ingest of the- old turn buffer, new-session buffers cleared).-- Submitting BOTH hooks as one task on the manager's single background- worker gives both properties at a single chokepoint: the caller returns- immediately, and the worker's FIFO order serializes end→switch against- every other provider write (per-turn ``sync_all``, prefetches), which- already share the same worker. If the executor is unavailable,- ``_submit_background`` degrades to inline execution — the pre-#16454- synchronous behavior, slow but correct.+ ``on_session_end`` (LLM-bound extraction, seconds) must run strictly+ BEFORE ``on_session_switch`` rebinds provider-internal session state;+ an ad-hoc thread raced the inline switch and misattributed transcripts+ to the new session. One task on the single FIFO worker gives both an+ immediate return and ordering against every other provider write. If+ the executor is unavailable, ``_submit_background`` runs it inline."""if not self._providers:return@@ -1051,64 +908,49 @@ class MemoryManager:rewound: bool = False,**kwargs,) -> None:- """Notify all providers that the agent's session_id has rotated.+ """Notify providers that ``AIAgent.session_id`` rotated without teardown.- Fires on ``/resume``, ``/branch``, ``/reset``, ``/new``, and- context compression — any path that reassigns- ``AIAgent.session_id`` without tearing the provider down.-- Providers keep running; they only need to refresh cached- per-session state so subsequent writes land in the correct- session's record. See ``MemoryProvider.on_session_switch`` for- the full contract.-- ``rewound=True`` signals that session_id is unchanged but the- transcript was truncated; providers caching per-turn document- state should invalidate.+ Fires on ``/resume``, ``/branch``, ``/reset``, ``/new`` and compression;+ providers refresh cached per-session state so later writes land in the+ right record. ``rewound=True`` (``/undo``) means the id is unchanged but+ the transcript was truncated."""if not new_session_id:return- # Only forward ``rewound`` when it's actually set. Passing it- # unconditionally would inject ``rewound=False`` into every- # provider's **kwargs for the common /resume, /branch, /new, and- # compression paths, polluting providers that capture extra kwargs- # (and breaking exact-dict assertions). The /undo path sets- # rewound=True explicitly; everyone else stays clean.+ # Forward ``rewound`` only when set: an unconditional ``rewound=False``+ # would pollute every provider's **kwargs on the common paths.if rewound:kwargs["rewound"] = True- for provider in self._providers:- try:- provider.on_session_switch(- new_session_id,- parent_session_id=parent_session_id,- reset=reset,- **kwargs,- )- except Exception as e:- logger.debug(- "Memory provider '%s' on_session_switch failed: %s",- provider.name, e,+ self._each_provider(+ "on_session_switch failed",+ lambda p: p.on_session_switch(+ new_session_id, parent_session_id=parent_session_id, reset=reset, **kwargs+ ),+ )++ @staticmethod+ def _checkpoint_api_version(provider: MemoryProvider) -> Optional[int]:+ """Provider's advertised pre-compress checkpoint API version; None if unparseable."""+ try:+ return int(+ getattr(+ provider,+ "pre_compress_checkpoint_api_version",+ _LEGACY_PRE_COMPRESS_API_VERSION,)+ )+ except (TypeError, ValueError):+ return Nonedef supports_pre_compress_checkpoint(self,api_version: int = PRE_COMPRESS_CHECKPOINT_API_VERSION,) -> bool:"""Return whether an active provider guarantees checkpoint API support."""- for provider in self._providers:- try:- provider_version = int(- getattr(- provider,- "pre_compress_checkpoint_api_version",- _LEGACY_PRE_COMPRESS_API_VERSION,- )- )- except (TypeError, ValueError):- continue- if provider_version >= api_version:- return True- return False+ return any(+ (version := self._checkpoint_api_version(p)) is not None and version >= api_version+ for p in self._providers+ )def on_pre_compress(self,@@ -1118,34 +960,20 @@ class MemoryManager:require_checkpoint: bool = False,checkpoint_api_version: int = PRE_COMPRESS_CHECKPOINT_API_VERSION,) -> str:- """Notify all providers before context compression.-- Returns combined text from providers to include in the compression- summary prompt. Empty string if no provider contributes.+ """Notify providers before compression; return their combined summary-prompt text.- ``messages`` is the raw transcript — the historical (API v1)- contract every existing provider receives unchanged.- ``evidence_messages`` is the host-normalized direct-evidence list- handed only to providers that opted into checkpoint API v2+; when- omitted, v2 providers receive the raw list too.-- When ``require_checkpoint`` is true, at least one provider- advertising the requested checkpoint API must return successfully;- its exception is propagated so the caller can preserve the+ ``messages`` is the raw transcript (the API v1 contract every provider+ gets). ``evidence_messages`` is the host-normalized evidence list handed+ only to checkpoint (v2+) providers; when omitted they get the raw list.+ With ``require_checkpoint``, at least one checkpoint provider must+ succeed — its exception propagates so the caller can keep theuncompressed transcript."""parts = []checkpoint_succeeded = Falsefor provider in self._providers:- try:- provider_version = int(- getattr(- provider,- "pre_compress_checkpoint_api_version",- _LEGACY_PRE_COMPRESS_API_VERSION,- )- )- except (TypeError, ValueError):+ provider_version = self._checkpoint_api_version(provider)+ if provider_version is None:provider_version = _LEGACY_PRE_COMPRESS_API_VERSIONis_checkpoint_provider = provider_version >= checkpoint_api_versionprovider_messages = messages@@ -1160,11 +988,8 @@ class MemoryManager:require_checkpoint=require_checkpoint,)else:- # Legacy (v1) providers keep the strict one-argument- # contract. v2 providers written against the original- # docs example (``def on_pre_compress(self, messages)``)- # also land here instead of dying on an unexpected- # kwarg — they simply never see the requirement signal.+ # v1 providers, and v2 providers with the bare one-argument+ # shape, never see the requirement signal.result = provider.on_pre_compress(provider_messages)if result and result.strip():parts.append(result)@@ -1187,29 +1012,12 @@ class MemoryManager:@staticmethoddef _provider_memory_write_metadata_mode(provider: MemoryProvider) -> str:- """Return how to pass metadata to a provider's memory-write hook."""- try:- signature = inspect.signature(provider.on_memory_write)- except (TypeError, ValueError):+ """How to pass metadata to ``on_memory_write``: "keyword", "positional", or "legacy" (none)."""+ params = _signature_params(provider.on_memory_write)+ if params is None or _has_var_kwargs(params) or "metadata" in params:return "keyword"-- params = list(signature.parameters.values())- if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params):- return "keyword"- if "metadata" in signature.parameters:- return "keyword"-- accepted = [- p for p in params- if p.kind in {- inspect.Parameter.POSITIONAL_ONLY,- inspect.Parameter.POSITIONAL_OR_KEYWORD,- inspect.Parameter.KEYWORD_ONLY,- }- ]- if len(accepted) >= 4:- return "positional"- return "legacy"+ accepted = sum(p.kind is not inspect.Parameter.VAR_POSITIONAL for p in params.values())+ return "positional" if accepted >= 4 else "legacy"def on_memory_write(self,@@ -1218,42 +1026,34 @@ class MemoryManager:content: str,metadata: Optional[Dict[str, Any]] = None,) -> None:- """Notify external providers when the built-in memory tool writes.+ """Notify external providers when the built-in memory tool writes (skips builtin, the source)."""++ def _notify(provider: MemoryProvider) -> None:+ mode = self._provider_memory_write_metadata_mode(provider)+ if mode == "keyword":+ provider.on_memory_write(action, target, content, metadata=dict(metadata or {}))+ elif mode == "positional":+ provider.on_memory_write(action, target, content, dict(metadata or {}))+ else:+ provider.on_memory_write(action, target, content)- Skips the builtin provider itself (it's the source of the write).- """- for provider in self._providers:- if provider.name == "builtin":- continue- try:- metadata_mode = self._provider_memory_write_metadata_mode(provider)- if metadata_mode == "keyword":- provider.on_memory_write(- action, target, content, metadata=dict(metadata or {})- )- elif metadata_mode == "positional":- provider.on_memory_write(action, target, content, dict(metadata or {}))- else:- provider.on_memory_write(action, target, content)- except Exception as e:- logger.debug(- "Memory provider '%s' on_memory_write failed: %s",- provider.name, e,- )+ self._each_provider(+ "on_memory_write failed",+ _notify,+ providers=[p for p in self._providers if p.name != "builtin"],+ )- # Actions the bridge mirrors to external providers. The built-in memory- # tool can also return non-mutating shapes (errors, staged-for-approval- # records); those are filtered out by ``notify_memory_tool_write`` before- # we ever reach a provider.+ # Actions the bridge mirrors to external providers. Non-mutating tool result+ # shapes (errors, staged-for-approval) are filtered by+ # ``notify_memory_tool_write`` before reaching a provider._MIRRORED_MEMORY_ACTIONS = {"add", "replace", "remove"}@staticmethoddef _memory_tool_result_succeeded(result: Any) -> bool:"""True only when the built-in memory tool actually committed a write.- Fails closed: a string that isn't JSON, a non-dict result, a missing- ``success``, or a write staged for approval (``staged is True``) all- return False so external providers are never told about a write that+ Fails closed: non-JSON, non-dict, missing ``success``, or a write staged+ for approval all return False so providers never mirror a write thatdid not land."""if isinstance(result, str):@@ -1274,35 +1074,25 @@ class MemoryManager:) -> None:"""Mirror a built-in memory tool call to external providers.- This is the single entry point the agent loop calls after running the- built-in ``memory`` tool. All the decisions about *whether* and *what*- to mirror live here, behind the manager interface — the loop only hands- over the raw tool result and args:-- * gate on a committed (non-staged, successful) write,- * expand the single-op and batched (``operations``) shapes,- * keep only mutating actions (add/replace/remove),- * build per-op provenance metadata and forward ``old_text``.-- ``build_metadata`` is an optional agent-side callable (the loop knows- session/task/tool-call provenance the manager does not) invoked once per- mirrored op.+ Single entry point the agent loop calls after the ``memory`` tool runs:+ gates on a committed write, expands single-op and batched ``operations``+ shapes, keeps only mutating actions, and forwards ``old_text`` plus the+ per-op provenance from ``build_metadata`` (the loop knows session/task/+ tool-call identity the manager does not)."""if not self._memory_tool_result_succeeded(tool_result):returntarget = str(tool_args.get("target") or "memory")operations = tool_args.get("operations")- if isinstance(operations, list) and operations:- raw_operations = operations- else:- raw_operations = [{+ if not (isinstance(operations, list) and operations):+ operations = [{"action": tool_args.get("action"),"content": tool_args.get("content"),"old_text": tool_args.get("old_text"),}]- for op in raw_operations:+ for op in operations:if not isinstance(op, dict):continueaction = str(op.get("action") or "")@@ -1325,35 +1115,20 @@ class MemoryManager:def on_delegation(self, task: str, result: str, *,child_session_id: str = "", **kwargs) -> None:"""Notify all providers that a subagent completed."""- for provider in self._providers:- try:- provider.on_delegation(- task, result, child_session_id=child_session_id, **kwargs- )- except Exception as e:- logger.debug(- "Memory provider '%s' on_delegation failed: %s",- provider.name, e,- )+ self._each_provider(+ "on_delegation failed",+ lambda p: p.on_delegation(task, result, child_session_id=child_session_id, **kwargs),+ )def shutdown_all(self) -> None:- """Shut down all providers (reverse order for clean teardown).-- Drains the background sync/prefetch executor first (bounded by- ``_SYNC_DRAIN_TIMEOUT_S``) so a turn's final sync has a chance to- land before providers are torn down. The worker threads are- daemon, so anything still wedged past the drain window dies with- the interpreter rather than blocking exit.- """+ """Drain the background executor (bounded), then shut providers down in reverse order."""self._drain_sync_executor()- for provider in reversed(self._providers):- try:- provider.shutdown()- except Exception as e:- logger.warning(- "Memory provider '%s' shutdown failed: %s",- provider.name, e,- )+ self._each_provider(+ "shutdown failed",+ lambda p: p.shutdown(),+ level=logging.WARNING,+ providers=list(reversed(self._providers)),+ )@propertydef shutdown_drain_state(self) -> Dict[str, Any]:@@ -1377,9 +1152,9 @@ class MemoryManager:if executor is None:return- # shutdown(wait=False) closes submission without touching the FIFO.- # Waiting on the tracked futures lets the real single-worker executor- # run every queued write/boundary task in order up to the deadline.+ # shutdown(wait=False) closes submission without touching the FIFO;+ # waiting on the tracked futures lets the worker run every queued+ # write/boundary task in order up to the deadline.executor.shutdown(wait=False, cancel_futures=False)_, pending = wait(tuple(tracked), timeout=_SYNC_DRAIN_TIMEOUT_S)if not pending:@@ -1387,18 +1162,14 @@ class MemoryManager:self._shutdown_drain_state.update(status="drained", active_tasks=0)return- abandoned_writes = 0- abandoned_prefetches = 0- active_tasks = 0+ abandoned_writes = abandoned_prefetches = active_tasks = 0for future in pending:- kind = tracked[future]- if future.cancel():- if kind == "prefetch":- abandoned_prefetches += 1- else:- abandoned_writes += 1- else:+ if not future.cancel():active_tasks += 1+ elif tracked[future] == "prefetch":+ abandoned_prefetches += 1+ else:+ abandoned_writes += 1with self._sync_executor_lock:self._shutdown_drain_state.update(@@ -1417,20 +1188,12 @@ class MemoryManager:)def initialize_all(self, session_id: str, **kwargs) -> None:- """Initialize all providers.-- Automatically injects ``hermes_home`` into *kwargs* so that every- provider can resolve profile-scoped storage paths without importing- ``get_hermes_home()`` themselves.- """+ """Initialize all providers, injecting ``hermes_home`` so they resolve profile-scoped paths."""if "hermes_home" not in kwargs:from hermes_constants import get_hermes_homekwargs["hermes_home"] = str(get_hermes_home())- for provider in self._providers:- try:- provider.initialize(session_id=session_id, **kwargs)- except Exception as e:- logger.warning(- "Memory provider '%s' initialize failed: %s",- provider.name, e,- )+ self._each_provider(+ "initialize failed",+ lambda p: p.initialize(session_id=session_id, **kwargs),+ level=logging.WARNING,+ )diff --git a/agent/memory_provider.py b/agent/memory_provider.pyindex 014f8955032..c27b736ae22 100644--- a/agent/memory_provider.py+++ b/agent/memory_provider.py@@ -1,34 +1,11 @@"""Abstract base class for pluggable memory providers.-Memory providers give the agent persistent recall across sessions.-The MemoryManager enforces a one-external-provider limit to prevent-tool schema bloat and conflicting memory backends.--External providers (Honcho, Hindsight, Mem0, etc.) are registered-and managed via MemoryManager. Only one external provider runs at a-time.--Registration:- Plugins ship in plugins/memory/<name>/ and are activated via- the memory.provider config key.--Lifecycle (called by MemoryManager, wired in run_agent.py):- initialize() — connect, create resources, warm up- system_prompt_block() — static text for the system prompt- prefetch(query) — background recall before each turn- sync_turn(user, asst) — async write after each turn- get_tool_schemas() — tool schemas to expose to the model- handle_tool_call() — dispatch a tool call- shutdown() — clean exit--Optional hooks (override to opt in):- on_turn_start(turn, message, **kwargs) — per-turn tick with runtime context- on_session_end(messages) — end-of-session extraction- on_session_switch(new_session_id, **kwargs) — mid-process session_id rotation- on_pre_compress(messages) -> str — extract before context compression- on_memory_write(action, target, content, metadata=None) — mirror built-in memory writes- on_delegation(task, result, **kwargs) — parent-side observation of subagent work- backup_paths() -> list[str] — extra on-disk paths to include in `hermes backup`+Memory providers give the agent persistent recall across sessions. Plugins+ship in ``plugins/memory/<name>/`` and are activated via ``memory.provider``;+MemoryManager allows only ONE external provider at a time (tool-schema bloat,+conflicting backends). Lifecycle is driven by MemoryManager: initialize ->+system_prompt_block / prefetch / sync_turn per turn -> tool dispatch ->+shutdown, plus the optional ``on_*`` hooks below."""from __future__ import annotations@@ -41,43 +18,30 @@ from typing import Any, Dict, List, Optionallogger = logging.getLogger(__name__)-# Version 1 is the historical, implicit contract every provider is already-# on: best-effort on_pre_compress() with the raw message list. Version 2 is-# the opt-in fail-closed checkpoint contract (normalized evidence handoff +-# strict-mode failure propagation).+# v1 = historical implicit contract (best-effort on_pre_compress() with the raw+# message list); v2 = opt-in fail-closed checkpoint (normalized evidence handoff+# + strict-mode failure propagation).PRE_COMPRESS_CHECKPOINT_API_VERSION = 2-# Default glyph for the deterministic memory indicators. Providers override-# per-status with their own brand mark (e.g. Hindsight uses "👁️").+# Default glyph for recall indicators; providers may use their own brand mark.INDICATOR_GLYPH = "🧠"@dataclass(frozen=True)class RecallStatus:- """Summary of what a provider's most recent prefetch injected this turn.-- Returned by :meth:`MemoryProvider.recall_status` so the agent can emit a- deterministic, model-independent "memory was used" indicator (see- ``MemoryManager.describe_recall``). ``count`` is the number of discrete- memories injected; ``0`` means content was injected but has no discrete- count (e.g. a synthesized reflect answer), which the indicator renders- generically rather than as "0 memories". ``glyph`` is the brand mark the- indicator leads with.- """+ """What the last prefetch injected, for the deterministic recall indicator+ (``MemoryManager.describe_recall``). ``count == 0`` means content without a+ discrete count (e.g. a synthesized reflect answer) and renders generically."""provider_label: strcount: intglyph: str = INDICATOR_GLYPH-# Prompts that carry no semantic signal — trivial acknowledgements, greetings,-# slash commands, empty input. Single source of truth shared by the core-# per-turn prefetch gate (agent/turn_context.py, run_agent.py) and provider--# side classifiers (plugins/memory/honcho) so the two can never drift apart.-# The alternation is anchored and may only be followed by whitespace or-# punctuation, so words that merely START with a trivial word ("k8s", "yolo",-# "note", "hindsight") do NOT match, while trailing-punctuation variants-# ("hi!", "hey.", "thanks :)", "done???") do.+# Prompts with no semantic signal. Single source of truth for the core prefetch+# gate (turn_context.py, run_agent.py) and provider-side classifiers (honcho).+# Anchored and followed only by whitespace/punctuation, so "k8s"/"yolo"/"note"+# do NOT match while "hi!"/"thanks :)"/"done???" do.TRIVIAL_PROMPT_RE = re.compile(r'^(yes|no|ok|okay|sure|thanks|thank you|y|n|yep|nope|yeah|nah|'r'hi|hey|hello|yo|sup|'@@ -88,21 +52,13 @@ TRIVIAL_PROMPT_RE = re.compile(def is_trivial_prompt(text: Optional[str]) -> bool:- """Return True if a user prompt is too trivial to warrant memory recall.-- Empty/whitespace-only input, slash commands, and bare greetings or- acknowledgements (with optional trailing punctuation) all count as- trivial. Callers use this to skip memory-provider prefetch/injection- on turns that carry no semantic signal — saving a blocking network- round-trip and preventing stale user-model context from derailing- one-word replies.+ """True for empty input, slash commands and bare greetings/acknowledgements.++ Skipping recall on these saves a blocking network round-trip and keeps+ stale user-model context from derailing one-word replies."""- if not text:- return True- stripped = text.strip()- if not stripped:- return True- if stripped.startswith("/"):+ stripped = (text or "").strip()+ if not stripped or stripped.startswith("/"):return Truereturn bool(TRIVIAL_PROMPT_RE.match(stripped))@@ -110,10 +66,8 @@ def is_trivial_prompt(text: Optional[str]) -> bool:class MemoryProvider(ABC):"""Abstract base class for memory providers."""- # Providers that durably checkpoint every successful on_pre_compress()- # call may opt into that host contract by setting the current version- # (PRE_COMPRESS_CHECKPOINT_API_VERSION). Version 1 is the implicit- # historical contract: best-effort semantics, raw message list.+ # Providers that durably checkpoint every successful on_pre_compress() opt+ # in by setting PRE_COMPRESS_CHECKPOINT_API_VERSION; 1 = best-effort legacy.pre_compress_checkpoint_api_version = 1@property@@ -125,89 +79,47 @@ class MemoryProvider(ABC):@abstractmethoddef is_available(self) -> bool:- """Return True if this provider is configured, has credentials, and is ready.-- Called during agent init to decide whether to activate the provider.- Should not make network calls — just check config and installed deps.- """+ """Configured, credentialed and ready? Gates activation at agent init;+ check config/deps only — no network calls."""@abstractmethoddef initialize(self, session_id: str, **kwargs) -> None:- """Initialize for a session.-- Called once at agent startup. May create resources (banks, tables),- establish connections, start background threads, etc.-- kwargs always include:- - hermes_home (str): The active HERMES_HOME directory path. Use this- for profile-scoped storage instead of hardcoding ``~/.hermes``.- - platform (str): "cli", "telegram", "discord", "cron", etc.-- kwargs may also include:- - agent_context (str): "primary", "subagent", "cron", or "flush".- Providers should skip writes for non-primary contexts (cron system- prompts would corrupt user representations).- - agent_identity (str): Profile name (e.g. "coder"). Use for- per-profile provider identity scoping.- - agent_workspace (str): Shared workspace name (e.g. "hermes").- - parent_session_id (str): For subagents, the parent's session_id.- - user_id (str): Platform user identifier (gateway sessions).- - user_id_alt (str): Optional alternate stable platform user identifier.+ """Initialize once at agent startup (connections, resources, threads).++ kwargs always include ``hermes_home`` (use it for profile-scoped storage,+ never hardcode ``~/.hermes``) and ``platform``. May include+ ``agent_context`` ("primary" | "subagent" | "cron" | "flush" — skip+ writes for non-primary contexts, cron prompts would corrupt user+ representations), ``agent_identity`` (profile name), ``agent_workspace``,+ ``parent_session_id``, ``user_id``, ``user_id_alt``."""def unavailable_reason(self) -> str:- """Actionable reason this provider reports unavailable, for the caller.-- ``is_available()`` gates initialization, so a provider that reports- unavailable is never initialized — any diagnostic it would log from- ``initialize()`` is unreachable. Return a short, user-facing hint here- (e.g. which package to install) so the caller's "provider unavailable"- warning can surface it. Empty string (the default) adds nothing.- """+ """Short user-facing hint for the "provider unavailable" warning (e.g.+ which package to install) — ``initialize()`` never runs when unavailable,+ so this is the only place such a diagnostic can surface."""return ""def system_prompt_block(self) -> str:- """Return text to include in the system prompt.-- Called during system prompt assembly. Return empty string to skip.- This is for STATIC provider info (instructions, status). Prefetched- recall context is injected separately via prefetch().- """+ """STATIC system-prompt text (instructions, status); "" to skip.+ Recalled context goes through prefetch(), not here."""return ""def prefetch(self, query: str, *, session_id: str = "") -> str:- """Recall relevant context for the upcoming turn.-- Called before each API call. Return formatted text to inject as- context, or empty string if nothing relevant. Implementations- should be fast — use background threads for the actual recall- and return cached results here.+ """Formatted recall context for the upcoming turn ("" if none).- session_id is provided for providers serving concurrent sessions- (gateway group chats, cached agents). Providers that don't need- per-session scoping can ignore it.+ Must be fast — do the recall in the background and return cached+ results. ``session_id`` scopes concurrent sessions (gateway, cached agents)."""return ""def queue_prefetch(self, query: str, *, session_id: str = "") -> None:- """Queue a background recall for the NEXT turn.-- Called after each turn completes. The result will be consumed- by prefetch() on the next turn. Default is no-op — providers- that do background prefetching should override this.- """+ """Queue a background recall after each turn; prefetch() consumes it next turn."""def recall_status(self) -> Optional[RecallStatus]:- """Describe what the most recent :meth:`prefetch` injected, for the UI.-- Called by the agent right after prefetch, on the same (single) turn- thread, so it can surface a deterministic "👁️ recalled N memories"- status line that does not depend on the model choosing to mention it.-- Return ``None`` (the default) when this provider injected nothing this- turn or does not want a visible indicator. Providers that override it- must reflect only the LAST prefetch — never a stale prior count.- """+ """What the most recent :meth:`prefetch` injected, for a deterministic+ "recalled N memories" indicator. ``None`` = nothing / no indicator.+ Must reflect only the LAST prefetch, never a stale prior count."""return Nonedef sync_turn(@@ -218,32 +130,16 @@ class MemoryProvider(ABC):session_id: str = "",messages: Optional[List[Dict[str, Any]]] = None,) -> None:- """Persist a completed turn to the backend.-- Called after each turn. Should be non-blocking — queue for- background processing if the backend has latency.-- ``messages`` is the OpenAI-style conversation message list as of the- completed turn, including any assistant tool calls and tool results.- Providers that do not need raw turn context can ignore it.- """+ """Persist a completed turn; should be non-blocking. ``messages`` is the+ OpenAI-style list as of this turn, including tool calls/results."""@abstractmethoddef get_tool_schemas(self) -> List[Dict[str, Any]]:- """Return tool schemas this provider exposes.-- Each schema follows the OpenAI function calling format:- {"name": "...", "description": "...", "parameters": {...}}-- Return empty list if this provider has no tools (context-only).- """+ """OpenAI function-calling schemas ({"name", "description", "parameters"});+ [] for context-only providers."""def handle_tool_call(self, tool_name: str, args: Dict[str, Any], **kwargs) -> str:- """Handle a tool call for one of this provider's tools.-- Must return a JSON string (the tool result).- Only called for tool names returned by get_tool_schemas().- """+ """Handle one of this provider's tools; must return a JSON string."""raise NotImplementedError(f"Provider {self.name} does not handle tool {tool_name}")def shutdown(self) -> None:@@ -252,23 +148,12 @@ class MemoryProvider(ABC):# -- Optional hooks (override to opt in) ---------------------------------def on_turn_start(self, turn_number: int, message: str, **kwargs) -> None:- """Called at the start of each turn with the user message.-- Use for turn-counting, scope management, periodic maintenance.-- kwargs may include: remaining_tokens, model, platform, tool_count.- Providers use what they need; extras are ignored.- """+ """Per-turn tick (turn-counting, scope management, maintenance).+ kwargs may include remaining_tokens, model, platform, tool_count."""def on_session_end(self, messages: List[Dict[str, Any]]) -> None:- """Called when a session ends (explicit exit or timeout).-- Use for end-of-session fact extraction, summarization, etc.- messages is the full conversation history.-- NOT called after every turn — only at actual session boundaries- (CLI exit, /reset, gateway session expiry).- """+ """End-of-session extraction over the full history. Fires only at real+ session boundaries (CLI exit, /reset, gateway expiry), never per-turn."""def on_session_switch(self,@@ -279,104 +164,43 @@ class MemoryProvider(ABC):rewound: bool = False,**kwargs,) -> None:- """Called when the agent switches session_id mid-process.-- Fires on ``/resume``, ``/branch``, ``/reset``, ``/new`` (CLI), the- gateway equivalents, and context compression — any path that- reassigns ``AIAgent.session_id`` without tearing the provider down.-- Providers that cache per-session state in ``initialize()``- (``_session_id``, ``_document_id``, accumulated turn buffers,- counters) should update or reset that state here so subsequent- writes land in the correct session's record.-- Parameters- ----------- new_session_id:- The session_id the agent just switched to.- parent_session_id:- The previous session_id, if meaningful — set for ``/branch``- (fork lineage), context compression (continuation lineage),- and ``/resume`` (the session we're leaving). Empty string- when no lineage applies.- reset:- ``True`` when this is a genuinely new conversation, not a- resumption of an existing one. Fired by ``/reset`` / ``/new``.- Providers should flush accumulated per-session buffers- (``_session_turns``, ``_turn_counter``, etc.) when this is- set. ``False`` for ``/resume`` / ``/branch`` / compression- where the logical conversation continues under the new id.- rewound:- ``True`` if session_id is unchanged but the transcript was- truncated; providers caching per-turn document state should- invalidate.-- Default is no-op for backward compatibility.+ """session_id reassigned mid-process (/resume, /branch, /reset, /new,+ gateway equivalents, context compression) without a provider teardown.++ Update or reset any per-session state cached in ``initialize()`` so+ later writes land in the right record. ``parent_session_id`` carries+ lineage for /branch, compression and /resume ("" when none). ``reset``+ is True only for a genuinely new conversation (/reset, /new) — flush+ per-session buffers; False when the logical conversation continues+ under a new id. ``rewound``: same id but the transcript was truncated,+ so invalidate per-turn document state."""def on_pre_compress(self, messages: List[Dict[str, Any]]) -> str:- """Called before context compression discards old messages.-- Use to extract insights from messages about to be compressed.- messages is the list that will be summarized/discarded.-- Return text to include in the compression summary prompt so the- compressor preserves provider-extracted insights. Return empty- string for no contribution (backwards-compatible default).- """+ """Extract insights from ``messages`` about to be compressed; the returned+ text is fed into the compression summary prompt ("" = nothing)."""return ""def on_delegation(self, task: str, result: str, *,child_session_id: str = "", **kwargs) -> None:- """Called on the PARENT agent when a subagent completes.-- The parent's memory provider gets the task+result pair as an- observation of what was delegated and what came back. The subagent- itself has no provider session (skip_memory=True).-- task: the delegation prompt- result: the subagent's final response- child_session_id: the subagent's session_id- """+ """PARENT-side observation of a completed delegation (task prompt + final+ result); the subagent itself has no provider session (skip_memory=True)."""def get_config_schema(self) -> List[Dict[str, Any]]:- """Return config fields this provider needs for setup.-- Used by 'hermes memory setup' to walk the user through configuration.- Each field is a dict with:- key: config key name (e.g. 'api_key', 'mode')- description: human-readable description- secret: True if this should go to .env (default: False)- required: True if required (default: False)- default: default value (optional)- choices: list of valid values (optional)- type: text, integer, number, or boolean (optional)- minimum: numeric lower bound for integer/number fields (optional)- maximum: numeric upper bound for integer/number fields (optional)- step: numeric input step for Dashboard rendering (optional)- url: URL where user can get this credential (optional)- env_var: explicit env var name for secrets (default: auto-generated)-- Return empty list if no config needed (e.g. local-only providers).+ """Setup fields for ``hermes memory setup`` ([] if none).++ Each field: ``key``, ``description``, optional ``secret`` (goes to .env),+ ``required``, ``default``, ``choices``, ``type`` (text | integer |+ number | boolean), ``minimum`` / ``maximum`` / ``step`` (numeric,+ Dashboard rendering), ``url`` (where to get the credential), ``env_var``+ (explicit secret env var; default auto-generated)."""return []def save_config(self, values: Dict[str, Any], hermes_home: str) -> None:- """Write non-secret config to the provider's native location.-- Called by 'hermes memory setup' after collecting user inputs.- ``values`` contains only non-secret fields (secrets go to .env).- ``hermes_home`` is the active HERMES_HOME directory path.-- Providers with native config files (JSON, YAML) should override- this to write to their expected location. Providers that use only- env vars can leave the default (no-op).-- All new memory provider plugins MUST implement either:- - save_config() for native config file formats, OR- - use only env vars (in which case get_config_schema() fields- should all have ``env_var`` set and this method stays no-op).- """+ """Write non-secret setup ``values`` (secrets go to .env) to the provider's+ native config location. Plugins MUST either override this or use only+ env vars (every schema field carrying ``env_var``) and keep the no-op."""def on_memory_write(self,@@ -385,32 +209,14 @@ class MemoryProvider(ABC):content: str,metadata: Optional[Dict[str, Any]] = None,) -> None:- """Called when the built-in memory tool writes an entry.-- action: 'add', 'replace', or 'remove'- target: 'memory' or 'user'- content: the entry content- metadata: structured provenance for the write, when available. Common- keys include ``write_origin``, ``execution_context``, ``session_id``,- ``parent_session_id``, ``platform``, and ``tool_name``.-- Use to mirror built-in memory writes to your backend.- """+ """Mirror a built-in memory-tool write. ``action`` is add | replace |+ remove, ``target`` is memory | user; ``metadata`` (when available) has+ provenance such as write_origin, execution_context, session_id,+ parent_session_id, platform, tool_name."""def backup_paths(self) -> List[str]:- """Return extra on-disk paths this provider stores OUTSIDE HERMES_HOME.-- ``hermes backup`` only walks HERMES_HOME, so any provider state kept- under ``~/.honcho``, ``~/.hindsight``, ``~/.openviking``, etc. is lost- across a backup/import cycle unless it's declared here.-- Return a list of absolute path strings (files or directories). The- backup command resolves each, captures the ones that exist and live- under the user's home directory into a reserved ``_external/`` subtree- of the archive, and ``hermes import`` restores them to their original- locations. Paths outside the home directory are skipped for safety.-- MUST be callable without ``initialize()`` and without network — resolve- from config/env only. Default returns an empty list (nothing external).- """+ """Absolute paths of provider state OUTSIDE HERMES_HOME (e.g. ``~/.honcho``)+ so ``hermes backup`` can capture them under ``_external/`` and+ ``hermes import`` restore them; paths outside the home dir are skipped.+ MUST work without ``initialize()`` or network — resolve from config/env."""return []diff --git a/agent/provider_base.py b/agent/provider_base.pynew file mode 100644index 00000000000..470b1c0a6c0--- /dev/null+++ b/agent/provider_base.py@@ -0,0 +1,77 @@+"""Shared base classes for the pluggable-backend provider ABCs.++Every tool-provider ABC (browser, TTS, image/video gen, transcription, web+search, terminal env) shares the same identity + ``hermes tools`` picker+surface; the previous per-ABC copies of these defaults were byte-identical.+Concrete ABCs subclass :class:`ProviderBase` (or :class:`CatalogProviderBase`+when the backend also exposes a model catalog and is available by default) and+add only their domain methods. Plugins keep subclassing the concrete ABC, so+``isinstance`` checks and abstract-method sets are unchanged.+"""++from __future__ import annotations++import abc+from typing import Any, Dict, List, Optional+++class ProviderBase(abc.ABC):+ """Identity + picker metadata common to every provider ABC."""++ @property+ @abc.abstractmethod+ def name(self) -> str:+ """Stable short identifier used as the provider's config-key value.++ Lowercase, no spaces (hyphens allowed where they preserve an existing+ user-visible name). Registries key providers by this string.+ """++ @property+ def display_name(self) -> str:+ """Human-readable label shown in ``hermes tools``. Defaults to ``name``."""+ return self.name++ def get_setup_schema(self) -> Dict[str, Any]:+ """Provider row for the ``hermes tools`` picker.++ Shape: ``{"name", "badge", "tag", "env_vars": [{"key", "prompt", "url"}, ...]}``+ (browser providers may add ``"post_setup"``). Default: a minimal entry+ derived from ``display_name`` with no env vars — override to expose API+ key prompts and badges.+ """+ return {+ "name": self.display_name,+ "badge": "",+ "tag": "",+ "env_vars": [],+ }+++class CatalogProviderBase(ProviderBase):+ """Provider with a model catalog; available by default, ``display_name`` is title-cased."""++ @property+ def display_name(self) -> str:+ """Human-readable label shown in ``hermes tools``. Defaults to ``name.title()``."""+ return self.name.title()++ def is_available(self) -> bool:+ """True when this provider can service calls (API key present, SDK importable).++ Default True. Must NOT raise and must NOT make network calls — the picker+ and ``hermes setup`` call it on every paint.+ """+ return True++ def list_models(self) -> List[Dict[str, Any]]:+ """Model catalog entries (``{"id": ..., "display": ...}`` plus optional+ provider-specific keys). Default: empty (no user-selectable models)."""+ return []++ def default_model(self) -> Optional[str]:+ """Id of the first catalog entry, or None when the catalog is empty."""+ models = self.list_models()+ if models:+ return models[0].get("id")+ return Nonediff --git a/agent/provider_media.py b/agent/provider_media.pynew file mode 100644index 00000000000..ba69a003fd1--- /dev/null+++ b/agent/provider_media.py@@ -0,0 +1,112 @@+"""Shared ``$HERMES_HOME/cache/<kind>/`` materialisation helpers for the+image/video generation provider ABCs.++Several backends (xAI, OpenAI, DeepInfra, FAL) return *ephemeral* delivery URLs+that expire before a downstream consumer (Telegram ``send_photo``, browser+fetch) can resolve them, so providers materialise the bytes locally at+tool-completion time. Filenames are ``<prefix>_<YYYYMMDD_HHMMSS>_<uuid8>.<ext>``.+"""++from __future__ import annotations++import base64+import datetime+import uuid+from pathlib import Path+from typing import Dict, Tuple+++def cache_dir(kind: str) -> Path:+ """Return ``$HERMES_HOME/cache/<kind>/``, creating parents as needed."""+ from hermes_constants import get_hermes_home++ path = get_hermes_home() / "cache" / kind+ path.mkdir(parents=True, exist_ok=True)+ return path+++def cache_path(kind: str, prefix: str, extension: str) -> Path:+ ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")+ short = uuid.uuid4().hex[:8]+ return cache_dir(kind) / f"{prefix}_{ts}_{short}.{extension}"+++def save_bytes(kind: str, raw: bytes, *, prefix: str, extension: str) -> Path:+ """Write raw bytes to the cache and return the absolute path."""+ path = cache_path(kind, prefix, extension)+ path.write_bytes(raw)+ return path+++def save_b64(kind: str, b64_data: str, *, prefix: str, extension: str) -> Path:+ """Decode base64 data into the cache and return the absolute path."""+ return save_bytes(kind, base64.b64decode(b64_data), prefix=prefix, extension=extension)+++def save_url(+ kind: str,+ url: str,+ *,+ prefix: str,+ timeout: float,+ max_bytes: int,+ chunk_size: int,+ content_types: Dict[str, str],+ url_extensions: Tuple[str, ...],+ default_extension: str,+ label: str,+ empty_error: str,+) -> Path:+ """Stream-download *url* into the cache with a size cap.++ The extension comes from the response ``Content-Type`` (a small explicit+ table — never inherit a type that points at HTML/JSON from a degenerate+ response), then the URL suffix (some CDNs return+ ``application/octet-stream``), then *default_extension*. Raises on any+ network / HTTP / oversize / empty error so callers can fall back to the bare+ URL; a partial file is never left behind.+ """+ import requests++ response = requests.get(url, timeout=timeout, stream=True)+ response.raise_for_status()++ content_type = (response.headers.get("Content-Type") or "").split(";", 1)[0].strip().lower()+ extension = content_types.get(content_type)+ if extension is None:+ url_path = url.split("?", 1)[0].lower()+ for ext in url_extensions:+ if url_path.endswith(f".{ext}"):+ extension = "jpg" if ext == "jpeg" else ext+ break+ if extension is None:+ extension = default_extension++ path = cache_path(kind, prefix, extension)++ bytes_written = 0+ with path.open("wb") as fh:+ for chunk in response.iter_content(chunk_size=chunk_size):+ if not chunk:+ continue+ bytes_written += len(chunk)+ if bytes_written > max_bytes:+ fh.close()+ _unlink_quiet(path)+ raise ValueError(+ f"{label} at {url} exceeds {max_bytes // (1024 * 1024)}MB cap; refusing to cache."+ )+ fh.write(chunk)++ if bytes_written == 0:+ _unlink_quiet(path)+ raise ValueError(empty_error.format(url=url))++ return path+++def _unlink_quiet(path: Path) -> None:+ try:+ path.unlink()+ except OSError:+ passdiff --git a/agent/terminal_env_provider.py b/agent/terminal_env_provider.pyindex b7f28e5a1a3..3a862108fd0 100644--- a/agent/terminal_env_provider.py+++ b/agent/terminal_env_provider.py@@ -2,65 +2,42 @@Terminal Environment Provider ABC=================================-Defines the pluggable-backend interface for terminal execution environments-(cloud sandboxes, remote runners). Providers register instances via-:meth:`PluginContext.register_terminal_environment_provider`; the dispatch-ladder in :func:`tools.terminal_tool._create_environment` consults the-registry for any ``TERMINAL_ENV`` / ``terminal.backend`` value that is not a-built-in backend (local, docker, singularity, modal, daytona,-vercel_sandbox, ssh).--Providers live in ``~/.hermes/plugins/<name>/`` (user, opt-in via-``plugins.enabled``) or ship as standalone plugin repos. Built-in backends-stay in-tree under ``tools/environments/`` — this extension point exists so-third-party sandbox vendors do NOT have to live in core (see AGENTS.md:-"Third-party products ... ship them as a standalone plugin repo").--This ABC mirrors :class:`agent.browser_provider.BrowserProvider` — same-registration flow, same scope semantics, same plugin-context gating.+Pluggable-backend interface for terminal execution environments (cloud+sandboxes, remote runners). Providers register via+:meth:`PluginContext.register_terminal_environment_provider`;+:func:`tools.terminal_tool._create_environment` consults the registry for any+``TERMINAL_ENV`` / ``terminal.backend`` value that is not a built-in backend.+Built-ins stay in-tree under ``tools/environments/``; this extension point+exists so third-party sandbox vendors do NOT have to live in core.Classification contract-------------------------Beyond creating environments, a terminal backend participates in several-core policy decisions that were historically frozensets of built-in names.-Each is expressed as a declarative attribute so the class of "new backend-missed classification site N" bugs (see PR #30112's seven-site sweep) cannot-recur for plugin backends:--* ``is_remote`` — commands run somewhere other than the host machine.- Suppresses host OS/home/cwd hints in the system prompt, the host Python- env probe, and remote-aware skill env handling.-* ``is_container`` — the backend behaves like a container/sandbox with its- own filesystem rooted away from the host: container resource config is- passed through, host-looking cwds are sanitized, and file tools use- container path resolution.-* ``skip_container_guards`` — the sandbox is isolated enough that- dangerous-command approval prompts are skipped (a wiped filesystem is- disposable). Defaults to ``is_container``. Backends that can mount host- paths should override to ``False``.-* ``cache_path_base`` — where auto-synced ``~/.hermes/cache`` files land- inside the backend (e.g. ``"~/.hermes"`` for home-synced backends,- ``"/root/.hermes"`` for root-homed containers), or ``None`` when host- paths remain correct (nothing is translated).-* ``strip_env_keys`` — credential env var names owned by this backend- (API tokens for the sandbox vendor). Stripped from every subprocess the- agent spawns so a model-authored command can never read them.+A backend participates in core policy decisions that were historically+frozensets of built-in names. Each is a declarative attribute so a new backend+cannot silently miss a classification site:++* ``is_remote`` — commands run off-host: suppresses host OS/home/cwd hints in+ the system prompt, the host Python probe, and remote-aware skill env handling.+* ``is_container`` — own filesystem rooted away from the host: container+ resource config is passed through, host-looking cwds are sanitized, file+ tools use container path resolution.+* ``skip_container_guards`` — sandbox is disposable enough to skip+ dangerous-command approval prompts. Defaults to ``is_container``; backends+ that can mount host paths should override to ``False``.+* ``cache_path_base`` — where auto-synced ``~/.hermes/cache`` files land inside+ the backend (``"~/.hermes"``, ``"/root/.hermes"``), or ``None`` when host+ paths remain correct.+* ``strip_env_keys`` — vendor credential env vars, stripped from every+ subprocess the agent spawns so a model-authored command can never read them.* ``session_isolated_when_nonpersistent`` — non-persistent mode gives each- session its own sandbox identity instead of sharing one (the #82731- contract; opt in when a shared name would let two ephemeral runs attach- and destroy each other's sandbox).--Environment object contract------------------------------:meth:`create_environment` returns an object satisfying the same duck-typed-interface as :class:`tools.environments.base.BaseEnvironment` (``execute()``,-``cleanup()`` …). Subclassing ``BaseEnvironment`` is recommended but not-required — the registry does not isinstance-check the returned environment.-The factory stamps ``_hermes_backend_name`` on the returned object so-file-path resolution can identify plugin backends without class-name-sniffing.+ session its own sandbox identity; opt in when a shared name would let two+ ephemeral runs attach to and destroy each other's sandbox.++:meth:`create_environment` returns any object satisfying the+:class:`tools.environments.base.BaseEnvironment` duck-typed interface+(``execute()``, ``cleanup()`` …); the registry does not isinstance-check it.+The factory stamps ``_hermes_backend_name`` on the result so file-path+resolution can identify plugin backends without class-name sniffing."""from __future__ import annotations@@ -68,38 +45,22 @@ from __future__ import annotationsimport abcfrom typing import Any, Dict, List, Optional, Tuple+from agent.provider_base import ProviderBase-class TerminalEnvironmentProvider(abc.ABC):- """Abstract base class for a pluggable terminal execution backend."""-- # ------------------------------------------------------------------- # Identity- # ------------------------------------------------------------------- @property- @abc.abstractmethod- def name(self) -> str:- """Stable short identifier used as the ``terminal.backend`` /- ``TERMINAL_ENV`` value.+class TerminalEnvironmentProvider(ProviderBase):+ """Abstract base class for a pluggable terminal execution backend.- Lowercase, ``[a-z0-9_]``. Must not collide with a built-in backend- name (local, docker, singularity, modal, managed_modal, daytona,- vercel_sandbox, ssh) — the registry rejects such registrations.- """-- @property- def display_name(self) -> str:- """Human-readable label for pickers. Defaults to ``name``."""- return self.name+ :attr:`name` is the ``terminal.backend`` / ``TERMINAL_ENV`` value+ (``[a-z0-9_]``); the registry rejects built-in backend names.+ """@propertydef description(self) -> str:"""One-line description shown in backend pickers."""return f"Run commands in a {self.display_name} environment."- # ------------------------------------------------------------------- # Classification flags (see module docstring)- # ------------------------------------------------------------------+ # -- Classification flags (see module docstring) -----------------------is_remote: bool = Trueis_container: bool = True@@ -122,63 +83,42 @@ class TerminalEnvironmentProvider(abc.ABC):@propertydef env_description(self) -> str:- """Prompt-builder fallback description of where commands run.-- Used when the live backend probe fails at system-prompt build time,- e.g. ``"a Daytona workspace (Linux)"``.- """+ """Prompt-builder fallback for where commands run when the live backend+ probe fails at system-prompt build time (e.g. ``"a Daytona workspace (Linux)"``)."""return f"a {self.display_name} environment (likely Linux)"- # ------------------------------------------------------------------- # Availability / setup UX- # ------------------------------------------------------------------+ # -- Availability / setup UX -------------------------------------------@abc.abstractmethoddef is_available(self) -> bool:- """Return True when this backend can service commands.-- Cheap check only (env var present, SDK importable). Must NOT make- network calls — this runs during requirement checks and UI paints.- """+ """True when this backend can service commands. Cheap check only — must+ NOT make network calls; runs during requirement checks and UI paints."""def check_requirements(self, config: Dict[str, Any]) -> bool:- """Full requirements check for :func:`check_terminal_requirements`.-- ``config`` is the merged terminal env config dict. Default defers to- :meth:`is_available`. Log actionable errors before returning False.- """+ """Full requirements check for :func:`check_terminal_requirements` with the+ merged terminal env config. Default defers to :meth:`is_available`; log+ actionable errors before returning False."""return self.is_available()def probe(self) -> Tuple[str, str]:- """Dashboard picker health probe: ``(status, detail)``.-- ``status`` is ``"ready"`` / ``"needs_setup"`` / ``"unavailable"``;- ``detail`` carries setup guidance for non-ready rows. Must never- raise and must stay fast (<~2s).- """+ """Dashboard picker health probe ``(status, detail)`` with status in+ ``ready`` / ``needs_setup`` / ``unavailable``. Must never raise; stay fast (<~2s)."""if self.is_available():return ("ready", "")return ("needs_setup", f"{self.display_name} is not configured.")def setup_instructions(self) -> List[str]:- """Lines printed by ``hermes setup`` after this backend is selected.-- Use for token acquisition hints, SDK install commands, etc. The- wizard persists ``terminal.backend`` itself; providers that need an- interactive flow can run it in :meth:`post_setup`.- """+ """Lines printed by ``hermes setup`` after this backend is selected. The+ wizard persists ``terminal.backend`` itself; interactive flows go in+ :meth:`post_setup`."""return []def post_setup(self) -> None:- """Optional interactive setup hook run by ``hermes setup`` after the- backend is selected (prompt for tokens, install SDKs). Default no-op.- """+ """Optional interactive hook run by ``hermes setup`` after selection+ (prompt for tokens, install SDKs). Default no-op."""def doctor_checks(self) -> List[Tuple[bool, str, str]]:- """``hermes doctor`` rows: ``(ok, label, detail)`` triples.-- Default: a single row reflecting :meth:`is_available`.- """+ """``hermes doctor`` rows ``(ok, label, detail)``; default reflects :meth:`is_available`."""ok = Falsetry:ok = bool(self.is_available())@@ -187,9 +127,7 @@ class TerminalEnvironmentProvider(abc.ABC):detail = "(configured)" if ok else "(not configured — see setup instructions)"return [(ok, f"{self.display_name} backend", detail)]- # ------------------------------------------------------------------- # The factory- # ------------------------------------------------------------------+ # -- The factory -------------------------------------------------------@abc.abstractmethoddef create_environment(@@ -202,21 +140,11 @@ class TerminalEnvironmentProvider(abc.ABC):container_config: Optional[Dict[str, Any]] = None,**kwargs: Any,):- """Create and return an execution environment instance.-- MUST accept ``**kwargs`` and ignore unknown keys — the forward-compat- contract that lets the factory signature evolve without breaking- older plugins.-- Args:- cwd: Working directory inside the backend.- timeout: Default per-command timeout in seconds.- task_id: Task identifier for environment reuse/persistence keying.- image: Configured container image name (may be irrelevant).- container_config: Resource config dict (``container_cpu``,- ``container_memory``, ``container_disk``,- ``container_persistent``) when :attr:`is_container` is True.-- Returns:- An object satisfying the ``BaseEnvironment`` duck-typed contract.+ """Create and return an execution environment (``BaseEnvironment`` duck type).++ MUST accept ``**kwargs`` and ignore unknown keys so the factory signature+ can evolve without breaking older plugins. ``task_id`` keys environment+ reuse/persistence; ``container_config`` carries ``container_cpu`` /+ ``container_memory`` / ``container_disk`` / ``container_persistent`` when+ :attr:`is_container` is True."""diff --git a/agent/transcription_provider.py b/agent/transcription_provider.pyindex a0f9597d3ce..80c32f07e5a 100644--- a/agent/transcription_provider.py+++ b/agent/transcription_provider.py@@ -2,41 +2,16 @@Transcription Provider ABC==========================-Defines the pluggable-backend interface for speech-to-text. Providers-register instances via-:meth:`PluginContext.register_transcription_provider`; the active one-(selected via ``stt.provider`` in ``config.yaml``) services every-:func:`tools.transcription_tools.transcribe_audio` call **when the-configured name is neither a built-in (``local``, ``local_command``,-``groq``, ``openai``, ``mistral``, ``xai``) nor disabled**.+Pluggable-backend interface for speech-to-text. Providers register via+:meth:`PluginContext.register_transcription_provider`; the one named by+``stt.provider`` services :func:`tools.transcription_tools.transcribe_audio`+**when that name is not a built-in**. Built-ins (``BUILTIN_STT_PROVIDERS`` in+:mod:`tools.transcription_tools`) always win: the registry rejects colliding+names at registration and the dispatcher re-checks at dispatch time. The+``HERMES_LOCAL_STT_COMMAND`` shell escape hatch stays on the built-in+``local_command`` path.-Two coexisting STT extension surfaces — in resolution order:--1. **Built-in providers** (``BUILTIN_STT_PROVIDERS`` in- :mod:`tools.transcription_tools`) — native Python implementations- for the 6 backends shipped today (faster-whisper, local_command,- Groq, OpenAI, Mistral, xAI). **Always win** — plugins cannot- shadow them. The single-env-var shell escape hatch- ``HERMES_LOCAL_STT_COMMAND`` is preserved via the built-in- ``local_command`` path.-2. **Plugin-registered providers** (this ABC). For new STT backends —- OpenRouter, SenseAudio, Gemini-STT, custom proprietary engines —- that need a Python implementation without modifying- ``tools/transcription_tools.py``.--Built-ins-always-win is enforced at registration time-(:func:`agent.transcription_registry.register_provider` rejects names-in ``BUILTIN_STT_PROVIDERS`` with a warning) AND at dispatch time-(:func:`tools.transcription_tools._dispatch_to_plugin_provider`-re-checks defensively).--Providers live in ``<repo>/plugins/transcription/<name>/`` (built-in-plugins, none shipped today) or-``~/.hermes/plugins/transcription/<name>/`` (user-installed).--Response contract-------------------:meth:`TranscriptionProvider.transcribe` returns a dict with keys::+Response contract for :meth:`TranscriptionProvider.transcribe`::success booltranscript str transcribed text (empty when success=False)@@ -48,106 +23,20 @@ from __future__ import annotationsimport abcimport logging-from typing import Any, Dict, List, Optional+from typing import Any, Dict, Optional-logger = logging.getLogger(__name__)+from agent.provider_base import CatalogProviderBase--# ----------------------------------------------------------------------------# ABC-# ---------------------------------------------------------------------------+logger = logging.getLogger(__name__)-class TranscriptionProvider(abc.ABC):+class TranscriptionProvider(CatalogProviderBase):"""Abstract base class for a speech-to-text backend.- Subclasses must implement :attr:`name` and :meth:`transcribe`.- Everything else has sane defaults — override only what your provider- needs.+ Subclasses must implement :attr:`name` (rejected at registration if it+ collides with a built-in STT name) and :meth:`transcribe`."""- @property- @abc.abstractmethod- def name(self) -> str:- """Stable short identifier used in ``stt.provider`` config.-- Lowercase, no spaces. Examples: ``openrouter``, ``sensaudio``,- ``gemini``, ``deepgram``. Names that collide with a built-in STT- provider (``local``, ``local_command``, ``groq``, ``openai``,- ``mistral``, ``xai``) are rejected at registration time.- """-- @property- def display_name(self) -> str:- """Human-readable label shown in ``hermes tools``.-- Defaults to ``name.title()``.- """- return self.name.title()-- def is_available(self) -> bool:- """Return True when this provider can service calls.-- Typically checks for a required API key + that the SDK is- importable. Default: True (providers with no external- dependencies are always available).-- Must NOT raise — used by the picker and ``hermes setup`` for- availability displays and should fail gracefully.- """- return True-- def list_models(self) -> List[Dict[str, Any]]:- """Return model catalog entries.-- Each entry::-- {- "id": "whisper-large-v3-turbo", # required- "display": "Whisper Large v3 Turbo", # optional- "languages": ["en", "es", "fr"], # optional- "max_audio_seconds": 1500, # optional- }-- Default: empty list (provider has a single fixed model or- doesn't expose model selection).- """- return []-- def default_model(self) -> Optional[str]:- """Return the default model id, or None if not applicable."""- models = self.list_models()- if models:- return models[0].get("id")- return None-- def get_setup_schema(self) -> Dict[str, Any]:- """Return provider metadata for the ``hermes tools`` picker.-- Used by ``tools_config.py`` to inject this provider as a row in- the Speech-to-Text provider list. Shape::-- {- "name": "OpenRouter STT", # picker label- "badge": "paid", # optional short tag- "tag": "Whisper via OpenRouter API", # optional subtitle- "env_vars": [ # keys to prompt for- {"key": "OPENROUTER_API_KEY",- "prompt": "OpenRouter API key",- "url": "https://openrouter.ai/keys"},- ],- }-- Default: minimal entry derived from ``display_name`` with no- env vars. Override to expose API key prompts and custom badges.- """- return {- "name": self.display_name,- "badge": "",- "tag": "",- "env_vars": [],- }-@abc.abstractmethoddef transcribe(self,@@ -157,42 +46,13 @@ class TranscriptionProvider(abc.ABC):language: Optional[str] = None,**extra: Any,) -> Dict[str, Any]:- """Transcribe the audio file at ``file_path``.-- Returns a dict with the standard envelope::-- {- "success": True,- "transcript": "the transcribed text",- "provider": "<this provider's name>",- }-- or on failure::-- {- "success": False,- "transcript": "",- "error": "human-readable error message",- "provider": "<this provider's name>",- }-- Implementations should NOT raise — convert exceptions to the- error envelope so the dispatcher can deliver a consistent shape- to the gateway/CLI caller.-- Args:- file_path: Absolute path to the audio file. The dispatcher- has already validated existence + size before calling.- model: Model identifier from :meth:`list_models`, or None- to use :meth:`default_model`.- language: Optional BCP-47 language hint (e.g. ``"en"``,- ``"ja"``) — providers without language hints should- ignore this argument.- **extra: Forward-compat parameters future schema versions- may expose. Implementations should ignore unknown keys.- The dispatcher currently forwards ``prompt`` here when a- transcription prompt is set (via the ``stt.prompt`` config- key or a ``pre_transcription`` hook) — prompt-capable- providers may use it as a vocabulary/context hint; others- should ignore it.+ """Transcribe the audio file at ``file_path`` into the module-docstring envelope.++ Implementations should NOT raise — convert exceptions to the error+ envelope so the gateway/CLI caller always gets a consistent shape. The+ dispatcher has already validated existence + size. ``model`` None →+ :meth:`default_model`; ``language`` is an optional BCP-47 hint. The+ dispatcher forwards ``prompt`` in ``extra`` when ``stt.prompt`` or a+ ``pre_transcription`` hook sets one — prompt-capable providers may use+ it as a vocabulary hint; unknown keys must be ignored."""diff --git a/agent/tts_provider.py b/agent/tts_provider.pyindex 075cab3f40a..d7e21ad7812 100644--- a/agent/tts_provider.py+++ b/agent/tts_provider.py@@ -2,45 +2,22 @@Text-to-Speech Provider ABC============================-Defines the pluggable-backend interface for text-to-speech synthesis.-Providers register instances via-``PluginContext.register_tts_provider()``; the active one (selected via-``tts.provider`` in ``config.yaml``) services every ``text_to_speech``-tool call **only when the configured name is neither a built-in nor a-command-type provider declared under ``tts.providers.<name>``**.--Three coexisting TTS extension surfaces — in resolution order:--1. **Built-in providers** (``BUILTIN_TTS_PROVIDERS`` in- :mod:`tools.tts_tool`) — native Python implementations (edge, openai,- elevenlabs, …). **Always win** — plugins cannot shadow them.-2. **Command-type providers** declared under ``tts.providers.<name>:- type: command`` (PR #17843, commit ``2facea7f7``). Wire any local- CLI into Hermes with shell-template placeholders. **Wins over a- same-name plugin** — config is more local than plugin install.-3. **Plugin-registered providers** (this ABC). For backends that need a- Python SDK, streaming bytes, OAuth refresh, or voice-listing APIs- the shell-template grammar can't reasonably express.--Built-ins-always-win is enforced at registration time-(:func:`agent.tts_registry.register_provider` rejects names in-``BUILTIN_TTS_PROVIDERS`` with a warning) AND at dispatch time-(:func:`tools.tts_tool._dispatch_to_plugin_provider` re-checks-defensively). The dispatcher also rejects plugin dispatch when a same--name command provider is configured.--Providers live in ``<repo>/plugins/tts/<name>/`` (built-in plugins, no-shipped today) or ``~/.hermes/plugins/tts/<name>/`` (user-installed).-None ship in-tree as of issue #30398 — the hook is additive-infrastructure waiting for a real consumer (Cartesia, Fish Audio, …).--Response contract-------------------:meth:`TTSProvider.synthesize` writes the audio bytes to ``output_path``-and returns the path as a string. Implementations should raise on-failure — the dispatcher converts exceptions into the standard-``{success: False, error: …}`` JSON envelope the rest of Hermes-expects.+Pluggable-backend interface for TTS synthesis. Providers register via+``PluginContext.register_tts_provider()``; the one named by ``tts.provider``+services ``text_to_speech`` **only when that name is neither a built-in nor a+``tts.providers.<name>: type: command`` entry**. Resolution order:++1. Built-in providers (``BUILTIN_TTS_PROVIDERS`` in :mod:`tools.tts_tool`) —+ always win; :func:`agent.tts_registry.register_provider` rejects colliding+ names and the dispatcher re-checks at dispatch time.+2. Command-type providers from ``config.yaml`` — win over a same-name plugin+ because config is more local than a plugin install.+3. Plugin providers (this ABC) — for backends needing a Python SDK, streaming+ bytes, OAuth refresh, or voice-listing APIs the shell template can't express.++:meth:`TTSProvider.synthesize` writes audio to ``output_path`` and returns the+path; it should raise on failure — the dispatcher converts exceptions into the+standard ``{success: False, error: …}`` envelope."""from __future__ import annotations@@ -49,6 +26,8 @@ import abcimport loggingfrom typing import Any, Dict, Iterator, List, Optional+from agent.provider_base import CatalogProviderBase+logger = logging.getLogger(__name__)@@ -56,122 +35,20 @@ DEFAULT_OUTPUT_FORMAT = "mp3"VALID_OUTPUT_FORMATS = frozenset({"mp3", "wav", "ogg", "opus", "flac"})-# ----------------------------------------------------------------------------# ABC-# ------------------------------------------------------------------------------class TTSProvider(abc.ABC):+class TTSProvider(CatalogProviderBase):"""Abstract base class for a text-to-speech backend.- Subclasses must implement :attr:`name` and :meth:`synthesize`.- Everything else has sane defaults — override only what your provider- needs.+ Subclasses must implement :attr:`name` (rejected at registration if it+ collides with a built-in TTS provider name) and :meth:`synthesize`."""- @property- @abc.abstractmethod- def name(self) -> str:- """Stable short identifier used in ``tts.provider`` config.-- Lowercase, no spaces. Examples: ``cartesia``, ``fishaudio``,- ``deepgram``. Names that collide with a built-in TTS provider- (``edge``, ``openai``, ``elevenlabs``, ``minimax``, ``gemini``,- ``mistral``, ``xai``, ``piper``, ``kittentts``, ``neutts``) are- rejected at registration time.- """-- @property- def display_name(self) -> str:- """Human-readable label shown in ``hermes tools``.-- Defaults to ``name.title()`` (e.g. ``Cartesia`` for ``cartesia``).- """- return self.name.title()-- def is_available(self) -> bool:- """Return True when this provider can service calls.-- Typically checks for a required API key + that the SDK is- importable. Default: True (providers with no external- dependencies are always available).-- Must NOT raise — used by the picker and ``hermes setup`` for- availability displays and should fail gracefully.- """- return True-def list_voices(self) -> List[Dict[str, Any]]:- """Return voice catalog entries.-- Each entry::-- {- "id": "voice-abc-123", # required- "display": "Aria — neutral female", # optional; defaults to id- "language": "en-US", # optional- "gender": "female", # optional- "preview_url": "https://...mp3", # optional- }-- Default: empty list (provider has no enumerable voices or- doesn't surface them via API).- """- return []-- def list_models(self) -> List[Dict[str, Any]]:- """Return model catalog entries.-- Each entry::-- {- "id": "sonic-2", # required- "display": "Sonic 2", # optional- "languages": ["en", "es", "fr"], # optional- "max_text_length": 5000, # optional- }-- Default: empty list (provider has a single fixed model or- doesn't expose model selection).- """+ """Voice catalog entries: ``{"id"}`` required; ``display`` / ``language``+ / ``gender`` / ``preview_url`` optional. Default: empty."""return []- def get_setup_schema(self) -> Dict[str, Any]:- """Return provider metadata for the ``hermes tools`` picker.-- Used by ``tools_config.py`` to inject this provider as a row in- the Text-to-Speech provider list. Shape::-- {- "name": "Cartesia", # picker label- "badge": "paid", # optional short tag- "tag": "Ultra-low-latency streaming", # optional subtitle- "env_vars": [ # keys to prompt for- {"key": "CARTESIA_API_KEY",- "prompt": "Cartesia API key",- "url": "https://play.cartesia.ai/console"},- ],- }-- Default: minimal entry derived from ``display_name`` with no- env vars. Override to expose API key prompts and custom badges.- """- return {- "name": self.display_name,- "badge": "",- "tag": "",- "env_vars": [],- }-- def default_model(self) -> Optional[str]:- """Return the default model id, or None if not applicable."""- models = self.list_models()- if models:- return models[0].get("id")- return None-def default_voice(self) -> Optional[str]:- """Return the default voice id, or None if not applicable."""+ """Id of the first voice entry, or None if not applicable."""voices = self.list_voices()if voices:return voices[0].get("id")@@ -189,31 +66,14 @@ class TTSProvider(abc.ABC):format: str = DEFAULT_OUTPUT_FORMAT,**extra: Any,) -> str:- """Synthesize ``text`` and write audio bytes to ``output_path``.-- Returns the absolute path to the written file as a string- (typically just echoes ``output_path``). Raises on failure —- the dispatcher converts exceptions to the standard- ``{success: False, error: ...}`` JSON envelope.-- Args:- text: The text to synthesize. Already truncated to the- provider's max length by the dispatcher.- output_path: Absolute path where the audio file should be- written. Parent directory is guaranteed to exist.- voice: Voice identifier from :meth:`list_voices`, or None- to use :meth:`default_voice`.- model: Model identifier from :meth:`list_models`, or None- to use :meth:`default_model`.- speed: Optional speech-rate multiplier (1.0 = normal).- Providers that don't support speed control should- ignore this argument.- format: Output audio format. Implementations should match- the requested format when possible; if unsupported,- pick the closest equivalent and ensure ``output_path``- ends with the correct extension.- **extra: Forward-compat parameters future schema versions- may expose. Implementations should ignore unknown keys.+ """Synthesize ``text`` into ``output_path`` and return the written path.++ ``text`` is already truncated to the provider's max length and the+ parent directory exists. ``voice`` / ``model`` fall back to+ :meth:`default_voice` / :meth:`default_model` when None; ``speed`` is a+ rate multiplier providers may ignore. If ``format`` is unsupported, pick+ the closest equivalent and make ``output_path`` carry the right+ extension. Unknown ``extra`` keys must be ignored. Raise on failure."""def stream(@@ -225,15 +85,12 @@ class TTSProvider(abc.ABC):format: str = "opus",**extra: Any,) -> Iterator[bytes]:- """Stream synthesized audio bytes.-- Optional. Providers that don't support streaming raise- :class:`NotImplementedError` (the default) and the dispatcher- falls back to :meth:`synthesize` + read-whole-file.+ """Stream synthesized audio bytes (optional).- Args mirror :meth:`synthesize`. Default ``format`` is ``opus``- because the primary streaming use case is voice-bubble- delivery (Telegram et al.) which requires Opus.+ Default raises :class:`NotImplementedError`; the dispatcher then falls+ back to :meth:`synthesize` + read-whole-file. ``format`` defaults to+ ``opus`` because the primary streaming consumer is voice-bubble+ delivery (Telegram et al.), which requires Opus."""raise NotImplementedError(f"TTS provider {self.name!r} does not implement streaming "@@ -244,44 +101,29 @@ class TTSProvider(abc.ABC):def warm(self) -> None:"""Speech output was just turned on; pre-load so the first reply is hot.- Optional. Called from the TTS lease path (Desktop read-aloud / voice- conversation, ``/voice tts``) when this provider is the configured- ``tts.provider`` — e.g. ask a local model server to load its model.- Best-effort: exceptions are logged at debug and ignored. Default: no-op.+ Called from the TTS lease path (Desktop read-aloud / voice conversation)+ when this is the configured provider. Best-effort; default no-op."""def release(self) -> None:- """The last speech-output lease was released; free resident resources.-- Optional counterpart of :meth:`warm` — e.g. tell a local model server- to unload. Best-effort; default: no-op.- """+ """Last speech-output lease released; free resident resources (counterpart+ of :meth:`warm`). Best-effort; default no-op."""@propertydef voice_compatible(self) -> bool:- """Whether output is suitable for voice-bubble delivery.-- Mirrors the ``tts.providers.<name>.voice_compatible`` field- from PR #17843. When True, the gateway's voice-message- delivery pipeline runs ffmpeg conversion to Opus if needed.- When False, output is delivered as a regular audio attachment.+ """Whether output suits voice-bubble delivery (mirrors+ ``tts.providers.<name>.voice_compatible``).- Default: False (safe — providers opt in explicitly).+ True → the gateway converts to Opus via ffmpeg if needed; False →+ delivered as a regular audio attachment. Default False (opt in)."""return False-# ----------------------------------------------------------------------------# Helpers-# -----------------------------------------------------------------------------def resolve_output_format(value: Optional[str]) -> str:- """Clamp an output_format value to the valid set.-- Invalid values are coerced to :data:`DEFAULT_OUTPUT_FORMAT` rather- than rejected so the tool surface is forgiving of agent mistakes.- """+ """Clamp an output_format to :data:`VALID_OUTPUT_FORMATS`; invalid values+ coerce to :data:`DEFAULT_OUTPUT_FORMAT` so the tool surface forgives agent+ mistakes instead of rejecting them."""if not isinstance(value, str):return DEFAULT_OUTPUT_FORMATv = value.strip().lower()diff --git a/agent/video_gen_provider.py b/agent/video_gen_provider.pyindex 92c548f816f..d8cab4192c0 100644--- a/agent/video_gen_provider.py+++ b/agent/video_gen_provider.py@@ -2,35 +2,20 @@Video Generation Provider ABC=============================-Defines the pluggable-backend interface for video generation. Providers register-instances via ``PluginContext.register_video_gen_provider()``; the active one-(selected via ``video_gen.provider`` in ``config.yaml``) services every-``video_generate`` tool call.--Providers live in ``<repo>/plugins/video_gen/<name>/`` (built-in, auto-loaded-as ``kind: backend``) or ``~/.hermes/plugins/video_gen/<name>/`` (user, opt-in-via ``plugins.enabled``).--Mirrors the ``image_gen`` provider design (``agent/image_gen_provider.py``) so-the two surfaces stay learnable together.--Unified surface-----------------One tool — ``video_generate`` — covers **text-to-video** and **image-to-video**.-The router is the presence of ``image_url``: if it's set, the provider routes-to its image-to-video endpoint; if it's omitted, the provider routes to-text-to-video. Users pick one **model family** (e.g. Pixverse v6, Veo 3.1,-Kling O3 Standard); the provider handles which underlying FAL/xAI endpoint-to hit.--Video edit and video extend are intentionally NOT exposed in this surface —-the inconsistency across backends is too large for one unified tool. If-those use cases warrant attention later they can ship as separate tools.--Response shape----------------All providers return a dict built by :func:`success_response` /-:func:`error_response`. Keys:+Pluggable-backend interface for video generation. Providers register via+``PluginContext.register_video_gen_provider()``; the one selected by+``video_gen.provider`` services every ``video_generate`` call. Providers live in+``<repo>/plugins/video_gen/<name>/`` (built-in) or+``~/.hermes/plugins/video_gen/<name>/`` (user, opt-in). Mirrors+``agent/image_gen_provider.py`` so the two surfaces stay learnable together.++One tool covers text-to-video and image-to-video: ``image_url`` present routes+to the provider's image-to-video endpoint, absent routes to text-to-video. Users+pick one model family; the provider picks the FAL/xAI endpoint. Video edit and+extend are deliberately NOT exposed — backends are too inconsistent for one+unified tool.++Response shape (built by :func:`success_response` / :func:`error_response`)::success boolvideo str | None URL or absolute file path@@ -47,19 +32,18 @@ All providers return a dict built by :func:`success_response` /from __future__ import annotationsimport abc-import base64-import datetimeimport logging-import uuidfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuple+from agent import provider_media+from agent.provider_base import CatalogProviderBase+logger = logging.getLogger(__name__)-# Common aspect ratios across providers (Veo / Kling / xAI / Pixverse). The-# tool schema advertises this set as an enum hint, but providers may accept-# a narrower or wider set — they are responsible for clamping.+# Advertised as an enum hint in the tool schema; providers may accept a narrower+# or wider set and are responsible for clamping.COMMON_ASPECT_RATIOS: Tuple[str, ...] = ("16:9", "9:16", "1:1", "4:3", "3:4", "3:2", "2:3")DEFAULT_ASPECT_RATIO = "16:9"@@ -67,98 +51,23 @@ COMMON_RESOLUTIONS: Tuple[str, ...] = ("480p", "540p", "720p", "1080p")DEFAULT_RESOLUTION = "720p"-# ----------------------------------------------------------------------------# ABC-# ------------------------------------------------------------------------------class VideoGenProvider(abc.ABC):+class VideoGenProvider(CatalogProviderBase):"""Abstract base class for a video generation backend.- Subclasses must implement :meth:`generate`. Everything else has sane- defaults — override only what your provider needs.+ Subclasses must implement :attr:`name` and :meth:`generate`; everything else+ has defaults. ``list_models`` entries are **model families** and may add+ ``speed`` / ``strengths`` / ``price`` / advisory ``modalities``."""- @property- @abc.abstractmethod- def name(self) -> str:- """Stable short identifier used in ``video_gen.provider`` config.-- Lowercase, no spaces. Examples: ``xai``, ``fal``, ``google``.- """-- @property- def display_name(self) -> str:- """Human-readable label shown in ``hermes tools``. Defaults to ``name.title()``."""- return self.name.title()-- def is_available(self) -> bool:- """Return True when this provider can service calls.-- Typically checks for a required API key and optional-dependency- import. Default: True.- """- return True-- def list_models(self) -> List[Dict[str, Any]]:- """Return catalog entries for ``hermes tools`` model picker.-- Each entry represents a **model family** that supports text-to-video- and/or image-to-video routing internally::-- {- "id": "veo-3.1", # required- "display": "Veo 3.1", # optional; defaults to id- "speed": "~60s", # optional- "strengths": "...", # optional- "price": "$0.20/s", # optional- "modalities": ["text", "image"], # optional, advisory- }-- Default: empty list (provider has no user-selectable models).- """- return []-- def get_setup_schema(self) -> Dict[str, Any]:- """Return provider metadata for the ``hermes tools`` picker."""- return {- "name": self.display_name,- "badge": "",- "tag": "",- "env_vars": [],- }-- def default_model(self) -> Optional[str]:- """Return the default model id, or None if not applicable."""- models = self.list_models()- if models:- return models[0].get("id")- return None-def capabilities(self) -> Dict[str, Any]:- """Return what this provider supports.-- Returned dict (all keys optional)::-- {- "modalities": ["text", "image"], # which inputs the backend accepts- "aspect_ratios": ["16:9", "9:16", ...],- "resolutions": ["720p", "1080p"],- "max_duration": 15, # seconds- "min_duration": 1,- "supports_audio": True,- "supports_negative_prompt": True,- "supports_seed": True,- "supports_upscale": True,- "max_reference_images": 7,- }-- Used by the tool layer for soft validation, for capability-gated- param rendering in the dynamic ``video_generate`` schema (args a- backend can't honor are not advertised), and by ``hermes tools``- for the picker. Default fails closed: text-only, no optional- features — a provider that doesn't declare a capability doesn't- advertise it.+ """What this provider supports (all keys optional): ``modalities``,+ ``aspect_ratios``, ``resolutions``, ``max_duration`` / ``min_duration``,+ ``supports_audio`` / ``supports_negative_prompt`` / ``supports_seed`` /+ ``supports_upscale``, ``max_reference_images``.++ Used for soft validation, capability-gated params in the dynamic+ ``video_generate`` schema (args a backend can't honor aren't advertised),+ and the picker. Default fails closed: text-only, no optional features."""return {"modalities": ["text"],@@ -189,24 +98,12 @@ class VideoGenProvider(abc.ABC):seed: Optional[int] = None,**kwargs: Any,) -> Dict[str, Any]:- """Generate a video from a prompt (text-to-video) or animate an image- (image-to-video).-- Routing: if ``image_url`` is provided, the provider should route to- its image-to-video endpoint; otherwise text-to-video. The plugin- is responsible for picking the right underlying endpoint within- the user's chosen model family.-- Implementations should return the dict from :func:`success_response`- or :func:`error_response`. ``kwargs`` may contain forward-compat- parameters future versions of the schema will expose —- implementations MUST ignore unknown keys (no TypeError).-- Known optional kwarg: ``upscale`` (bool) — when true, the caller- requests a post-generation high-resolution pass through the- backend's video upscaler. Providers without an upscaler simply- ignore it; providers that honor it should report ``upscaled: True``- in the response ``extra``.+ """Generate a video from a prompt, or animate ``image_url`` when given.++ Return :func:`success_response` / :func:`error_response`. Unknown+ ``kwargs`` MUST be ignored (forward compat). Known optional kwarg:+ ``upscale`` (bool) — a post-generation high-res pass; providers that+ honor it report ``upscaled: True`` in ``extra``."""@@ -215,33 +112,14 @@ class VideoGenProvider(abc.ABC):# ----------------------------------------------------------------------------def _videos_cache_dir() -> Path:- """Return ``$HERMES_HOME/cache/videos/``, creating parents as needed."""- from hermes_constants import get_hermes_home-- path = get_hermes_home() / "cache" / "videos"- path.mkdir(parents=True, exist_ok=True)- return path--def save_b64_video(b64_data: str,*,prefix: str = "video",extension: str = "mp4",) -> Path:- """Decode base64 video data and write under ``$HERMES_HOME/cache/videos/``.-- Returns the absolute :class:`Path` to the saved file.-- Filename format: ``<prefix>_<YYYYMMDD_HHMMSS>_<short-uuid>.<ext>``.- """- raw = base64.b64decode(b64_data)- ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")- short = uuid.uuid4().hex[:8]- path = _videos_cache_dir() / f"{prefix}_{ts}_{short}.{extension}"- path.write_bytes(raw)- return path+ """Decode base64 video data into ``$HERMES_HOME/cache/videos/``; return the path."""+ return provider_media.save_b64("videos", b64_data, prefix=prefix, extension=extension)def save_bytes_video(@@ -251,11 +129,7 @@ def save_bytes_video(extension: str = "mp4",) -> Path:"""Write raw video bytes (e.g. an HTTP download body) to the cache."""- ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")- short = uuid.uuid4().hex[:8]- path = _videos_cache_dir() / f"{prefix}_{ts}_{short}.{extension}"- path.write_bytes(raw)- return path+ return provider_media.save_bytes("videos", raw, prefix=prefix, extension=extension)_URL_VIDEO_CONTENT_TYPES = {@@ -273,61 +147,17 @@ def save_url_video(timeout: float = 180.0,max_bytes: int = 200 * 1024 * 1024,) -> Path:- """Download a video URL and write it under ``$HERMES_HOME/cache/videos/``.-- The video twin of :func:`agent.image_gen_provider.save_url_image`: several- backends (DeepInfra, FAL) return an *ephemeral* delivery URL that expires- before a downstream consumer can fetch it, so we materialise the bytes- locally at tool-completion time. Streams with a size cap.+ """Download an (often ephemeral) video URL into ``$HERMES_HOME/cache/videos/``.- Raises on any network / HTTP / oversize error so callers can fall back to- returning the bare URL.+ Raises on network / HTTP / oversize / empty errors so callers can fall back+ to returning the bare URL. See :mod:`agent.provider_media`."""- import requests-- response = requests.get(url, timeout=timeout, stream=True)- response.raise_for_status()-- content_type = (response.headers.get("Content-Type") or "").split(";", 1)[0].strip().lower()- extension = _URL_VIDEO_CONTENT_TYPES.get(content_type)- if extension is None:- url_path = url.split("?", 1)[0].lower()- for ext in ("mp4", "webm", "mov", "mkv"):- if url_path.endswith(f".{ext}"):- extension = ext- break- if extension is None:- extension = "mp4"-- ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")- short = uuid.uuid4().hex[:8]- path = _videos_cache_dir() / f"{prefix}_{ts}_{short}.{extension}"-- bytes_written = 0- with path.open("wb") as fh:- for chunk in response.iter_content(chunk_size=256 * 1024):- if not chunk:- continue- bytes_written += len(chunk)- if bytes_written > max_bytes:- fh.close()- try:- path.unlink()- except OSError:- pass- raise ValueError(- f"Video at {url} exceeds {max_bytes // (1024 * 1024)}MB cap; refusing to cache."- )- fh.write(chunk)-- if bytes_written == 0:- try:- path.unlink()- except OSError:- pass- raise ValueError(f"Video at {url} was empty (0 bytes).")-- return path+ return provider_media.save_url(+ "videos", url, prefix=prefix, timeout=timeout, max_bytes=max_bytes,+ chunk_size=256 * 1024, content_types=_URL_VIDEO_CONTENT_TYPES,+ url_extensions=("mp4", "webm", "mov", "mkv"), default_extension="mp4",+ label="Video", empty_error="Video at {url} was empty (0 bytes).",+ )def success_response(@@ -341,12 +171,7 @@ def success_response(provider: str,extra: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:- """Build a uniform success response dict.-- ``video`` may be an HTTP URL or an absolute filesystem path.- ``modality`` is ``"text"`` (text-to-video) or ``"image"`` (image-to-video) —- indicates which endpoint was actually hit, useful for diagnostics.- """+ """Uniform success dict; ``extra`` keys are added without overriding standard ones."""payload: Dict[str, Any] = {"success": True,"video": video,@@ -393,10 +218,9 @@ def error_response(class OpenAICompatibleVideoGenProvider(VideoGenProvider):"""Generic text/image-to-video over the OpenAI ``client.videos`` API.- DeepInfra, OpenAI/Sora, and OpenRouter all expose the same- ``POST /videos`` async-job shape (``create`` → poll → ``download_content``),- so the SDK call lives here once. A concrete backend only needs to declare- its identity and credentials::+ DeepInfra, OpenAI/Sora, and OpenRouter share the ``POST /videos`` async-job+ shape (``create`` → poll → ``download_content``), so the SDK call lives here+ once; a concrete backend declares identity and credentials::class FooVideoGenProvider(OpenAICompatibleVideoGenProvider):name = "foo"@@ -413,12 +237,9 @@ class OpenAICompatibleVideoGenProvider(VideoGenProvider):_env_key: str = "OPENAI_API_KEY"_default_base_url: str = "https://api.openai.com/v1"- # Polling cadence for the async video job. The OpenAI SDK's- # ``create_and_poll`` defaults to ~1 poll/second and loops forever on a- # non-terminal status, so a multi-minute job issues hundreds of sequential- # requests and a stuck job pins its tool-executor worker thread with no way- # out. We hand-roll a bounded poll instead: a coarse interval plus a hard- # wall-clock deadline that surfaces a timeout error.+ # The SDK's ``create_and_poll`` polls ~1/s forever on a non-terminal status,+ # pinning the tool-executor thread on a stuck job; we poll coarsely with a+ # hard wall-clock deadline instead._poll_interval_s: float = 5.0_poll_deadline_s: float = 900.0@@ -431,13 +252,8 @@ class OpenAICompatibleVideoGenProvider(VideoGenProvider):return bool(self._api_key())def _create_and_poll(self, client: Any, call_kwargs: Dict[str, Any]) -> Any:- """Create the video job and poll to completion with a hard deadline.-- Replaces ``client.videos.create_and_poll`` (unbounded 1/s loop) with a- coarse interval and a wall-clock cap. Returns the terminal video object- (any status); raises :class:`TimeoutError` if the deadline passes- first.- """+ """Create the job and poll to a terminal status (any); raise+ :class:`TimeoutError` when ``_poll_deadline_s`` passes first."""import timevideo = client.videos.create(**call_kwargs)@@ -502,8 +318,7 @@ class OpenAICompatibleVideoGenProvider(VideoGenProvider):provider=self.name,)- # Provider-specific fields the OpenAI ``videos.create`` signature does- # not name natively — pass them through ``extra_body``.+ # Fields ``videos.create`` doesn't name natively ride in ``extra_body``.extra_body = {k: vfor k, v in {@@ -537,13 +352,10 @@ class OpenAICompatibleVideoGenProvider(VideoGenProvider):aspect_ratio=aspect_ratio,)- # Terminal success status differs across backends: DeepInfra reports- # "succeeded", OpenAI/Sora reports "completed". Accept both.+ # DeepInfra reports "succeeded", OpenAI/Sora "completed" — accept both.status = getattr(video, "status", None)if status not in ("completed", "succeeded"):- # ``video.error`` is a structured SDK object (pydantic- # VideoCreateError), not a string — str() it so the response- # dict stays JSON-serializable for the tool layer.+ # ``video.error`` is a pydantic object — str() keeps the dict JSON-serializable.job_error = getattr(video, "error", None)return error_response(error=str(job_error) if job_error else f"video job ended with status={status!r}",@@ -554,11 +366,9 @@ class OpenAICompatibleVideoGenProvider(VideoGenProvider):aspect_ratio=aspect_ratio,)- # Resolve the output. Providers expose it either as a delivery URL in- # the job's ``data`` list (DeepInfra, FAL-style) or only via the SDK- # download endpoint (OpenAI/Sora). Download the bytes and save locally- # so the caller gets a durable file — DeepInfra's delivery URLs in- # particular are short-lived. Matches plugins/image_gen/deepinfra.+ # Output is a delivery URL in ``data`` (DeepInfra/FAL) or only reachable+ # via the SDK download endpoint (OpenAI/Sora). Save locally either way —+ # DeepInfra's delivery URLs are short-lived.url = Nonefor item in getattr(video, "data", None) or []:candidate = item.get("url") if isinstance(item, dict) else getattr(item, "url", None)@@ -568,15 +378,12 @@ class OpenAICompatibleVideoGenProvider(VideoGenProvider):try:if url:- # Materialise the (often short-lived) delivery URL locally.video_ref = str(save_url_video(url, prefix=self.name))else:- # OpenAI/Sora style: no public URL — pull bytes via the SDK.raw = client.videos.download_content(video.id).read()video_ref = str(save_bytes_video(raw, prefix=self.name))except Exception as exc: # noqa: BLE001if url:- # Best-effort: hand back the URL rather than fail outright.logger.debug("%s: saving video locally failed (%s); returning URL", self.name, exc)video_ref = urlelse:diff --git a/agent/web_search_provider.py b/agent/web_search_provider.pyindex 66cab340b6b..7d2eb310ca0 100644--- a/agent/web_search_provider.py+++ b/agent/web_search_provider.py@@ -2,51 +2,25 @@Web Search Provider ABC=======================-Defines the pluggable-backend interface for web search and content extraction.-Providers register instances via ``PluginContext.register_web_search_provider()``;-the active one (selected via ``web.search_backend`` / ``web.extract_backend`` /-``web.backend`` in ``config.yaml``) services every ``web_search`` /-``web_extract`` tool call.--Providers live in ``<repo>/plugins/web/<name>/`` (built-in, auto-loaded as-``kind: backend``) or ``~/.hermes/plugins/web/<name>/`` (user, opt-in via-``plugins.enabled``).--This ABC is the SINGLE plugin-facing surface for web providers — every-provider in the tree (brave-free, ddgs, searxng, exa, parallel, tavily,-keenable, firecrawl) implements it. The legacy in-tree ``tools.web_providers.base``-ABCs were deleted in PR #25182 along with the per-vendor inline helpers-in ``tools/web_tools.py``; the response-shape contract documented below-is preserved bit-for-bit so the tool wrapper does not have to translate.--Response shape (preserved from the legacy contract):--Search results::-- {- "success": True,- "data": {- "web": [- {"title": str, "url": str, "description": str, "position": int},- ...- ]- }- }--Extract results::-- {- "success": True,- "data": [- {"url": str, "title": str, "content": str,- "raw_content": str, "metadata": dict},- ...- ]- }--On failure (either capability)::-- {"success": False, "error": str}+Pluggable-backend interface for web search and content extraction — the SINGLE+plugin-facing surface every in-tree web provider (brave-free, ddgs, searxng,+exa, parallel, tavily, keenable, firecrawl) implements. Providers register via+``PluginContext.register_web_search_provider()``; the active one (selected by+``web.search_backend`` / ``web.extract_backend`` / ``web.backend``) services+every ``web_search`` / ``web_extract`` call.++Response shape (preserved from the legacy contract so the tool wrapper does not+translate). Search::++ {"success": True, "data": {"web": [+ {"title": str, "url": str, "description": str, "position": int}, ...]}}++Extract::++ {"success": True, "data": [+ {"url": str, "title": str, "content": str, "raw_content": str, "metadata": dict}, ...]}++On failure (either capability): ``{"success": False, "error": str}``."""from __future__ import annotations@@ -55,19 +29,16 @@ import abcimport osfrom typing import Any, Dict, List, Optional+from agent.provider_base import ProviderBase-def get_provider_env(name: str) -> str:- """Config-aware env lookup for web providers.- Resolves *name* via :func:`hermes_cli.config.get_env_value` (checks- ``os.environ`` first, then ``~/.hermes/.env``) so credentials set- through Hermes' config layer are visible even when they were never- exported into the process environment — gateway sessions, delegate- children, and subprocess agent runs (issue #40190). Falls back to a- bare ``os.getenv`` when the config module is unavailable (stripped- installs, early import contexts).+def get_provider_env(name: str) -> str:+ """Config-aware env lookup: ``os.environ`` first, then ``~/.hermes/.env``.- Returns the stripped value, or ``""`` when unset.+ Credentials set through Hermes' config layer must be visible even when never+ exported into the process environment (gateway sessions, delegate children,+ subprocess agent runs). Falls back to bare ``os.getenv`` when the config+ module is unavailable. Returns the stripped value, or ``""`` when unset."""val: Optional[str] = Nonetry:@@ -81,147 +52,58 @@ def get_provider_env(name: str) -> str:return (val or "").strip()-# ----------------------------------------------------------------------------# ABC-# ------------------------------------------------------------------------------class WebSearchProvider(abc.ABC):+class WebSearchProvider(ProviderBase):"""Abstract base class for a web search/extract backend.- Subclasses must implement :meth:`is_available` and at least one of- :meth:`search` / :meth:`extract`. The :meth:`supports_search` /- :meth:`supports_extract` capability flags let the registry route each- tool call to the right provider, and let multi-capability providers- (Firecrawl, Tavily, Exa, …) advertise multiple capabilities from a- single class.+ Subclasses implement :meth:`is_available` and at least one of :meth:`search`+ / :meth:`extract`; the :meth:`supports_search` / :meth:`supports_extract`+ flags let the registry route each capability, so one class can serve both."""- @property- @abc.abstractmethod- def name(self) -> str:- """Stable short identifier used in ``web.search_backend`` /- ``web.extract_backend`` / ``web.backend`` config keys.-- Lowercase, no spaces; hyphens permitted to preserve existing- user-visible names. Examples: ``brave-free``, ``ddgs``,- ``searxng``, ``firecrawl``.- """-- @property- def display_name(self) -> str:- """Human-readable label shown in ``hermes tools``. Defaults to ``name``."""- return self.name-@abc.abstractmethoddef is_available(self) -> bool:- """Return True when this provider can service calls.+ """True when this provider can service calls.- Typically a cheap check (env var present, optional Python dep- importable, instance URL set). Must NOT make network calls — this- runs at tool-registration time and on every ``hermes tools`` paint.+ Cheap check only (env var present, dep importable, instance URL set) —+ must NOT make network calls; runs at tool-registration time and on every+ ``hermes tools`` paint."""def supports_search(self) -> bool:- """Return True if this provider implements :meth:`search`."""+ """True if this provider implements :meth:`search`."""return Truedef is_keyless_available(self) -> bool:- """Return True when this provider can serve calls WITHOUT credentials.-- A separate, weaker tier than :meth:`is_available`: providers with a- public anonymous free tier (Exa / Parallel MCP endpoints) return- True here so the registry can fall back to them when NO provider is- configured or keyed — and only then. Keyless availability must never- make :meth:`is_available` return True, or the legacy preference walk- would route users with real credentials for a lower-priority backend- onto the free tier of a higher-priority one.-- Like :meth:`is_available`, this must be cheap and must NOT make- network calls. Default: False.+ """True when this provider can serve calls WITHOUT credentials.++ A weaker tier than :meth:`is_available`, used only when NO provider is+ configured or keyed (public anonymous free tiers such as Exa / Parallel+ MCP). It must never make :meth:`is_available` True, or the legacy+ preference walk would route users holding real credentials for a+ lower-priority backend onto a higher-priority backend's free tier.+ Cheap, no network. Default False."""return Falsedef supports_extract(self) -> bool:- """Return True if this provider implements :meth:`extract`.-- Both sync and async :meth:`extract` implementations are valid — the- dispatcher detects coroutine functions via- :func:`inspect.iscoroutinefunction` and awaits as needed. Sync- implementations that perform blocking I/O (HTTP, SDK calls) should- ideally wrap in :func:`asyncio.to_thread` at the call site; small- providers can keep their sync shape and let the dispatcher handle- threading.- """+ """True if this provider implements :meth:`extract` (sync or ``async def`` —+ the dispatcher awaits coroutine functions)."""return Falsedef search(self, query: str, limit: int = 5) -> Dict[str, Any]:- """Execute a web search.-- Override when :meth:`supports_search` returns True. The default- raises NotImplementedError; callers should gate on- :meth:`supports_search` before calling.- """+ """Execute a web search. Callers gate on :meth:`supports_search`."""raise NotImplementedError(f"{self.name} does not support search (override supports_search)")def extract(self, urls: List[str], **kwargs: Any) -> Any:- """Extract content from one or more URLs.-- Override when :meth:`supports_extract` returns True. The default- raises NotImplementedError; callers should gate on- :meth:`supports_extract` before calling.-- Return shape: a list of result dicts matching what the legacy- :func:`tools.web_tools.web_extract_tool` post-processing pipeline- expects::-- [- {- "url": str,- "title": str,- "content": str,- "raw_content": str,- "metadata": dict, # optional- "error": str, # optional, only on per-URL failure- },- ...- ]-- Implementations MAY be ``async def`` — the dispatcher detects- coroutines via :func:`inspect.iscoroutinefunction` and awaits.-- ``kwargs`` may carry forward-compat fields (``format``, ``include_raw``,- ``max_chars``) — implementations should ignore unknown keys.+ """Extract content from URLs. Callers gate on :meth:`supports_extract`.++ Returns a list of ``{"url", "title", "content", "raw_content",+ "metadata"?, "error"?}`` dicts (``error`` only on per-URL failure).+ May be ``async def``. ``kwargs`` may carry forward-compat fields+ (``format``, ``include_raw``, ``max_chars``) — ignore unknown keys."""raise NotImplementedError(f"{self.name} does not support extract (override supports_extract)")-- def get_setup_schema(self) -> Dict[str, Any]:- """Return provider metadata for the ``hermes tools`` picker.-- Used by ``hermes_cli/tools_config.py`` to inject this provider as a- row in the Web Search / Web Extract picker. Shape::-- {- "name": "Brave Search (Free)",- "badge": "free",- "tag": "No paid tier needed — uses Brave's free API.",- "env_vars": [- {"key": "BRAVE_SEARCH_API_KEY",- "prompt": "Brave Search API key",- "url": "https://brave.com/search/api/"},- ],- }-- Default: minimal entry derived from ``display_name``. Override to- expose API key prompts, badges, and instance URL fields.- """- return {- "name": self.display_name,- "badge": "",- "tag": "",- "env_vars": [],- }