The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(plugins): shared path-based plugin loader; dedupe cron_providers/context_engine discovery; compact plugin_utils/plugin_storage
Tekniumb54cc716c78c
diff --git a/plugins/context_engine/__init__.py b/plugins/context_engine/__init__.pyindex 906ade4a34c..e70e428d5ef 100644--- a/plugins/context_engine/__init__.py+++ b/plugins/context_engine/__init__.py@@ -1,209 +1,68 @@"""Context engine plugin discovery.-Scans ``plugins/context_engine/<name>/`` directories for context engine-plugins. Each subdirectory must contain ``__init__.py`` with a class-implementing the ContextEngine ABC.--Context engines are separate from the general plugin system — they live-in the repo and are always available without user installation. Only ONE-can be active at a time, selected via ``context.engine`` in config.yaml.-The default engine is ``"compressor"`` (the built-in ContextCompressor).--Usage:- from plugins.context_engine import discover_context_engines, load_context_engine-- available = discover_context_engines() # [(name, desc, available), ...]- engine = load_context_engine("lcm") # ContextEngine instance+Scans ``plugins/context_engine/<name>/`` for ``ContextEngine`` implementations. Engines live+in the repo (always available, no user install) and are separate from the general plugin+system. Only one is active (``context.engine`` in config.yaml; default ``"compressor"``,+the built-in ContextCompressor)."""from __future__ import annotations-import importlib-import importlib.utilimport logging-import sysfrom pathlib import Pathfrom typing import List, Optional, Tuple+from plugins import plugin_loader as _loader+logger = logging.getLogger(__name__)_CONTEXT_ENGINE_PLUGINS_DIR = Path(__file__).parentdef discover_context_engines() -> List[Tuple[str, str, bool]]:- """Scan plugins/context_engine/ for available engines.-- Returns list of (name, description, is_available) tuples.- Does NOT import the engines — just reads plugin.yaml for metadata- and does a lightweight availability check.- """- results = []- if not _CONTEXT_ENGINE_PLUGINS_DIR.is_dir():- return results-- for child in sorted(_CONTEXT_ENGINE_PLUGINS_DIR.iterdir()):- if not child.is_dir() or child.name.startswith(("_", ".")):- continue- init_file = child / "__init__.py"- if not init_file.exists():- continue-- # Read description from plugin.yaml if available- desc = ""- yaml_file = child / "plugin.yaml"- if yaml_file.exists():- try:- import yaml- with open(yaml_file, encoding="utf-8-sig") as f:- meta = yaml.safe_load(f) or {}- desc = meta.get("description", "")- except Exception:- pass-- # Quick availability check — try loading and calling is_available()- available = True- try:- engine = _load_engine_from_dir(child)- if engine is None:- available = False- elif hasattr(engine, "is_available"):- available = engine.is_available()- except Exception:- available = False-- results.append((child.name, desc, available))-- return results-+ """Return ``[(name, description, is_available), ...]`` for every bundled engine."""+ return [+ (+ child.name,+ _loader.read_plugin_description(child),+ _loader.probe_availability(lambda c=child: _load_engine_from_dir(c)),+ )+ for child in _loader.iter_plugin_dirs(_CONTEXT_ENGINE_PLUGINS_DIR)+ ]-def load_context_engine(name: str) -> Optional["ContextEngine"]:- """Load and return a ContextEngine instance by name.- Returns None if the engine is not found or fails to load.- """+def load_context_engine(name: str) -> Optional["ContextEngine"]: # noqa: F821+ """Load a ContextEngine instance by name; None if not found or it fails to load."""engine_dir = _CONTEXT_ENGINE_PLUGINS_DIR / nameif not engine_dir.is_dir():logger.debug("Context engine '%s' not found in %s", name, _CONTEXT_ENGINE_PLUGINS_DIR)return None-- try:- engine = _load_engine_from_dir(engine_dir)- if engine:- return engine- logger.warning("Context engine '%s' loaded but no engine instance found", name)- return None- except Exception as e:- logger.warning("Failed to load context engine '%s': %s", name, e)- return None+ return _loader.load_named(+ name, engine_dir, _load_engine_from_dir,+ kind="Context engine", noun="engine", logger=logger,+ )-def _load_engine_from_dir(engine_dir: Path) -> Optional["ContextEngine"]:- """Import an engine module and extract the ContextEngine instance.+def _load_engine_from_dir(engine_dir: Path) -> Optional["ContextEngine"]: # noqa: F821+ """Import an engine module and extract its ContextEngine (register(ctx) or subclass)."""+ from agent.context_engine import ContextEngine- The module must have either:- - A register(ctx) function (plugin-style) — we simulate a ctx- - A top-level class that extends ContextEngine — we instantiate it- """name = engine_dir.name- module_name = f"plugins.context_engine.{name}"- init_file = engine_dir / "__init__.py"-- if not init_file.exists():+ mod = _loader.load_plugin_module(+ f"plugins.context_engine.{name}", engine_dir,+ parents=("plugins", "plugins.context_engine"), logger=logger,+ )+ if mod is None:return None+ return _loader.instance_from_module(+ mod, collector=_EngineCollector(engine_name=name), collected_attr="engine",+ base_cls=ContextEngine, name=name, logger=logger,+ )- # Check if already loaded- if module_name in sys.modules:- mod = sys.modules[module_name]- else:- # Handle relative imports within the plugin- # First ensure the parent packages are registered- for parent in ("plugins", "plugins.context_engine"):- if parent not in sys.modules:- parent_path = Path(__file__).parent- if parent == "plugins":- parent_path = parent_path.parent- parent_init = parent_path / "__init__.py"- if parent_init.exists():- spec = importlib.util.spec_from_file_location(- parent, str(parent_init),- submodule_search_locations=[str(parent_path)]- )- if spec:- parent_mod = importlib.util.module_from_spec(spec)- sys.modules[parent] = parent_mod- try:- spec.loader.exec_module(parent_mod)- except Exception:- pass- # Now load the engine module- spec = importlib.util.spec_from_file_location(- module_name, str(init_file),- submodule_search_locations=[str(engine_dir)]- )- if not spec:- return None-- mod = importlib.util.module_from_spec(spec)- sys.modules[module_name] = mod-- # Register submodules so relative imports work- for sub_file in engine_dir.glob("*.py"):- if sub_file.name == "__init__.py":- continue- sub_name = sub_file.stem- full_sub_name = f"{module_name}.{sub_name}"- if full_sub_name not in sys.modules:- sub_spec = importlib.util.spec_from_file_location(- full_sub_name, str(sub_file)- )- if sub_spec:- sub_mod = importlib.util.module_from_spec(sub_spec)- sys.modules[full_sub_name] = sub_mod- try:- sub_spec.loader.exec_module(sub_mod)- except Exception as e:- logger.debug("Failed to load submodule %s: %s", full_sub_name, e)-- try:- spec.loader.exec_module(mod)- except Exception as e:- logger.debug("Failed to exec_module %s: %s", module_name, e)- sys.modules.pop(module_name, None)- return None-- # Try register(ctx) pattern first (how plugins are written)- if hasattr(mod, "register"):- collector = _EngineCollector(engine_name=name)- try:- mod.register(collector)- if collector.engine:- return collector.engine- except Exception as e:- logger.debug("register() failed for %s: %s", name, e)-- # Fallback: find a ContextEngine subclass and instantiate it- from agent.context_engine import ContextEngine- for attr_name in dir(mod):- attr = getattr(mod, attr_name, None)- if (isinstance(attr, type) and issubclass(attr, ContextEngine)- and attr is not ContextEngine):- try:- return attr()- except Exception:- pass-- return None---class _EngineCollector:- """Fake plugin context that captures register_context_engine calls.-- Plugin context engines using the standard ``register(ctx)`` pattern may- also call ``ctx.register_command(...)`` to expose slash commands (e.g.- ``/lcm``). Forward those to the global plugin command registry so they- behave identically to commands registered by normal plugins.- """+class _EngineCollector(_loader.NoopPluginContext):+ """Fake plugin context capturing register_context_engine; forwards register_command+ to the global plugin command registry so engine slash commands behave like plugin ones."""def __init__(self, engine_name: str = ""):self.engine = None@@ -213,14 +72,7 @@ class _EngineCollector:def register_context_engine(self, engine):self.engine = engine- def register_command(- self,- name: str,- handler,- description: str = "",- args_hint: str = "",- ) -> None:- """Forward to the global plugin command registry."""+ def register_command(self, name: str, handler, description: str = "", args_hint: str = "") -> None:clean = (name or "").lower().strip().lstrip("/").replace(" ", "-")if not clean:logger.warning(@@ -229,15 +81,11 @@ class _EngineCollector:)return- # Reject conflicts with built-in commands.+ conflict = "Context engine '%s' tried to register command '/%s' which %s Skipping."try:from hermes_cli.commands import resolve_commandif resolve_command(clean) is not None:- logger.warning(- "Context engine '%s' tried to register command '/%s' which conflicts "- "with a built-in command. Skipping.",- self._engine_name, clean,- )+ logger.warning(conflict, self._engine_name, clean, "conflicts with a built-in command.")returnexcept Exception:pass@@ -246,13 +94,7 @@ class _EngineCollector:from hermes_cli.plugins import get_plugin_managermanager = get_plugin_manager()if clean in manager._plugin_commands:- # Don't clobber a regular plugin's command — same conflict- # policy the plugin system uses for plugin-vs-plugin collisions.- logger.warning(- "Context engine '%s' tried to register command '/%s' which "- "is already registered by a plugin. Skipping.",- self._engine_name, clean,- )+ logger.warning(conflict, self._engine_name, clean, "is already registered by a plugin.")returnmanager._plugin_commands[clean] = {"handler": handler,@@ -261,25 +103,8 @@ class _EngineCollector:"args_hint": (args_hint or "").strip(),}self._registered_commands.append(clean)- logger.debug(- "Context engine '%s' registered command: /%s",- self._engine_name, clean,- )+ logger.debug("Context engine '%s' registered command: /%s", self._engine_name, clean)except Exception as exc:logger.debug(- "Context engine '%s' could not register /%s: %s",- self._engine_name, clean, exc,+ "Context engine '%s' could not register /%s: %s", self._engine_name, clean, exc,)-- # No-op for other registration methods- def register_tool(self, *args, **kwargs):- pass-- def register_hook(self, *args, **kwargs):- pass-- def register_cli_command(self, *args, **kwargs):- pass-- def register_memory_provider(self, *args, **kwargs):- passdiff --git a/plugins/cron_providers/__init__.py b/plugins/cron_providers/__init__.pyindex 79dd1a2256e..47dceb11cc4 100644--- a/plugins/cron_providers/__init__.py+++ b/plugins/cron_providers/__init__.py@@ -1,87 +1,30 @@"""Cron scheduler provider plugin discovery.-Scans two directories for cron scheduler provider plugins:--1. Bundled providers: ``plugins/cron_providers/<name>/`` (shipped with hermes-agent)-2. User-installed providers: ``$HERMES_HOME/plugins/<name>/``--Each subdirectory must contain ``__init__.py`` with a class implementing the-``CronScheduler`` ABC (``cron/scheduler_provider.py``). On name collisions,-bundled providers take precedence.--This is a near-verbatim clone of ``plugins/memory/__init__.py`` — the same-discovery/loader machinery, retargeted at ``CronScheduler``. The built-in-``InProcessCronScheduler`` is NOT discovered here: it is core (lives in-``cron/scheduler_provider.py``) so the fallback can never be accidentally-removed. Only NON-default providers (e.g. "chronos") live under this directory.--Only ONE provider can be active at a time, selected via ``cron.provider`` in-config.yaml (empty = built-in). See ``cron.scheduler_provider.resolve_cron_scheduler``.--Usage:- from plugins.cron_providers import discover_cron_schedulers, load_cron_scheduler-- available = discover_cron_schedulers() # [(name, desc, available), ...]- provider = load_cron_scheduler("chronos") # CronScheduler instance+Scans bundled ``plugins/cron_providers/<name>/`` then user ``$HERMES_HOME/plugins/<name>/``+for ``CronScheduler`` implementations (bundled wins on name collision). The built-in+``InProcessCronScheduler`` is core (``cron/scheduler_provider.py``), not discovered here,+so the fallback can never be accidentally removed; only one provider is active+(``cron.provider`` in config.yaml, empty = built-in)."""from __future__ import annotations-import importlib-import importlib.machinery-import importlib.utilimport logging-import sysfrom pathlib import Pathfrom typing import List, Optional, Tuple+from plugins import plugin_loader as _loader+logger = logging.getLogger(__name__)_CRON_PLUGINS_DIR = Path(__file__).parent--# Synthetic parent package for user-installed providers, so they don't-# collide with bundled providers in sys.modules.+# Synthetic parent package for user-installed providers (keeps them out of the bundled namespace)._USER_NAMESPACE = "_hermes_user_cron"-def _register_synthetic_package(name: str, search_locations: List[str]) -> None:- """Register an empty package shell in sys.modules.-- User-installed providers import as ``_hermes_user_cron.<name>``, a dotted- name whose parents exist nowhere on disk. Unless those parents are present- in ``sys.modules``, any relative import inside the plugin- (``from . import config``) fails with- ``ModuleNotFoundError: No module named '_hermes_user_cron'`` — the same- reason the loader already registers ``plugins`` and ``plugins.cron_providers`` for- bundled providers.- """- if name in sys.modules:- return- spec = importlib.machinery.ModuleSpec(name, None, is_package=True)- spec.submodule_search_locations = search_locations- sys.modules[name] = importlib.util.module_from_spec(spec)---# ----------------------------------------------------------------------------# Directory helpers-# -----------------------------------------------------------------------------def _get_user_plugins_dir() -> Optional[Path]:- """Return ``$HERMES_HOME/plugins/`` or None if unavailable."""- try:- from hermes_constants import get_hermes_home- d = get_hermes_home() / "plugins"- return d if d.is_dir() else None- except Exception:- return None-def _is_cron_provider_dir(path: Path) -> bool:- """Heuristic: does *path* look like a cron scheduler provider plugin?-- Checks for ``register_cron_scheduler`` or ``CronScheduler`` in the- ``__init__.py`` source. Cheap text scan — no import needed.- """+ """Cheap text heuristic: ``__init__.py`` mentions the cron scheduler contract."""init_file = path / "__init__.py"if not init_file.exists():return False@@ -92,248 +35,82 @@ def _is_cron_provider_dir(path: Path) -> bool:return False-def _iter_provider_dirs() -> List[Tuple[str, Path]]:- """Yield ``(name, path)`` for all discovered provider directories.+def _user_provider_dirs() -> List[Path]:+ """User-installed ``$HERMES_HOME/plugins/<name>/`` dirs that look like cron providers."""+ user_dir = _loader.user_plugins_dir()+ if not user_dir:+ return []+ return [+ child for child in sorted(user_dir.iterdir())+ if child.is_dir() and not child.name.startswith(("_", ".")) and _is_cron_provider_dir(child)+ ]- Scans bundled first, then user-installed. Bundled takes precedence on- name collisions (first-seen wins via ``seen`` set).- """- seen: set = set()- dirs: List[Tuple[str, Path]] = []-- # 1. Bundled providers (plugins/cron_providers/<name>/)- if _CRON_PLUGINS_DIR.is_dir():- for child in sorted(_CRON_PLUGINS_DIR.iterdir()):- if not child.is_dir() or child.name.startswith(("_", ".")):- continue- if not (child / "__init__.py").exists():- continue- seen.add(child.name)- dirs.append((child.name, child))-- # 2. User-installed providers ($HERMES_HOME/plugins/<name>/)- user_dir = _get_user_plugins_dir()- if user_dir:- for child in sorted(user_dir.iterdir()):- if not child.is_dir() or child.name.startswith(("_", ".")):- continue- if child.name in seen:- continue # bundled takes precedence- if not _is_cron_provider_dir(child):- continue # skip non-cron plugins- dirs.append((child.name, child))+def _iter_provider_dirs() -> List[Tuple[str, Path]]:+ """``(name, path)`` for bundled then user providers; bundled wins on collisions."""+ dirs = [(child.name, child) for child in _loader.iter_plugin_dirs(_CRON_PLUGINS_DIR)]+ seen = {name for name, _ in dirs}+ dirs.extend((child.name, child) for child in _user_provider_dirs() if child.name not in seen)return dirsdef find_provider_dir(name: str) -> Optional[Path]:- """Resolve a provider name to its directory.-- Checks bundled first, then user-installed.- """- # Bundled+ """Resolve a provider name to its directory (bundled first, then user-installed)."""bundled = _CRON_PLUGINS_DIR / nameif bundled.is_dir() and (bundled / "__init__.py").exists():return bundled- # User-installed- user_dir = _get_user_plugins_dir()- if user_dir:- user = user_dir / name- if user.is_dir() and _is_cron_provider_dir(user):- return user+ user_dir = _loader.user_plugins_dir()+ if user_dir and (user_dir / name).is_dir() and _is_cron_provider_dir(user_dir / name):+ return user_dir / namereturn None-# ----------------------------------------------------------------------------# Public API-# ----------------------------------------------------------------------------def discover_cron_schedulers() -> List[Tuple[str, str, bool]]:- """Scan bundled and user-installed directories for available providers.-- Returns list of (name, description, is_available) tuples. May be empty —- the built-in is core, not discovered here, so a fresh checkout with no- bundled non-default provider returns []. Bundled providers take precedence- on name collisions.- """- results = []-- for name, child in _iter_provider_dirs():- # Read description from plugin.yaml if available- desc = ""- yaml_file = child / "plugin.yaml"- if yaml_file.exists():- try:- import yaml- with open(yaml_file, encoding="utf-8-sig") as f:- meta = yaml.safe_load(f) or {}- desc = meta.get("description", "")- except Exception:- pass-- # Quick availability check — try loading and calling is_available()- available = True- try:- provider = _load_provider_from_dir(child)- if provider:- available = provider.is_available()- else:- available = False- except Exception:- available = False-- results.append((name, desc, available))-- return results+ """Return ``[(name, description, is_available), ...]`` for all discovered providers."""+ return [+ (+ name,+ _loader.read_plugin_description(child),+ _loader.probe_availability(lambda c=child: _load_provider_from_dir(c)),+ )+ for name, child in _iter_provider_dirs()+ ]def load_cron_scheduler(name: str) -> Optional["CronScheduler"]: # noqa: F821- """Load and return a CronScheduler instance by name.-- Checks both bundled (``plugins/cron_providers/<name>/``) and user-installed- (``$HERMES_HOME/plugins/<name>/``) directories. Bundled takes precedence- on name collisions.-- Returns None if the provider is not found or fails to load.- """+ """Load a CronScheduler instance by name; None if not found or it fails to load."""provider_dir = find_provider_dir(name)if not provider_dir:logger.debug("Cron provider '%s' not found in bundled or user plugins", name)return None-- try:- provider = _load_provider_from_dir(provider_dir)- if provider:- return provider- logger.warning("Cron provider '%s' loaded but no provider instance found", name)- return None- except Exception as e:- logger.warning("Failed to load cron provider '%s': %s", name, e)- return None+ return _loader.load_named(+ name, provider_dir, _load_provider_from_dir,+ kind="Cron provider", noun="provider", logger=logger,+ )def _load_provider_from_dir(provider_dir: Path) -> Optional["CronScheduler"]: # noqa: F821- """Import a provider module and extract the CronScheduler instance.+ """Import a provider module and extract its CronScheduler (register(ctx) or subclass)."""+ from cron.scheduler_provider import CronScheduler- The module must have either:- - A register(ctx) function (plugin-style) — we simulate a ctx- - A top-level class that extends CronScheduler — we instantiate it- """name = provider_dir.name- # Use a separate namespace for user-installed plugins so they don't- # collide with bundled providers in sys.modules.- _is_bundled = _CRON_PLUGINS_DIR in provider_dir.parents or provider_dir.parent == _CRON_PLUGINS_DIR- module_name = f"plugins.cron_providers.{name}" if _is_bundled else f"{_USER_NAMESPACE}.{name}"- init_file = provider_dir / "__init__.py"-- if not init_file.exists():+ is_bundled = _CRON_PLUGINS_DIR in provider_dir.parents or provider_dir.parent == _CRON_PLUGINS_DIR+ module_name = f"plugins.cron_providers.{name}" if is_bundled else f"{_USER_NAMESPACE}.{name}"+ mod = _loader.load_plugin_module(+ module_name, provider_dir,+ parents=("plugins", "plugins.cron_providers"),+ logger=logger,+ synthetic_namespace=None if is_bundled else _USER_NAMESPACE,+ )+ if mod is None:return None+ return _loader.instance_from_module(+ mod, collector=_ProviderCollector(), collected_attr="provider",+ base_cls=CronScheduler, name=name, logger=logger,+ )- # Check if already loaded. A synthetic package shell has no __file__;- # only reuse modules that were actually loaded from disk.- cached = sys.modules.get(module_name)- if cached is not None and getattr(cached, "__file__", None):- mod = cached- else:- # Ensure the parent packages are registered (for relative imports)- for parent in ("plugins", "plugins.cron_providers"):- if parent not in sys.modules:- parent_path = Path(__file__).parent- if parent == "plugins":- parent_path = parent_path.parent- parent_init = parent_path / "__init__.py"- if parent_init.exists():- spec = importlib.util.spec_from_file_location(- parent, str(parent_init),- submodule_search_locations=[str(parent_path)]- )- if spec:- parent_mod = importlib.util.module_from_spec(spec)- sys.modules[parent] = parent_mod- try:- spec.loader.exec_module(parent_mod)- except Exception:- pass-- # User-installed plugins need their synthetic parent registered the- # same way, or relative imports inside the plugin cannot resolve.- if not _is_bundled:- _register_synthetic_package(_USER_NAMESPACE, [])-- # Now load the provider module- spec = importlib.util.spec_from_file_location(- module_name, str(init_file),- submodule_search_locations=[str(provider_dir)]- )- if not spec:- return None-- mod = importlib.util.module_from_spec(spec)- sys.modules[module_name] = mod- loaded_submodules = []- # Register submodules so relative imports work- # e.g., "from ._nas_client import NasCronClient" in the chronos plugin- for sub_file in provider_dir.glob("*.py"):- if sub_file.name == "__init__.py":- continue- sub_name = sub_file.stem- full_sub_name = f"{module_name}.{sub_name}"- if full_sub_name not in sys.modules:- sub_spec = importlib.util.spec_from_file_location(- full_sub_name, str(sub_file)- )- if sub_spec:- sub_mod = importlib.util.module_from_spec(sub_spec)- sys.modules[full_sub_name] = sub_mod- try:- sub_spec.loader.exec_module(sub_mod)- loaded_submodules.append((sub_name, sub_mod))- except Exception as e:- logger.debug("Failed to load submodule %s: %s", full_sub_name, e)-- try:- spec.loader.exec_module(mod)- except Exception as e:- logger.debug("Failed to exec_module %s: %s", module_name, e)- sys.modules.pop(module_name, None)- return None-- # Manual importlib loading bypasses the normal import machinery that- # binds child modules onto their parent packages. Restore that shape so- # later dotted imports and pytest monkeypatch paths resolve normally.- parent_name, child_name = module_name.rsplit(".", 1)- parent_mod = sys.modules.get(parent_name)- if parent_mod is not None:- setattr(parent_mod, child_name, mod)- for sub_name, sub_mod in loaded_submodules:- setattr(mod, sub_name, sub_mod)-- # Try register(ctx) pattern first (how our plugins are written)- if hasattr(mod, "register"):- collector = _ProviderCollector()- try:- mod.register(collector)- if collector.provider:- return collector.provider- except Exception as e:- logger.debug("register() failed for %s: %s", name, e)-- # Fallback: find a CronScheduler subclass and instantiate it- from cron.scheduler_provider import CronScheduler- for attr_name in dir(mod):- attr = getattr(mod, attr_name, None)- if (isinstance(attr, type) and issubclass(attr, CronScheduler)- and attr is not CronScheduler):- try:- return attr()- except Exception:- pass-- return None---class _ProviderCollector:+class _ProviderCollector(_loader.NoopPluginContext):"""Fake plugin context that captures register_cron_scheduler calls."""def __init__(self):@@ -341,16 +118,3 @@ class _ProviderCollector:def register_cron_scheduler(self, provider):self.provider = provider-- # No-op for other registration methods- def register_tool(self, *args, **kwargs):- pass-- def register_hook(self, *args, **kwargs):- pass-- def register_memory_provider(self, *args, **kwargs):- pass-- def register_cli_command(self, *args, **kwargs):- passdiff --git a/plugins/cron_providers/chronos/__init__.py b/plugins/cron_providers/chronos/__init__.pyindex a4c80977a4b..3ae5d820f61 100644--- a/plugins/cron_providers/chronos/__init__.py+++ b/plugins/cron_providers/chronos/__init__.py@@ -1,34 +1,19 @@"""Chronos — NAS-mediated managed cron provider (scale-to-zero).-Chronos (the Greek god of time, alongside Hermes) is the first non-default-``CronScheduler``. It lets a hosted gateway scale to zero while idle and still-fire cron jobs: instead of a 60s in-process ticker, it asks NAS to arm exactly-one external one-shot per job at that job's real next-fire time. NAS calls the-agent back at fire time over an authenticated webhook (``/api/cron/fire``); the-agent runs the job via the shared ``run_one_job`` body and re-arms the next-one-shot.--The external scheduler NAS uses is an internal NAS implementation detail —-Chronos names no vendor, holds no scheduler credentials, and speaks only to+Instead of a 60s in-process ticker, asks NAS to arm one external one-shot per job at its+next-fire time; NAS calls back ``/api/cron/fire`` and the job re-arms after running.+Between fires the machine is truly idle: start() never blocks or spawns a periodic wake,+and reconcile only runs on a warm process (start / on_jobs_changed / piggybacked on a fire).+Chronos names no scheduler vendor and holds no scheduler credentials — it speaks only toNAS's ``agent-cron`` endpoints with the agent's existing Nous token.--Design constraints (see the plan's DQ-1):- - start() arms all enabled jobs and RETURNS; it never blocks and never spawns- a periodic wake. Between fires the machine is truly at zero.- - reconcile runs only on a warm process (start / on_jobs_changed / piggybacked- on a fire), never as a periodic wake of a sleeping machine.--Inert unless ``cron.provider: chronos``. ``resolve_cron_scheduler`` falls back-to the built-in if Chronos is unavailable, so cron never loses its trigger.--Wire contract: ``docs/chronos-managed-cron-contract.md``.+Inert unless ``cron.provider: chronos``. Wire contract: ``docs/chronos-managed-cron-contract.md``."""from __future__ import annotationsimport loggingimport threading-from typing import Any, Dict, Optional+from typing import Any, Dictfrom cron.scheduler_provider import CronScheduler@@ -48,117 +33,85 @@ class ChronosCronScheduler(CronScheduler):"""NAS-mediated external cron provider."""def __init__(self) -> None:- # In-memory map of job_id → fire_at we've asked NAS to arm. Best-effort- # cache; reconcile rebuilds desired state from jobs.json, so a cold- # process simply re-arms (idempotent via dedup_key).+ # Best-effort cache of job_id -> fire_at armed via NAS; reconcile rebuilds+ # desired state from jobs.json, so a cold process simply re-arms (idempotent).self._armed: Dict[str, str] = {}self._lock = threading.Lock()self._client = None # lazily constructed (no network in is_available)- # -- identity / availability ------------------------------------------@propertydef name(self) -> str:return "chronos"def is_available(self) -> bool:- """Config presence only — NO network.-- Chronos needs a portal base URL, the agent's own publicly-reachable- callback URL (for NAS→agent fires), and a usable Nous token (the agent- is logged into the portal). If any is missing, resolve_cron_scheduler- falls back to the built-in ticker.- """+ """Config presence only — NO network. Needs portal URL, a publicly reachable+ callback URL (for NAS->agent fires) and a Nous login; otherwise the resolver+ falls back to the built-in ticker."""if not (_cfg("cron", "chronos", "portal_url") and _cfg("cron", "chronos", "callback_url")):return False- return self._have_nous_token()-- def _have_nous_token(self) -> bool:- """True if the agent has a Nous Portal login (no network call).-- Checks the stored auth state for a Nous access token — does NOT refresh- or hit the network (is_available must stay offline). The actual- refresh-aware token is resolved lazily at provision time.- """+ # Stored-token presence only (no refresh); the refresh-aware token is resolved at provision time.try:from hermes_cli.auth import get_provider_auth_state- state = get_provider_auth_state("nous") or {}- return bool(state.get("access_token"))+ return bool((get_provider_auth_state("nous") or {}).get("access_token"))except Exception:return False- # -- client ------------------------------------------------------------def _get_client(self):if self._client is None:from ._nas_client import NasCronClientself._client = NasCronClient(_cfg("cron", "chronos", "portal_url"))return self._client- def _callback_url(self) -> str:- return str(_cfg("cron", "chronos", "callback_url") or "")-# -- lifecycle --------------------------------------------------------def start(self, stop_event, *, adapters=None, loop=None, interval=60):- """Arm all enabled jobs via NAS, then RETURN immediately.-- Does NOT block and does NOT spawn a 60s wake (DQ-1) — that is the whole- point of scale-to-zero. The machine wakes only on a NAS→agent fire.- """- # A new provider lifecycle cannot prove what an interrupted prior- # process did. Classify those attempts unknown for audit only; do not- # requeue them here.+ """Arm all enabled jobs via NAS, then RETURN — no loop, no periodic wake (scale-to-zero)."""+ # A new lifecycle cannot prove what an interrupted prior process did:+ # classify those attempts unknown for audit only, never requeue here.self.recover_interrupted()try:self.reconcile()except Exception as e:logger.warning("Chronos start() reconcile failed: %s", e)- # Intentionally return — no loop, no periodic wake.def stop(self) -> None:return Nonedef on_jobs_changed(self) -> None:- """A job was created/updated/removed/paused/resumed — reconcile the NAS- registry so the affected one-shot is (re-)armed or cancelled."""try:self.reconcile()except Exception as e:logger.debug("Chronos on_jobs_changed reconcile failed: %s", e)def register_job(self, job: Dict[str, Any]) -> None:- """Arm the first one-shot for a newly persisted job.-- Unlike full reconciliation, this operation is allowed to raise so the- creation surface can report that the local job exists but its external- trigger was not registered.- """+ """Arm the first one-shot for a new job; may raise so creation can report it."""self._arm_one_shot(job)# -- arming -----------------------------------------------------------def _arm_one_shot(self, job: Dict[str, Any]) -> None:- """Ask NAS to arm exactly one one-shot at the job's next_run_at.-- The agent computes the time; NAS+its scheduler are the dumb executor.- Idempotent per (job_id, fire_at) via dedup_key, so re-arming the same- fire is a no-op NAS-side.- """+ """Arm exactly one one-shot at next_run_at. The agent computes the time; NAS is the+ dumb executor. dedup_key=(job_id, fire_at) makes re-arming the same fire a no-op."""job_id = job["id"]fire_at = job.get("next_run_at")if not fire_at:return- dedup_key = f"{job_id}:{fire_at}"self._get_client().provision(job_id=job_id,fire_at=fire_at,- agent_callback_url=self._callback_url(),- dedup_key=dedup_key,+ agent_callback_url=str(_cfg("cron", "chronos", "callback_url") or ""),+ dedup_key=f"{job_id}:{fire_at}",)with self._lock:self._armed[job_id] = fire_at+ def _arm_logged(self, job: Dict[str, Any], what: str) -> None:+ """Best-effort arm: log a warning instead of raising (reconcile/fire must not die)."""+ try:+ self._arm_one_shot(job)+ except Exception as e:+ logger.warning("Chronos failed to %s: %s", what, e)+def _cancel(self, job_id: str) -> None:try:self._get_client().cancel(job_id=job_id)@@ -167,12 +120,8 @@ class ChronosCronScheduler(CronScheduler):self._armed.pop(job_id, None)def _list_armed(self) -> Dict[str, str]:- """Observed armed one-shots: job_id → fire_at.-- Prefer the in-memory map (warm process); on a cold/empty map, ask NAS- (best-effort). If NAS list fails, return what we have — reconcile then- re-arms desired jobs idempotently.- """+ """Observed armed one-shots (job_id -> fire_at): in-memory map when warm, else ask+ NAS. If the NAS list fails return {} — reconcile then re-arms idempotently."""with self._lock:if self._armed:return dict(self._armed)@@ -189,12 +138,9 @@ class ChronosCronScheduler(CronScheduler):logger.debug("Chronos _list_armed failed (will re-arm idempotently): %s", e)return {}- # -- reconcile ---------------------------------------------------------def reconcile(self) -> None:- """Converge the NAS-armed one-shots toward jobs.json (desired state):- arm missing / re-arm changed-time, cancel orphaned."""- from cron.jobs import load_jobs+ """Converge NAS one-shots toward jobs.json: arm missing/changed, cancel orphans."""+ from cron.jobs import get_job, load_jobsdesired: Dict[str, str] = {j["id"]: j["next_run_at"]@@ -203,19 +149,12 @@ class ChronosCronScheduler(CronScheduler):}observed = self._list_armed()- # Arm missing or changed-time.for job_id, fire_at in desired.items():if observed.get(job_id) != fire_at:- # Re-fetch the full job dict to arm (need the whole record).- from cron.jobs import get_jobjob = get_job(job_id)if job:- try:- self._arm_one_shot(job)- except Exception as e:- logger.warning("Chronos failed to arm job %s: %s", job_id, e)+ self._arm_logged(job, f"arm job {job_id}")- # Cancel orphans (armed but no longer desired).for job_id in list(observed.keys()):if job_id not in desired:try:@@ -223,14 +162,9 @@ class ChronosCronScheduler(CronScheduler):except Exception as e:logger.warning("Chronos failed to cancel orphan %s: %s", job_id, e)- # -- fire --------------------------------------------------------------- # NOTE: no ``fire_due`` override on purpose. The base implementation- # virtually dispatches through ``self.claim_fire``/``self.fire_claimed``,- # and ``provider_supports_split_fire`` treats ANY ``fire_due`` override- # (even a pure ``super()`` delegate) as the legacy single-phase signal —- # overriding it here would silently opt Chronos out of claim admission,- # duplicate detection, and the cancel-aware drain on the fire webhook.+ # No ``fire_due`` override on purpose: ``provider_supports_split_fire`` treats ANY+ # override as the legacy single-phase signal, which would opt Chronos out of claim+ # admission, duplicate detection, and cancel-aware drain on the fire webhook.def fire_claimed(self,@@ -240,28 +174,18 @@ class ChronosCronScheduler(CronScheduler):loop: Any = None,cancel_event: Any = None,) -> bool:- job_id = claimed_job["id"]ran = super().fire_claimed(- claimed_job,- adapters=adapters,- loop=loop,- cancel_event=cancel_event,+ claimed_job, adapters=adapters, loop=loop, cancel_event=cancel_event,)if ran:from cron.jobs import get_job+ job_id = claimed_job["id"]job = get_job(job_id)if job and job.get("enabled") and job.get("next_run_at"):- try:- self._arm_one_shot(job)- except Exception as e:- logger.warning("Chronos failed to re-arm job %s after fire: %s", job_id, e)+ self._arm_logged(job, f"re-arm job {job_id} after fire")return randef register(ctx) -> None:- """Plugin entrypoint — register the Chronos provider with the loader.-- Mirrors the memory-plugin shape; plugins/cron_providers discovery calls this and- collects the provider via register_cron_scheduler.- """+ """Plugin entrypoint — plugins/cron_providers discovery collects the provider here."""ctx.register_cron_scheduler(ChronosCronScheduler())diff --git a/plugins/cron_providers/chronos/_nas_client.py b/plugins/cron_providers/chronos/_nas_client.pyindex 04382adc8ea..2707bbc447c 100644--- a/plugins/cron_providers/chronos/_nas_client.py+++ b/plugins/cron_providers/chronos/_nas_client.py@@ -1,23 +1,17 @@-"""Thin HTTP client for the agent → NAS ``agent-cron`` endpoints (Chronos).+"""Thin HTTP client for the agent -> NAS ``agent-cron`` endpoints (Chronos).-The Chronos provider speaks ONLY to NAS — it names no scheduler vendor and-holds no scheduler credentials. NAS owns the external scheduler (an internal-implementation detail) and that scheduler's account; the agent just asks NAS to-"arm a one-shot at time T" / "cancel" / "list", authenticated with the agent's-existing Nous Portal access token (the same token it already uses to call the-portal — no new secret).--Wire contract: ``docs/chronos-managed-cron-contract.md``.+The agent only asks NAS to "arm a one-shot at time T" / "cancel" / "list", authenticated+with its existing Nous Portal access token (no new secret). NAS owns the external+scheduler and its credentials. Wire contract: ``docs/chronos-managed-cron-contract.md``."""from __future__ import annotationsimport logging-from typing import Any, Dict, List, Optional+from typing import Any, Dict, Listlogger = logging.getLogger("cron.chronos")-# Endpoint paths under the portal base URL._PROVISION_PATH = "/api/agent-cron/provision"_CANCEL_PATH = "/api/agent-cron/cancel"_LIST_PATH = "/api/agent-cron/list"@@ -28,79 +22,48 @@ class NasCronClientError(RuntimeError):class NasCronClient:- """Minimal client for the agent→NAS provision/cancel/list endpoints.-- Uses the agent's refresh-aware Nous access token for auth. No scheduler- vendor, no scheduler creds — NAS hides all of that behind these three calls.- """+ """Minimal client for the agent->NAS provision/cancel/list endpoints."""def __init__(self, portal_url: str, *, timeout_seconds: float = 15.0) -> None:self.portal_url = portal_url.rstrip("/")self.timeout_seconds = timeout_seconds- # -- auth --------------------------------------------------------------- def _access_token(self) -> str:- """The agent's existing Nous Portal access token (refresh-aware)."""- from hermes_cli.auth import resolve_nous_access_token- return resolve_nous_access_token()-def _headers(self) -> Dict[str, str]:+ """Bearer auth with the agent's existing Nous Portal access token (refresh-aware)."""+ from hermes_cli.auth import resolve_nous_access_tokenreturn {- "Authorization": f"Bearer {self._access_token()}",+ "Authorization": f"Bearer {resolve_nous_access_token()}","Content-Type": "application/json",}- # -- HTTP --------------------------------------------------------------- def _post(self, path: str, body: Dict[str, Any]) -> Dict[str, Any]:+ def _request(self, method: str, path: str, **kwargs: Any) -> Dict[str, Any]:+ """Issue one request; raise NasCronClientError on transport error or non-2xx."""import requests # lazy: agent already depends on requests- url = f"{self.portal_url}{path}"- try:- resp = requests.post(- url, json=body, headers=self._headers(), timeout=self.timeout_seconds- )- except Exception as e:- raise NasCronClientError(f"POST {path} failed: {e}") from e- if resp.status_code // 100 != 2:- raise NasCronClientError(- f"POST {path} returned {resp.status_code}: {resp.text[:200]}"- )- try:- return resp.json() if resp.content else {}- except Exception:- return {}-- def _get(self, path: str, params: Dict[str, Any]) -> Dict[str, Any]:- import requests-- url = f"{self.portal_url}{path}"try:- resp = requests.get(- url, params=params, headers=self._headers(), timeout=self.timeout_seconds+ resp = requests.request(+ method, f"{self.portal_url}{path}",+ headers=self._headers(), timeout=self.timeout_seconds, **kwargs,)except Exception as e:- raise NasCronClientError(f"GET {path} failed: {e}") from e+ raise NasCronClientError(f"{method} {path} failed: {e}") from eif resp.status_code // 100 != 2:raise NasCronClientError(- f"GET {path} returned {resp.status_code}: {resp.text[:200]}"+ f"{method} {path} returned {resp.status_code}: {resp.text[:200]}")try:return resp.json() if resp.content else {}except Exception:return {}- # -- endpoints ---------------------------------------------------------def provision(self, *, job_id: str, fire_at: str, agent_callback_url: str,dedup_key: str) -> Dict[str, Any]:- """Ask NAS to arm a one-shot for ``job_id`` at ``fire_at`` (ISO 8601).+ """Arm a one-shot for ``job_id`` at ``fire_at`` (ISO 8601).- ``dedup_key`` (``{job_id}:{fire_at}``) makes re-arming the same fire- idempotent NAS-side. Returns the NAS response (e.g. ``{schedule_id}``).+ ``dedup_key`` (``{job_id}:{fire_at}``) makes re-arming the same fire idempotent+ NAS-side. Returns the NAS response (e.g. ``{schedule_id}``)."""- return self._post(_PROVISION_PATH, {+ return self._request("POST", _PROVISION_PATH, json={"job_id": job_id,"fire_at": fire_at,"agent_callback_url": agent_callback_url,@@ -108,16 +71,11 @@ class NasCronClient:})def cancel(self, *, job_id: str) -> Dict[str, Any]:- """Ask NAS to cancel any armed one-shot for ``job_id``."""- return self._post(_CANCEL_PATH, {"job_id": job_id})+ """Cancel any armed one-shot for ``job_id``."""+ return self._request("POST", _CANCEL_PATH, json={"job_id": job_id})def list_armed(self) -> List[Dict[str, Any]]:- """List the one-shots NAS currently has armed for this agent.-- Returns a list of ``{job_id, fire_at, schedule_id}``. Best-effort: used- by reconcile to find orphaned arms on a cold process; on error the- caller falls back to idempotent re-arm of all desired jobs.- """- data = self._get(_LIST_PATH, {})+ """List armed one-shots (``{job_id, fire_at, schedule_id}``); best-effort, [] on odd shape."""+ data = self._request("GET", _LIST_PATH, params={})items = data.get("armed") if isinstance(data, dict) else Nonereturn items if isinstance(items, list) else []diff --git a/plugins/cron_providers/chronos/verify.py b/plugins/cron_providers/chronos/verify.pyindex 108d788a2ee..db2981d365d 100644--- a/plugins/cron_providers/chronos/verify.py+++ b/plugins/cron_providers/chronos/verify.py@@ -1,19 +1,10 @@-"""Inbound cron-fire token verification for Chronos (Phase 4E.1).+"""Inbound cron-fire token verification for Chronos.-When NAS relays an external scheduler fire to the agent, it POSTs-``/api/cron/fire`` with a short-lived NAS-minted JWT. This module verifies that-JWT before any job runs — the security boundary for remotely-triggered job-execution.--We verify a NAS-minted JWT (the trust path the agent already has) rather than-let an external scheduler call the agent directly: the scheduler signs with-NAS's keys, which the agent doesn't (and shouldn't) hold. See the plan's DQ-4.--The verifier is pluggable (``get_fire_verifier``) so the escape-hatch mode-(direct per-job cron-key) can swap in later with no handler change.--Crypto is delegated to PyJWT (already a declared dependency) — we do NOT-hand-roll JWT verification.+NAS POSTs ``/api/cron/fire`` with a short-lived NAS-minted JWT; this verifies it (via+PyJWT, never hand-rolled) before any job runs. We verify a NAS-minted token rather than+let the external scheduler call the agent directly because the scheduler signs with NAS+keys the agent doesn't hold. ``get_fire_verifier`` is the pluggable seam so an+alternative auth mode (direct per-job cron-key) can swap in without a handler change."""from __future__ import annotations@@ -24,36 +15,19 @@ from typing import Any, Callable, Dict, Optionallogger = logging.getLogger("cron.chronos.verify")-# The purpose claim that scopes a token to the fire endpoint. A general agent-# JWT (without this claim) must NOT be replayable against /api/cron/fire.+# Purpose claim scoping a token to the fire endpoint; a general agent JWT must not replay here._FIRE_PURPOSE = "cron_fire"-# Process-wide cache of PyJWKClient instances, keyed by JWKS URL.-#-# WHY THIS EXISTS: a PyJWKClient caches the fetched JWKS (signing keys) on the-# INSTANCE. Constructing a fresh client per fire therefore threw that cache-# away and forced a synchronous JWKS HTTP GET to the portal on EVERY fire. Under-# a burst of concurrent fires (an instance with several cron jobs firing in the-# same window) that fanned out into N simultaneous JWKS fetches, which the-# portal rate-limited (HTTP 403) — verification then failed and the agent-# answered 401. When a fetch was merely slow rather than rate-limited, it blocked-# the event loop long enough that the fire webhook could not return its 202-# before the relay's 30s timeout (observed in prod as relay 504s concentrated on-# high-job-count instances). Reusing one client per URL keeps the signing keys-# cached (NAS keys rotate rarely), so the steady state is zero JWKS fetches per-# fire. See docs/chronos-managed-cron-contract.md and the betterstack triage.+# Process-wide PyJWKClient cache keyed by JWKS URL. PyJWKClient caches keys on the+# INSTANCE, so a fresh client per fire re-fetched the JWKS every time — under bursts+# the portal rate-limited (403 -> 401) or the fetch blocked the loop past the relay+# timeout (504). One client per URL makes the steady state zero JWKS fetches per fire._JWK_CLIENTS: Dict[str, Any] = {}_JWK_CLIENTS_LOCK = threading.Lock()def _get_jwk_client(jwks_url: str) -> Any:- """Return a process-cached PyJWKClient for ``jwks_url`` (one per URL).-- PyJWKClient does its own key caching internally (``cache_keys``/``lifespan``);- the whole point here is to reuse the SAME instance across fires so that cache- is actually hit instead of discarded. Double-checked-locked so concurrent- fires resolve to a single shared client without racing.- """+ """Return the process-cached PyJWKClient for ``jwks_url`` (double-checked lock)."""client = _JWK_CLIENTS.get(jwks_url)if client is not None:return client@@ -62,15 +36,10 @@ def _get_jwk_client(jwks_url: str) -> Any:if client is None:from jwt import PyJWKClient- # Explicit Accept + User-Agent so the JWKS fetch isn't blocked by the- # NAS portal's WAF, which 403s the default Python-urllib fingerprint- # (same fix as the dashboard-auth nous/self_hosted providers).+ # Explicit Accept + User-Agent: the portal WAF 403s the default urllib fingerprint.client = PyJWKClient(jwks_url,- headers={- "Accept": "application/json",- "User-Agent": "HermesAgent/1.0",- },+ headers={"Accept": "application/json", "User-Agent": "HermesAgent/1.0"},)_JWK_CLIENTS[jwks_url] = clientreturn client@@ -84,54 +53,36 @@ def verify_nas_fire_token(issuer: Optional[str] = None,leeway_seconds: int = 30,) -> Optional[Dict[str, Any]]:- """Verify a NAS-minted cron-fire JWT. Return decoded claims, or None.-- Checks (all must pass):- - signature against the NAS JWKS (``jwks_or_key`` is a JWKS URL) — RS256- family; symmetric secrets are rejected (NAS signs asymmetrically).- - ``aud`` == ``expected_audience`` (this agent: ``agent:{instance_id}``).- - ``exp`` / ``nbf`` within ``leeway_seconds``.- - ``iss`` == ``issuer`` when an issuer is configured.- - ``purpose`` == ``"cron_fire"`` — so a general agent JWT can't be- replayed against the fire endpoint.-- Returns None (never raises) on any failure, so the handler can answer 401- without leaking which check failed.+ """Verify a NAS-minted cron-fire JWT; return decoded claims or None (never raises).++ Checks asymmetric signature (JWKS URL or inline PEM; symmetric secrets rejected since+ NAS signs asymmetrically), ``aud``, ``exp``/``nbf`` with leeway, ``iss`` when configured,+ and ``purpose == "cron_fire"``. Never raises, so the handler answers 401 without+ leaking which check failed."""if not token or not expected_audience:return Noneif not jwks_or_key:- # No verification key configured → cannot verify → refuse. We never- # fall back to unsigned decode for a security boundary.+ # No key -> refuse; never fall back to unsigned decode on a security boundary.logger.warning("cron fire: no JWKS/key configured; refusing token")return Nonetry:import jwt- # Resolve the signing key from the JWKS endpoint by the token's kid.- signing_key = None- if jwks_or_key.startswith("http://") or jwks_or_key.startswith("https://"):- # Reuse a process-cached client so the JWKS fetch is amortised across- # fires (a fresh client per fire re-fetched the JWKS every time and,- # under concurrent fires, tripped the portal's rate limit → 403 →- # 401, or blocked the event loop past the relay's 30s timeout → 504).- jwk_client = _get_jwk_client(jwks_or_key)- signing_key = jwk_client.get_signing_key_from_jwt(token).key+ if jwks_or_key.startswith(("http://", "https://")):+ signing_key = _get_jwk_client(jwks_or_key).get_signing_key_from_jwt(token).keyelse:- # A PEM public key passed inline (test / pinned-key deployments).- signing_key = jwks_or_key+ signing_key = jwks_or_key # inline PEM public key (test / pinned-key deployments)- options = {"require": ["exp", "aud"]}decode_kwargs: Dict[str, Any] = dict(algorithms=["RS256", "RS384", "RS512", "ES256", "ES384"],audience=expected_audience,leeway=leeway_seconds,- options=options,+ options={"require": ["exp", "aud"]},)if issuer:decode_kwargs["issuer"] = issuer-claims = jwt.decode(token, signing_key, **decode_kwargs)except Exception as e:logger.warning("cron fire: token verification failed: %s", e)@@ -140,15 +91,9 @@ def verify_nas_fire_token(if claims.get("purpose") != _FIRE_PURPOSE:logger.warning("cron fire: token missing/!=%s purpose claim", _FIRE_PURPOSE)return None-return claimsdef get_fire_verifier() -> Callable[..., Optional[Dict[str, Any]]]:- """Return the active inbound-fire verifier.-- Default = the NAS-JWT verifier. The DQ-4 escape hatch (direct per-job- cron-key) would return a cron-key verifier here instead, selected by config- — so the webhook handler never changes when the auth mode is swapped.- """+ """Return the active inbound-fire verifier (default: the NAS-JWT verifier)."""return verify_nas_fire_tokendiff --git a/plugins/plugin_loader.py b/plugins/plugin_loader.pynew file mode 100644index 00000000000..bd36eb80943--- /dev/null+++ b/plugins/plugin_loader.py@@ -0,0 +1,220 @@+"""Shared directory-plugin loader for the ``plugins/<kind>/<name>/`` discovery packages.++Used by ``plugins.cron_providers`` and ``plugins.context_engine``: import a plugin+``__init__.py`` by path (with its sibling ``*.py`` pre-registered so relative+imports work), then extract the provider instance via ``register(ctx)`` or an+ABC-subclass fallback.+"""++from __future__ import annotations++import importlib.machinery+import importlib.util+import logging+import sys+from pathlib import Path+from typing import Any, Callable, List, Optional, Tuple++_PLUGINS_ROOT = Path(__file__).parent+++def register_synthetic_package(name: str, search_locations: List[str]) -> None:+ """Register an empty package shell so ``<name>.<child>`` relative imports resolve."""+ if name in sys.modules:+ return+ spec = importlib.machinery.ModuleSpec(name, None, is_package=True)+ spec.submodule_search_locations = search_locations+ sys.modules[name] = importlib.util.module_from_spec(spec)+++def user_plugins_dir() -> Optional[Path]:+ """Return ``$HERMES_HOME/plugins/`` or None if unavailable."""+ try:+ from hermes_constants import get_hermes_home+ d = get_hermes_home() / "plugins"+ return d if d.is_dir() else None+ except Exception:+ return None+++def iter_plugin_dirs(root: Path) -> List[Path]:+ """Sorted child dirs of *root* that have an ``__init__.py`` (skips ``_``/``.`` names)."""+ if not root.is_dir():+ return []+ return [+ child for child in sorted(root.iterdir())+ if child.is_dir()+ and not child.name.startswith(("_", "."))+ and (child / "__init__.py").exists()+ ]+++def read_plugin_description(plugin_dir: Path) -> str:+ """Return ``description`` from ``plugin.yaml`` (empty string if absent/unreadable)."""+ yaml_file = plugin_dir / "plugin.yaml"+ if not yaml_file.exists():+ return ""+ try:+ import yaml+ with open(yaml_file, encoding="utf-8-sig") as f:+ meta = yaml.safe_load(f) or {}+ return meta.get("description", "")+ except Exception:+ return ""+++def _new_module(name: str, file: Path, search_locations: Optional[List[str]] = None) -> Optional[Any]:+ """spec -> module -> sys.modules[name] (NOT executed); None if no spec."""+ spec = importlib.util.spec_from_file_location(+ name, str(file), submodule_search_locations=search_locations+ )+ if not spec:+ return None+ mod = importlib.util.module_from_spec(spec)+ sys.modules[name] = mod+ return mod+++def _exec(mod: Any, logger: Optional[logging.Logger] = None) -> bool:+ """Execute a module made by ``_new_module`` (None -> False); False (and debug-log) if it raised.++ The sys.modules entry is left in place on failure; callers that need a clean+ retry (the main plugin module) pop it themselves.+ """+ if mod is None:+ return False+ try:+ mod.__spec__.loader.exec_module(mod)+ return True+ except Exception as e:+ if logger:+ logger.debug("Failed to exec_module %s: %s", mod.__name__, e)+ return False+++def load_plugin_module(+ module_name: str,+ plugin_dir: Path,+ *,+ parents: Tuple[str, ...],+ logger: logging.Logger,+ synthetic_namespace: Optional[str] = None,+) -> Optional[Any]:+ """Import ``plugin_dir/__init__.py`` as *module_name* (reusing sys.modules when loaded).++ Order matters: parent packages first (relative imports need them), then sibling+ ``*.py`` as ``module_name.<stem>`` (so ``from ._x import Y`` resolves), then the+ module itself. Finally the child is bound onto its parent and the siblings onto the+ module — the shape normal imports produce, which dotted imports and monkeypatch rely on.+ """+ init_file = plugin_dir / "__init__.py"+ if not init_file.exists():+ return None++ # A synthetic package shell has no __file__; only reuse modules loaded from disk.+ cached = sys.modules.get(module_name)+ if cached is not None and getattr(cached, "__file__", None):+ return cached++ for parent in parents:+ parent_path = _PLUGINS_ROOT.joinpath(*parent.split(".")[1:])+ if parent not in sys.modules and (parent_path / "__init__.py").exists():+ _exec(_new_module(parent, parent_path / "__init__.py", [str(parent_path)]))+ if synthetic_namespace:+ register_synthetic_package(synthetic_namespace, [])++ # Reserve the name before siblings exec so their relative imports resolve.+ mod = _new_module(module_name, init_file, [str(plugin_dir)])+ if mod is None:+ return None++ loaded_submodules = []+ for sub_file in plugin_dir.glob("*.py"):+ full_sub_name = f"{module_name}.{sub_file.stem}"+ if sub_file.name == "__init__.py" or full_sub_name in sys.modules:+ continue+ sub_mod = _new_module(full_sub_name, sub_file)+ if _exec(sub_mod, logger):+ loaded_submodules.append((sub_file.stem, sub_mod))++ if not _exec(mod, logger):+ sys.modules.pop(module_name, None)+ return None++ parent_name, child_name = module_name.rsplit(".", 1)+ parent_mod = sys.modules.get(parent_name)+ if parent_mod is not None:+ setattr(parent_mod, child_name, mod)+ for sub_name, sub_mod in loaded_submodules:+ setattr(mod, sub_name, sub_mod)+ return mod+++class NoopPluginContext:+ """Base for the fake ``register(ctx)`` contexts: every registration is a no-op except+ the one the subclass overrides to capture its provider."""++ def _noop(self, *args, **kwargs):+ pass++ register_tool = register_hook = register_cli_command = register_memory_provider = _noop+++def instance_from_module(+ mod: Any,+ *,+ collector: Any,+ collected_attr: str,+ base_cls: type,+ name: str,+ logger: logging.Logger,+) -> Optional[Any]:+ """Extract the provider instance: ``register(ctx)`` first, then any ``base_cls`` subclass."""+ if hasattr(mod, "register"):+ try:+ mod.register(collector)+ instance = getattr(collector, collected_attr)+ if instance:+ return instance+ except Exception as e:+ logger.debug("register() failed for %s: %s", name, e)++ for attr_name in dir(mod):+ attr = getattr(mod, attr_name, None)+ if isinstance(attr, type) and issubclass(attr, base_cls) and attr is not base_cls:+ try:+ return attr()+ except Exception:+ pass+ return None+++def load_named(+ name: str,+ plugin_dir: Path,+ load_from_dir: Callable[[Path], Optional[Any]],+ *,+ kind: str,+ noun: str,+ logger: logging.Logger,+) -> Optional[Any]:+ """Shared body of ``load_<kind>(name)``: load from *plugin_dir*, warn + None on failure."""+ try:+ instance = load_from_dir(plugin_dir)+ except Exception as e:+ logger.warning("Failed to load %s '%s': %s", kind.lower(), name, e)+ return None+ if not instance:+ logger.warning("%s '%s' loaded but no %s instance found", kind, name, noun)+ return instance or None+++def probe_availability(load: Callable[[], Optional[Any]]) -> bool:+ """True iff *load()* returns an instance whose ``is_available()`` (if any) is truthy."""+ try:+ instance = load()+ if instance is None:+ return False+ return instance.is_available() if hasattr(instance, "is_available") else True+ except Exception:+ return Falsediff --git a/plugins/plugin_storage.py b/plugins/plugin_storage.pyindex ee32013052d..baba9809272 100644--- a/plugins/plugin_storage.py+++ b/plugins/plugin_storage.py@@ -1,32 +1,17 @@"""Per-plugin persistent storage convention.-Plugins that want durable state today invent their own paths, and most of-them invent the same wrong one: a scratch directory inside-``<hermes home>/plugins/<name>/``. That tree is the plugin *install* dir —-``hermes plugins remove`` deletes it and ``hermes plugins update`` git-pulls-into it — so user data parked there dies with the code that wrote it.--This module is the sanctioned alternative: one data root per plugin under-``<hermes home>/plugin-data/<name>/``, owned by the user, untouched by-install/update/remove. Agent-built plugins get durable state without-inventing a storage story, and every plugin's data is inspectable in one-predictable place.--Secrets are deliberately NOT part of this convention — credential reads go-through ``agent.secret_scope`` / ``.env`` like everywhere else in Hermes.+Plugins must NOT park state inside ``<hermes home>/plugins/<name>/`` — that is the+install dir, which ``hermes plugins remove`` deletes and ``update`` git-pulls into. The+sanctioned root is ``<hermes home>/plugin-data/<name>/``: user-owned, untouched by+install/update/remove, inspectable in one place. Secrets are deliberately NOT part of+this convention — credential reads go through ``agent.secret_scope`` / ``.env``.Usage::from plugins.plugin_storage import plugin_data_dir, plugin_dbstate_file = plugin_data_dir("my-plugin") / "state.json"-conn = plugin_db("my-plugin") # <data dir>/data.db- try:- conn.execute("CREATE TABLE IF NOT EXISTS ...")- conn.commit()- finally:- conn.close()"""from __future__ import annotations@@ -37,8 +22,8 @@ from pathlib import Path__all__ = ["plugin_data_dir", "plugin_db"]-# Mirrors the plugin-name shape `hermes plugins install` accepts. Anything-# else could escape the data root via separators or traversal.+# Mirrors the plugin-name shape `hermes plugins install` accepts; anything else could+# escape the data root via separators or traversal._NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$")@@ -49,12 +34,10 @@ def _validate_name(name: str) -> str:def plugin_data_dir(name: str) -> Path:- """Return (and create) this plugin's durable data directory.+ """Return (and create) ``<hermes home>/plugin-data/<name>/``.- ``<hermes home>/plugin-data/<name>/`` — survives plugin update and- removal, and follows the active profile because it resolves through- :func:`hermes_constants.get_hermes_home` on every call. Don't cache the- result across profile switches.+ Resolves ``get_hermes_home()`` on every call so it follows the active profile —+ don't cache the result across profile switches."""from hermes_constants import get_hermes_home@@ -64,12 +47,10 @@ def plugin_data_dir(name: str) -> Path:def plugin_db(name: str, filename: str = "data.db") -> sqlite3.Connection:- """Open this plugin's SQLite database (created on first use).+ """Open ``<data dir>/<filename>`` (created on first use).- Lives at ``<data dir>/<filename>``. WAL mode so a dashboard reader and an- agent-tool writer can coexist; ``check_same_thread=False`` matches the- multi-threaded FastAPI/tool environment plugins actually run in — the- caller still owns transaction discipline.+ WAL so a dashboard reader and an agent-tool writer coexist; ``check_same_thread=False``+ matches the multi-threaded FastAPI/tool environment — the caller owns transaction discipline."""if Path(filename).name != filename or not filename:raise ValueError(f"invalid plugin db filename: {filename!r}")diff --git a/plugins/plugin_utils.py b/plugins/plugin_utils.pyindex 8fce19f8b3b..36ea489527c 100644--- a/plugins/plugin_utils.py+++ b/plugins/plugin_utils.py@@ -1,32 +1,15 @@"""Shared concurrency helpers for plugin authors.-The most common plugin footgun is the lazy process-wide singleton:-- _client = None-- def get_client():- global _client- if _client is not None:- return _client- _client = ExpensiveClient(...) # <-- TOCTOU: two threads both run this- return _client--When two threads call ``get_client()`` before the singleton is set, both pass-the ``is not None`` guard, both run the expensive initialization, and the-second write clobbers the first — leaking whatever resource the first client-opened (connections, file handles, background threads).--Multi-threaded agent sessions share one process (delegated tool calls,-background workers, the self-improvement fork), so this race is reachable in-practice. Rather than make every plugin author remember to hand-roll-double-checked locking, this module gives them two thread-safe primitives:+The common plugin footgun is the lazy process-wide singleton (``if _client is None:+_client = Expensive()``): two threads both pass the guard, both build, and the second+write leaks the first's connections/threads. Multi-threaded agent sessions (delegated+tool calls, background workers) make this reachable, so use these instead of hand-rolling+double-checked locking:* :func:`lazy_singleton` — decorator for the zero-arg accessor case.-* :class:`SingletonSlot` — manual slot for accessors that build different- instances depending on a config/key argument.+* :class:`SingletonSlot` — manual slot when the instance depends on a config/key argument.-Both are import-light (stdlib ``threading`` only) so any plugin can import-them without dragging in heavyweight host modules.+Both are stdlib-only (``threading``) so any plugin can import them cheaply."""from __future__ import annotations@@ -40,68 +23,18 @@ __all__ = ["lazy_singleton", "SingletonSlot"]T = TypeVar("T")-def lazy_singleton(factory: Callable[[], T]) -> Callable[[], T]:- """Wrap a zero-argument factory into a thread-safe lazy singleton accessor.-- The wrapped callable returns the same instance on every call; the factory- runs exactly once even under concurrent first calls, using double-checked- locking. A ``.reset()`` attribute is attached for tests/teardown.-- Example::-- @lazy_singleton- def get_client():- return ExpensiveClient(load_config())-- client = get_client() # built once, safe across threads- get_client.reset() # drop the instance (next call rebuilds)-- Note: if the factory raises, no instance is cached and the next call- retries (the lock is released either way).- """- lock = threading.Lock()- box: list = [] # one-element [instance]; empty == not yet built-- @functools.wraps(factory)- def accessor() -> T:- if box:- return box[0]- with lock:- if box: # re-check inside the lock- return box[0]- instance = factory()- box.append(instance)- return instance-- def reset() -> None:- with lock:- box.clear()-- accessor.reset = reset # type: ignore[attr-defined]- return accessor--class SingletonSlot(Generic[T]):"""Thread-safe lazy slot for accessors that take a build argument.- Use this when the cached instance depends on a config/key passed to the- accessor (so a bare zero-arg :func:`lazy_singleton` doesn't fit). The slot- caches the first successfully-built instance and ignores the argument on- subsequent calls — matching the established "first config wins" singleton- semantics most plugins already rely on.-- Example::+ Caches the first successfully-built instance and ignores the argument afterwards+ ("first config wins", the semantics most plugins rely on). The factory runs at most+ once under concurrent first calls; if it raises, nothing is cached and the next call+ retries. Example::_slot: SingletonSlot[Honcho] = SingletonSlot()def get_honcho_client(config=None):return _slot.get(lambda: Honcho(**resolve(config)))-- def reset_honcho_client():- _slot.reset()-- The factory runs at most once even under concurrent first calls. If the- factory raises, nothing is cached and the next call retries."""__slots__ = ("_lock", "_value", "_set")@@ -112,12 +45,11 @@ class SingletonSlot(Generic[T]):self._set = Falsedef get(self, factory: Callable[[], T]) -> T:- # Fast path: already built, no lock needed (a set bool + ref read is- # atomic under CPython's GIL).+ # Fast path without the lock: a bool + ref read is atomic under the GIL.if self._set:return self._value # type: ignore[return-value]with self._lock:- if self._set: # re-check inside the lock+ if self._set:return self._value # type: ignore[return-value]value = factory()self._value = value@@ -133,3 +65,23 @@ class SingletonSlot(Generic[T]):with self._lock:self._value = Noneself._set = False+++def lazy_singleton(factory: Callable[[], T]) -> Callable[[], T]:+ """Wrap a zero-argument factory into a thread-safe lazy singleton accessor.++ The factory runs exactly once even under concurrent first calls (if it raises, the+ next call retries). A ``.reset()`` attribute drops the instance for tests/teardown::++ @lazy_singleton+ def get_client():+ return ExpensiveClient(load_config())+ """+ slot: SingletonSlot[T] = SingletonSlot()++ @functools.wraps(factory)+ def accessor() -> T:+ return slot.get(factory)++ accessor.reset = slot.reset # type: ignore[attr-defined]+ return accessor