The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(plugins): late-loaded plugins wire their platform handlers live (#87770)
teknium121d0b12958a7
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 4d795cdf2ea..d84289b9e64 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -3859,7 +3859,7 @@ export interface PluginsManageParams {values?: Record<string, unknown> | null}export type PluginsAction = 'list' | 'toggle' | 'install' | 'update' | 'remove' | 'settings'-/** ``list`` → ``plugins`` + counts; ``toggle`` → ``ok``/``unchanged``/``restart_required``/``name`` (the canonical key written)/``plugin``; ``install`` → ``hermes_cli.plugins_cmd.dashboard_install_plugin``'s ok payload; ``update`` → ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the ``delta`` (``{surface: [added...]}``) / ``delta_lines`` a widened pin adds — nothing changed until the client retries with ``accept_capabilities``; ``remove`` → ``ok``/``name`` plus ``cleared_memory_provider`` when the removed plugin was the live ``memory.provider``. */+/** ``list`` → ``plugins`` + counts; ``toggle`` → ``ok``/``unchanged``/``restart_required``/``name`` (the canonical key written)/``plugin``; ``install`` → ``hermes_cli.plugins_cmd.dashboard_install_plugin``'s ok payload; ``toggle``/``install``/``update`` that loaded a plugin also carry ``gateway_reloaded`` (the running gateway picked it up and re-wired its handlers) and ``activation`` — the honest split of what is live now vs deferred, so ``restart_required`` is True only when no gateway answered; ``update`` → ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the ``delta`` (``{surface: [added...]}``) / ``delta_lines`` a widened pin adds — nothing changed until the client retries with ``accept_capabilities``; ``remove`` → ``ok``/``name`` plus ``cleared_memory_provider`` when the removed plugin was the live ``memory.provider``. */export interface PluginsManageResult {plugins?: AgentPluginRow[] | nulluser_count?: number | null@@ -3867,6 +3867,8 @@ export interface PluginsManageResult {ok?: boolean | nullunchanged?: boolean | nullrestart_required?: boolean | null+ gateway_reloaded?: boolean | null+ activation?: PluginActivation | nullcleared_memory_provider?: boolean | nullname?: string | nullplugin?: AgentPluginRow | null@@ -3924,6 +3926,13 @@ export interface PluginSettingField {has_value?: boolean | null}export type PluginSettingFieldType = 'string' | 'number' | 'boolean' | 'enum' | 'secret' | 'json'+/** What a plugin loaded mid-run does NOW vs later (``hermes_cli.plugins_activation``), ``{kind: [names]}`` with only non-empty kinds present. ``activated_now`` kinds: ``gateway_commands`` (slash names), ``gateway_transforms`` / ``hooks`` (hook names), ``callbacks`` (platforms / ``slack:<action_id>``) — live in the running gateway once it reloaded (``gateway_reloaded``). ``deferred`` kinds: ``tools`` (tool names) and ``prompt`` (section ids) apply from the next session; ``mcp_servers`` lists the plugin's mcp.json server names (``<namespace>__<server>``, as ``mcp.servers.*`` know them) — not connected until ``mcp.reload``. The Desktop "Installed. Connect its servers now" card reads exactly ``deferred.mcp_servers``. */+export interface PluginActivation {+ name: string+ key: string+ activated_now?: Record<string, string[]>+ deferred?: Record<string, string[]>+}/** Single question: ``question`` / ``choices`` (/ ``multi_select``); batch: ``questions``. ``answers`` rides only on a reconnect replay (locks the server already accepted). */export interface ClarifyRequestParams {session_id: stringdiff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 0733ce1bcff..5a85078ac54 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -19376,6 +19376,46 @@"title": "PingResult","type": "object"},+ "PluginActivation": {+ "additionalProperties": false,+ "description": "What a plugin loaded mid-run does NOW vs later (``hermes_cli.plugins_activation``), ``{kind: [names]}``\nwith only non-empty kinds present. ``activated_now`` kinds: ``gateway_commands`` (slash names),\n``gateway_transforms`` / ``hooks`` (hook names), ``callbacks`` (platforms / ``slack:<action_id>``) \u2014 live in\nthe running gateway once it reloaded (``gateway_reloaded``). ``deferred`` kinds: ``tools`` (tool names) and\n``prompt`` (section ids) apply from the next session; ``mcp_servers`` lists the plugin's mcp.json server\nnames (``<namespace>__<server>``, as ``mcp.servers.*`` know them) \u2014 not connected until ``mcp.reload``.\nThe Desktop \"Installed. Connect its servers now\" card reads exactly ``deferred.mcp_servers``.",+ "properties": {+ "name": {+ "title": "Name",+ "type": "string"+ },+ "key": {+ "title": "Key",+ "type": "string"+ },+ "activated_now": {+ "additionalProperties": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "title": "Activated Now",+ "type": "object"+ },+ "deferred": {+ "additionalProperties": {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "title": "Deferred",+ "type": "object"+ }+ },+ "required": [+ "name",+ "key"+ ],+ "title": "PluginActivation",+ "type": "object"+ },"PluginServerRow": {"additionalProperties": false,"properties": {@@ -19699,7 +19739,7 @@},"PluginsManageResult": {"additionalProperties": false,- "description": "``list`` \u2192 ``plugins`` + counts; ``toggle`` \u2192 ``ok``/``unchanged``/``restart_required``/``name``\n(the canonical key written)/``plugin``; ``install`` \u2192 ``hermes_cli.plugins_cmd.dashboard_install_plugin``'s\nok payload; ``update`` \u2192 ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the\n``delta`` (``{surface: [added...]}``) / ``delta_lines`` a widened pin adds \u2014 nothing changed until the\nclient retries with ``accept_capabilities``; ``remove`` \u2192 ``ok``/``name`` plus\n``cleared_memory_provider`` when the removed plugin was the live ``memory.provider``.",+ "description": "``list`` \u2192 ``plugins`` + counts; ``toggle`` \u2192 ``ok``/``unchanged``/``restart_required``/``name``\n(the canonical key written)/``plugin``; ``install`` \u2192 ``hermes_cli.plugins_cmd.dashboard_install_plugin``'s\nok payload; ``toggle``/``install``/``update`` that loaded a plugin also carry ``gateway_reloaded`` (the\nrunning gateway picked it up and re-wired its handlers) and ``activation`` \u2014 the honest split of what is\nlive now vs deferred, so ``restart_required`` is True only when no gateway answered; ``update`` \u2192 ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the\n``delta`` (``{surface: [added...]}``) / ``delta_lines`` a widened pin adds \u2014 nothing changed until the\nclient retries with ``accept_capabilities``; ``remove`` \u2192 ``ok``/``name`` plus\n``cleared_memory_provider`` when the removed plugin was the live ``memory.provider``.","properties": {"plugins": {"anyOf": [@@ -19776,6 +19816,29 @@"default": null,"title": "Restart Required"},+ "gateway_reloaded": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Gateway Reloaded"+ },+ "activation": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/PluginActivation"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },"cleared_memory_provider": {"anyOf": [{diff --git a/gateway/control_socket.py b/gateway/control_socket.pyindex 30348e492cc..0230e6f9b33 100644--- a/gateway/control_socket.py+++ b/gateway/control_socket.py@@ -378,3 +378,14 @@ def purge_gateway_profile_identity(home: Path, name: str, *,``{"ok": True, "dropped": N, ...}`` answer, or None when no gateway answers / the gateway predatesthe verb."""return query_gateway_control(home, "purge-profile-identity", params={"name": name}, timeout=timeout)+++def reload_gateway_plugins(home: Path, *, profile_home: Optional[Path] = None,+ timeout: float = 30.0) -> Optional[dict[str, Any]]:+ """Ask the gateway serving ``home`` to force plugin re-discovery for ``profile_home`` (default: ``home``)+ and re-wire its live adapters' plugin handlers now (#87770). Returns ``{"reloaded", "plugins",+ "adapters_rewired", ...}`` or None when no gateway answers / it predates the verb — callers then+ fall back to the restart hint. Tools and prompt sections of the reloaded plugin still apply next+ session; only handlers go live."""+ params = {"home": str(profile_home or home)}+ return query_gateway_control(home, "reload-plugins", params=params, timeout=timeout)diff --git a/gateway/platforms/ADDING_A_PLATFORM.md b/gateway/platforms/ADDING_A_PLATFORM.mdindex 3fb182a3c72..63ab2e31030 100644--- a/gateway/platforms/ADDING_A_PLATFORM.md+++ b/gateway/platforms/ADDING_A_PLATFORM.md@@ -83,6 +83,13 @@ plugin guide with code examples and hook documentation.---+Plugin-registered native handlers (`ctx.register_platform_handler(<platform>, factory)`): call+`self._wire_plugin_handlers(native_client)` once in `connect()` before your own catch-all handlers. The base+class then handles plugins that load mid-run — the runner calls `rewire_plugin_handlers()` on every+plugin-loaded event and only factories not yet wired on that native client run. Override it only when your+adapter keeps a second plugin registry (Slack action handlers) or dispatches by registration order with a+catch-all last (Telegram hoists late handlers ahead of core); see `gateway/run_plugin_rewire.py`.+## Built-in Path (Core Contributors Only)Checklist for integrating a platform directly into the Hermes core.diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 2a24934662f..38ec5bc31fe 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -2198,10 +2198,20 @@ class BasePlatformAdapter(ABC):release_scoped_lock(self._platform_lock_scope, identity)self._platform_lock_identity = None+ # Plugin handler factories wired on the live native client: ``(plugin, qualname)`` keys, reset when+ # the native client is rebuilt. ``None`` = ``connect()`` has not wired yet (class defaults so+ # subclasses that skip ``super().__init__`` still re-wire safely).+ _plugin_handler_native: Any = None+ _plugin_handlers_wired: Optional[set] = None+def _wire_plugin_handlers(self, native: Any = None) -> None:"""Invoke plugin-registered native handler factories (``ctx.register_platform_handler``)with ``(native, adapter)``; adapters call this from ``connect()`` once the native- client exists. Each factory is isolated so a bad plugin can't block connecting."""+ client exists and :meth:`rewire_plugin_handlers` re-runs it for plugins loaded later.+ Idempotent per native client: a factory is keyed by ``(plugin, qualname)`` and skipped once+ wired on this ``native`` (a force re-discovery hands back NEW function objects for the same+ plugin, so identity alone would double-register). Each factory is isolated so a bad plugin+ can't block connecting."""try:from hermes_cli.plugins import get_plugin_managerfactories = get_plugin_manager().get_platform_handler_factories(@@ -2209,13 +2219,32 @@ class BasePlatformAdapter(ABC):except Exception as e: # pragma: no cover - defensivelogger.warning("[%s] Could not load plugin handler factories: %s", self.name, e)return+ if self._plugin_handler_native is not native or self._plugin_handlers_wired is None:+ # A rebuilt native client (transient-init rebuild, reconnect) starts with nothing wired.+ self._plugin_handler_native = native+ self._plugin_handlers_wired = set()for factory, plugin_name in factories:+ key = (plugin_name, getattr(factory, "__qualname__", None) or repr(factory))+ if key in self._plugin_handlers_wired:+ continuetry:factory(native, self)logger.info("[%s] Wired native handlers from plugin '%s'", self.name, plugin_name)except Exception as exc:logger.error("[%s] Plugin '%s' handler factory raised: %s", self.name, plugin_name,exc, exc_info=True)+ # A raising factory is recorded too: re-wire must not re-raise it on every plugin load.+ self._plugin_handlers_wired.add(key)++ def rewire_plugin_handlers(self) -> None:+ """Register handlers of plugins loaded AFTER ``connect()`` wired the first batch (#87770);+ the gateway runner calls this on every plugin-loaded event. Safe to call repeatedly: only+ factories not yet wired on the live native client run. Before ``connect()`` has wired once+ there is nothing to re-wire — connect will pick everything up. Adapters with extra plugin+ registries (Slack action handlers) extend this."""+ if self._plugin_handlers_wired is None:+ return+ self._wire_plugin_handlers(self._plugin_handler_native)@propertydef name(self) -> str:diff --git a/gateway/run.py b/gateway/run.pyindex 62f69cf98d0..2fb0fbca58d 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -2196,6 +2196,7 @@ from gateway.run_inbound import GatewayInboundMixinfrom gateway.run_goals import GatewayGoalsMixinfrom gateway.run_agent_cache import GatewayAgentCacheMixinfrom gateway.run_profile_reconcile import GatewayProfileReconcileMixin+from gateway.run_plugin_rewire import GatewayPluginRewireMixinfrom gateway.platforms.base import (BasePlatformAdapter,_reply_anchor_for_event,@@ -3386,7 +3387,7 @@ class GatewayRunner(GatewayVoiceMixin, GatewayAdapterLifecycleMixin, GatewayTopicThreadsMixin, GatewayTurnMixin,GatewayShutdownMixin, GatewayBusySessionMixin, GatewayConfigLoadersMixin, GatewayStartupMixin,GatewaySessionWatchersMixin, GatewayNotificationsMixin, GatewayInboundMixin, GatewayGoalsMixin,- GatewayAgentCacheMixin, GatewayProfileReconcileMixin):+ GatewayAgentCacheMixin, GatewayProfileReconcileMixin, GatewayPluginRewireMixin):"""Main gateway controller: manages adapter lifecycles, routes messages to/from the agent."""# Class-level defaults so partial construction in tests doesn't blow up on attribute access.@@ -5524,6 +5525,7 @@ async def _start_gateway_start_control_socket(runner):# this feature. See #92091.from gateway.control_socket import GatewayControlServerfrom gateway.run_profile_reconcile import migrate_profile_identity_verb, purge_profile_identity_verb+ from gateway.run_plugin_rewire import reload_plugins_verb# pause-for-update: the updater asks us to drain + exit (freeing venv handles) vs. a tree-kill# (same path as SIGUSR1). Handler runs on the socket executor thread, so marshal onto the loop.# pause-for-update (#92091 step 2): the updater asks this gateway to drain in-flight turns and exit@@ -5573,7 +5575,10 @@ async def _start_gateway_start_control_socket(runner):verb_handlers={"pause-for-update": _pause_for_update_handler,"rescan-profiles": _rescan_profiles_handler,"migrate-profile-identity": migrate_profile_identity_verb(runner),- "purge-profile-identity": purge_profile_identity_verb(runner)})+ "purge-profile-identity": purge_profile_identity_verb(runner),+ # A plugin installed/enabled by another process loads now and re-wires the+ # live adapters' handlers (#87770); tools/prompt still wait for the next session.+ "reload-plugins": reload_plugins_verb(runner, _main_loop)})if not await _control_server.start():_control_server = Noneelse:diff --git a/gateway/run_adapters.py b/gateway/run_adapters.pyindex 203c9d330d1..af4adf7c62f 100644--- a/gateway/run_adapters.py+++ b/gateway/run_adapters.py@@ -960,8 +960,9 @@ class GatewayAdapterLifecycleMixin:await asyncio.to_thread(hydrate_profile_secret_sources, profile_home)with _profile_runtime_scope(profile_home, hydrate_secrets=False):profile_runtime_cfg = _load_gateway_config()- from hermes_cli.plugins import discover_plugins+ from hermes_cli.plugins import discover_plugins, get_plugin_managerdiscover_plugins()+ self._subscribe_plugin_rewire(get_plugin_manager(), profile_name, profile_home)# This profile's `hooks:` block: start() registered before any profile scope existed.self._register_config_hooks("shell-hook/webhook registration failed for profile '%s'", profile_name, level=logging.WARNING,diff --git a/gateway/run_plugin_rewire.py b/gateway/run_plugin_rewire.pynew file mode 100644index 00000000000..03275d5cd9a--- /dev/null+++ b/gateway/run_plugin_rewire.py@@ -0,0 +1,126 @@+"""Late plugin loads re-wire the running adapters (#87770).++A plugin that finishes loading after an adapter connected — a tool-triggered force re-discovery, or+``hermes plugins install/enable`` / the Desktop / ``plugins.manage`` nudging the gateway over the control+socket — used to leave its platform handlers (slash commands, button callbacks, inbound transforms)+silently unwired until a restart. The runner subscribes to ``PluginManager.on_plugin_loaded`` per served+profile and calls every live adapter's idempotent ``rewire_plugin_handlers()`` on the event loop.++Scope is handlers only: a mid-run-loaded plugin's tools and system-prompt sections stay deferred to the+next session (prompt-cache invariant; same as ``/skills install``).+"""++from __future__ import annotations++import asyncio+import contextlib+import logging+from pathlib import Path+from typing import Any, Callable, Dict, Optional++logger = logging.getLogger(__name__)+++class GatewayPluginRewireMixin:+ """Subscribe once per plugin manager; re-wire that profile's adapters on every loaded event."""++ _plugin_rewire_unsubscribe: Optional[Dict[str, Callable[[], None]]] = None++ def _subscribe_plugin_rewire(self, manager: Any, profile_name: Optional[str] = None,+ profile_home: Optional[Path] = None) -> None:+ """Idempotent per manager scope: a served-profile rescan re-enters ``_load_secondary_profile_config``+ and must not stack a second listener (two listeners = two re-wire passes, still deduped, but noise)."""+ subs = self._plugin_rewire_unsubscribe+ if subs is None:+ subs = self._plugin_rewire_unsubscribe = {}+ scope = str(getattr(manager, "scope_key", "") or id(manager))+ if scope in subs:+ return+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ loop = None++ def _on_loaded(_names) -> None:+ # Fires on the discovering thread (tool worker, control-socket executor, or the loop itself):+ # adapters own PTB/Bolt handler tables, so always hop onto the gateway loop.+ if loop is None or loop.is_closed():+ return+ loop.call_soon_threadsafe(self._rewire_plugin_handlers, profile_name, profile_home)++ subs[scope] = manager.on_plugin_loaded(_on_loaded)++ def _rewire_plugin_handlers(self, profile_name: Optional[str] = None,+ profile_home: Optional[Path] = None) -> int:+ """Call ``rewire_plugin_handlers()`` on every live adapter of one profile (``None`` = the launch+ profile's ``self.adapters``); a secondary's adapters read their own manager, so bind its scope.+ Returns the number of adapters re-wired."""+ if profile_name is None:+ adapters = dict(getattr(self, "adapters", None) or {})+ else:+ adapters = dict((getattr(self, "_profile_adapters", None) or {}).get(profile_name) or {})+ if not adapters:+ return 0+ from gateway.run import _profile_runtime_scope+ scope = (_profile_runtime_scope(profile_home, hydrate_secrets=False)+ if profile_home is not None else contextlib.nullcontext())+ count = 0+ with scope:+ for platform, adapter in adapters.items():+ try:+ adapter.rewire_plugin_handlers()+ count += 1+ except Exception:+ logger.warning("[%s] plugin handler re-wire failed", getattr(platform, "value", platform),+ exc_info=True)+ logger.info("Re-wired plugin handlers on %d adapter(s)%s", count,+ f" for profile '{profile_name}'" if profile_name else "")+ return count+++def reload_plugins_verb(runner: Any, loop: asyncio.AbstractEventLoop) -> Callable[..., dict]:+ """Control-socket ``reload-plugins``: force re-discovery under the requested home's scope so a plugin+ installed/enabled by another process (CLI, Desktop, ``plugins.manage``) loads now; the loaded event+ then re-wires that profile's adapters. Only the gateway home and served profile homes are accepted.+ Answer: ``{"reloaded", "home", "plugins", "activations", "adapters_rewired"}``. Runs on the socket executor thread+ (discovery is blocking); the count is read on the loop AFTER the re-wire callback (FIFO), so a+ truthful "active now" reaches the caller."""++ def _handler(params: Optional[dict] = None) -> dict:+ from hermes_constants import get_hermes_home, hermes_home_key+ from hermes_cli.plugins import discover_plugins, get_plugin_manager+ from hermes_cli.plugins_activation import activation_summaries+ from gateway.run import _profile_runtime_scope+ params = params or {}+ gateway_home = Path(get_hermes_home())+ requested = Path(str(params.get("home") or gateway_home)).expanduser()+ req_key = hermes_home_key(requested)+ profile_name: Optional[str] = None+ if req_key != hermes_home_key(gateway_home):+ served = (getattr(runner, "_served_profile_homes", None) or {}).items()+ profile_name = next((str(n) for n, h in served if hermes_home_key(h) == req_key), None)+ if profile_name is None:+ return {"reloaded": False, "error": "home is not served by this gateway", "home": str(requested)}+ if profile_name == (getattr(runner, "_primary_profile_name", None) or "default"):+ profile_name = None+ scope = (_profile_runtime_scope(requested, hydrate_secrets=False) if profile_name+ else contextlib.nullcontext())+ with scope:+ discover_plugins(force=True)+ manager = get_plugin_manager()+ names, activations = sorted(manager._plugins), activation_summaries(manager)+ try:+ rewired = asyncio.run_coroutine_threadsafe(_count_adapters(runner, profile_name), loop).result(timeout=5.0)+ except Exception:+ rewired = None+ return {"reloaded": True, "home": str(requested), "plugins": names, "activations": activations,+ "adapters_rewired": rewired}++ return _handler+++async def _count_adapters(runner: Any, profile_name: Optional[str]) -> int:+ """Live adapters for the profile; scheduled after the loaded-event callback, so they are re-wired."""+ if profile_name is None:+ return len(getattr(runner, "adapters", None) or {})+ return len((getattr(runner, "_profile_adapters", None) or {}).get(profile_name) or {})diff --git a/gateway/run_startup.py b/gateway/run_startup.pyindex c151df0f15b..cb5bbdc00cd 100644--- a/gateway/run_startup.py+++ b/gateway/run_startup.py@@ -1026,6 +1026,10 @@ class GatewayStartupMixin:"""Plugins, relay, hooks, then crash/clean-exit recovery of processes and sessions."""from gateway.run import _hermes_homeself._start_register_plugins_relay_hooks()+ # Plugins that load later (force re-discovery, install/enable nudge) re-wire live adapters (#87770).+ with _log_suppressed(logging.WARNING, "plugin re-wire subscription failed", exc_info=True):+ from hermes_cli.plugins import get_plugin_manager+ self._subscribe_plugin_rewire(get_plugin_manager())self.hooks.discover_and_load()# Recover background processes from checkpoint (crash recovery). ``_checkpoint_path`` is# scope-relative, so a served secondary's turn wrote ITS home's processes.json; recover eachdiff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex db2c6a32cf4..464f6ee9f9d 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -1193,6 +1193,8 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):self._approval_transports: Dict[str, Any] = {}self._slack_action_handlers: List[tuple] = []self._platform_handler_factories: Dict[str, List[tuple]] = {}+ # Process-owned discovery listeners (``on_plugin_loaded``); never cleared by unload().+ self._plugin_loaded_listeners: List[Callable] = []# Event bus: owner-tagged subscriptions (unload removes zombies); one daemon worker keeps# registration order while emitters never block; per-worker chain depth caps mutual emitters.self._subscriptions: Dict[str, List[_EventSubscription]] = {}@@ -1265,6 +1267,9 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):with self._discovery_lock, _plugin_home_scope(self.home_path):if self._discovered and not force:return+ # ``on_plugin_loaded`` reports the plugins this sweep loads that the process did not have before+ # (boot: everything; a mid-run install/enable: just the newcomer), keyed on the pre-sweep set.+ loaded_before = frozenset(k for k, p in self._plugins.items() if not p.error and not p.deferred)if force:self.unload() # the ledger owns teardown of process-global registriesif env_var_enabled("HERMES_SAFE_MODE"):@@ -1296,6 +1301,8 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):except BaseException:self._discovered = Falseraise+ # Outside the lock: a listener (the gateway's re-wire) may read the registry from another thread.+ self._notify_plugin_loaded(loaded_before)def _re_register_config_hooks_after_force(self) -> None:"""Restore config-owned shell hooks/outbound webhooks after a force clear; each guardeddiff --git a/hermes_cli/plugins_activation.py b/hermes_cli/plugins_activation.pynew file mode 100644index 00000000000..f1cf3d927cd--- /dev/null+++ b/hermes_cli/plugins_activation.py@@ -0,0 +1,140 @@+"""Mid-run plugin activation: what a just-loaded plugin does NOW vs next session (#87770).++One seam for every surface: ``PluginManager.on_plugin_loaded`` fires with one+:func:`plugin_activation_summary` per loaded plugin. Gateway handlers (slash commands, transform hooks,+platform callbacks) are live as soon as the plugin loads; tools, system-prompt sections and portable MCP+servers stay deferred — tools/prompt to the next session (prompt-cache invariant, same as+``/skills install``), MCP servers until ``mcp.reload``. :func:`activate_plugin_now` is what the install /+enable / update surfaces call after a successful config or tree change.+"""++from __future__ import annotations++import logging+from pathlib import Path+from typing import Any, Dict, List, Optional++logger = logging.getLogger(__name__)++# Hooks the gateway consults per inbound/outbound message: live as soon as the registry holds them.+_GATEWAY_TRANSFORM_HOOKS = frozenset({+ "transform_llm_output", "transform_tool_result", "transform_terminal_output", "pre_gateway_dispatch",+ "gateway_platform_event", "pre_command",+})+++def plugin_activation_summary(manager: Any, plugin_key: str) -> Dict[str, Any]:+ """``{name, key, activated_now: {kind: [names]}, deferred: {kind: [names]}}`` for one loaded plugin,+ read from what it actually registered (ownership ledger + handler registries), not from what its+ manifest promises. Keys appear only when non-empty.++ ``activated_now``: ``gateway_commands`` (slash names), ``gateway_transforms`` / ``hooks`` (hook names),+ ``callbacks`` (platforms with a ``register_platform_handler`` factory / Slack action ids).+ ``deferred``: ``tools`` (tool names; next session), ``prompt`` (section ids; next session),+ ``mcp_servers`` (the plugin's mcp.json server names as registered — ``<namespace>__<server>``;+ until ``mcp.reload``)."""+ loaded = manager._plugins.get(plugin_key)+ manifest = getattr(loaded, "manifest", None)+ name = getattr(manifest, "name", None) or plugin_key+ regs = [r for r in manager._ownership_ledger.get(plugin_key, []) if getattr(r, "active", True)]+ kinds: Dict[str, List[str]] = {}+ for reg in regs:+ kinds.setdefault(reg.kind, []).append(str(reg.key))+ now: Dict[str, List[str]] = {}+ if kinds.get("command"):+ now["gateway_commands"] = sorted(kinds["command"])+ hooks = set(kinds.get("hook", ()))+ if hooks & _GATEWAY_TRANSFORM_HOOKS:+ now["gateway_transforms"] = sorted(hooks & _GATEWAY_TRANSFORM_HOOKS)+ if hooks - _GATEWAY_TRANSFORM_HOOKS:+ now["hooks"] = sorted(hooks - _GATEWAY_TRANSFORM_HOOKS)+ callbacks = sorted(platform for platform, factories in manager._platform_handler_factories.items()+ if any(plugin == name for _f, plugin in factories))+ callbacks += [f"slack:{a}" for a in kinds.get("slack_action_handler", ())]+ if callbacks:+ now["callbacks"] = callbacks+ deferred: Dict[str, List[str]] = {}+ tools = sorted(set(kinds.get("tool", ())) | set(getattr(loaded, "tools_registered", None) or ())+ | set(getattr(manifest, "provides_tools", None) or ()))+ if tools:+ deferred["tools"] = tools+ if kinds.get("system_prompt_section"):+ deferred["prompt"] = sorted(kinds["system_prompt_section"])+ servers = sorted(set(kinds.get("portable_mcp", ())) | {+ s for s, owner in manager._portable_mcp_server_plugins.items() if owner == plugin_key})+ if servers:+ deferred["mcp_servers"] = servers+ return {"name": name, "key": plugin_key, "activated_now": now, "deferred": deferred}+++def activation_summaries(manager: Any) -> List[Dict[str, Any]]:+ """One summary per loaded (non-deferred-platform, non-errored) plugin — the ``on_plugin_loaded`` payload."""+ out = []+ for key, loaded in list(manager._plugins.items()):+ if getattr(loaded, "deferred", False) or getattr(loaded, "error", None):+ continue+ out.append(plugin_activation_summary(manager, key))+ return out+++def find_activation(summaries: Optional[List[Dict[str, Any]]], name: str) -> Optional[Dict[str, Any]]:+ """The summary for ``name`` (manifest name, canonical key, or bare leaf of the key)."""+ for entry in summaries or ():+ key = str(entry.get("key") or "")+ if name in (entry.get("name"), key, key.rsplit("/", 1)[-1]):+ return entry+ return None+++def activate_plugin_now(name: str, *, in_process: bool = True) -> Dict[str, Any]:+ """After an install/enable/update: load the plugin in THIS process (so ``on_plugin_loaded``+ subscribers here — the TUI/Desktop server — see it) and nudge the running gateway to do the same+ over its control socket so live adapters re-wire their handlers. Never raises.++ Returns ``{"gateway_reloaded": bool, "activation": summary | None, "restart_required": bool}``.+ ``restart_required`` is True only when no gateway answered (old gateway, not running): with a+ reload, nothing needs a restart — tools/prompt wait for the next session, MCP servers for+ ``mcp.reload``, and that is what ``activation`` says."""+ from hermes_constants import get_hermes_home+ activation: Optional[Dict[str, Any]] = None+ if in_process:+ try:+ from hermes_cli.plugins import discover_plugins, get_plugin_manager+ discover_plugins(force=True)+ activation = find_activation(activation_summaries(get_plugin_manager()), name)+ except Exception:+ logger.debug("in-process plugin reload after change to %r failed", name, exc_info=True)+ answer = None+ try:+ from gateway.control_socket import reload_gateway_plugins+ from hermes_constants import get_default_hermes_root+ home = Path(get_hermes_home())+ answer = reload_gateway_plugins(home)+ if answer is None:+ root = Path(get_default_hermes_root())+ if root.resolve() != home.resolve(): # a served secondary: the multiplexer's socket+ answer = reload_gateway_plugins(root, profile_home=home)+ except Exception:+ logger.debug("gateway reload-plugins nudge for %r failed", name, exc_info=True)+ reloaded = bool(answer and answer.get("reloaded"))+ if reloaded and activation is None:+ activation = find_activation((answer or {}).get("activations"), name)+ return {"gateway_reloaded": reloaded, "activation": activation, "restart_required": not reloaded}+++def activation_hint(result: Dict[str, Any]) -> str:+ """One honest sentence for CLI surfaces from an :func:`activate_plugin_now` result."""+ if not result.get("gateway_reloaded"):+ return "Restart the gateway for the plugin to take effect:\n hermes gateway restart"+ act = result.get("activation") or {}+ now, deferred = act.get("activated_now") or {}, act.get("deferred") or {}+ parts = []+ if now:+ parts.append("active in the running gateway now: " + ", ".join(sorted(now)))+ if deferred:+ labels: Dict[str, str] = {"tools": "tools (next session)", "prompt": "system prompt (next session)",+ "mcp_servers": "MCP servers (mcp.reload / next session)"}+ parts.append("deferred: " + ", ".join(labels.get(k, k) for k in sorted(deferred)))+ if not parts:+ return "Gateway reloaded plugins; nothing of this plugin needs a session or restart."+ return "Gateway reloaded plugins — " + "; ".join(parts) + "."diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.pyindex c4fdcaee76c..1c0fa816740 100644--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@ -917,8 +917,10 @@ def cmd_install(declared_caps = _declared_capabilities_from_manifest(installed_manifest, installed_name)if declared_caps:_run_capability_consent(console, installed_name, declared_caps, context="install")- console.print("[dim]Restart the gateway for the plugin to take effect:[/dim]")- console.print("[dim] hermes gateway restart[/dim]")+ if enable:+ # Loads it into the running gateway now (handlers live) or says what needs a restart (#87770).+ from hermes_cli.plugins_activation import activate_plugin_now, activation_hint+ console.print(f"[dim]{activation_hint(activate_plugin_now(installed_name, in_process=False))}[/dim]")console.print()@@ -1278,7 +1280,9 @@ def cmd_enable(name: str, allow_tool_override: Optional[bool] = None) -> None:_fail(console, f"[red]Error:[/red] {exc}")if _activate_key(key, enable=True):+ from hermes_cli.plugins_activation import activate_plugin_now, activation_hintconsole.print(f"[green]✓[/green] Plugin [bold]{key}[/bold] enabled. Takes effect on next session.")+ console.print(f"[dim]{activation_hint(activate_plugin_now(key, in_process=False))}[/dim]")else:console.print(f"[dim]Plugin '{key}' is already enabled.[/dim]")@@ -2030,11 +2034,16 @@ def dashboard_install_plugin(_set_plugin_enabled(installed_name, enable=True)deps = _install_python_dependencies_quietly(target, warnings)ap = target / "after-install.md"+ # Deps first, then load: the plugin activates in this process (TUI/Desktop server subscribers see it)+ # and in the running gateway; ``activation`` says what is live now vs next session (#87770).+ from hermes_cli.plugins_activation import activate_plugin_now+ activated = activate_plugin_now(installed_name) if enable else {+ "gateway_reloaded": False, "activation": None, "restart_required": False}return {"ok": True, "plugin_name": installed_name, "warnings": warnings,"python_dependencies": deps,"missing_env": [s["name"] for s in _missing_env_specs(installed_manifest)],- "after_install_path": str(ap) if ap.exists() else None, "enabled": enable,+ "after_install_path": str(ap) if ap.exists() else None, "enabled": enable, **activated,}@@ -2112,8 +2121,13 @@ def dashboard_set_agent_plugin_enabled(name: str, *, enabled: bool) -> dict[str,changed = _activate_key(key, enable=enabled)if changed:_toggle_plugin_toolset(key, enable=enabled)- # Config-only change: a running gateway/TUI scanned plugins once at start and will not pick it- # up, so every UI can say so (the CLI prints "Takes effect on next session") — #71595/#54941.+ if changed and enabled:+ # Load it now, here and in the running gateway; ``activation`` tells the UI what is live vs+ # deferred, and ``restart_required`` only survives when no gateway answered (#87770).+ from hermes_cli.plugins_activation import activate_plugin_now+ return {"ok": True, "name": key, "unchanged": False, **activate_plugin_now(key)}+ # Disable is config-only: there is no un-wire primitive, so a running gateway keeps the plugin's+ # handlers until restart and every UI says so — #71595/#54941.return {"ok": True, "name": key, "unchanged": not changed, "restart_required": changed}@@ -2142,8 +2156,10 @@ def dashboard_update_user_plugin(name: str, *, accept_capabilities: bool = Falsewarnings = list(result.warnings)new_target = target.parent / result.installed_namedeps = _install_python_dependencies_quietly(new_target, warnings) if result.changed else []+ from hermes_cli.plugins_activation import activate_plugin_now+ activated = activate_plugin_now(result.installed_name) if result.changed else {}return {"ok": True, "name": result.installed_name, "sha": result.sha, "unchanged": not result.changed,- "python_dependencies": deps, "warnings": warnings}+ "python_dependencies": deps, "warnings": warnings, **activated}msg = _pull_plugin_update(target,lambda rec: (diff --git a/hermes_cli/plugins_loader.py b/hermes_cli/plugins_loader.pyindex 39656eacdae..abdaf9d240f 100644--- a/hermes_cli/plugins_loader.py+++ b/hermes_cli/plugins_loader.py@@ -183,6 +183,47 @@ def _dist_installed(req: str) -> Optional[bool]:class PluginLoaderMixin:+ def on_plugin_loaded(self, callback: Callable[[List[Dict[str, Any]]], Any]) -> Callable[[], None]:+ """Subscribe to "a discovery sweep loaded plugins this process did not have": fires from INSIDE+ :meth:`discover_and_load` (never emitted by an install RPC) with one+ ``{name, key, activated_now, deferred}`` summary per NEWLY loaded plugin — every plugin at boot,+ just the newcomer after a mid-run ``hermes plugins install/enable``, Desktop / dashboard /+ ``plugins.manage`` install-enable-update, a tool-triggered force re-discovery or the gateway's+ ``reload-plugins`` verb (all of which run ``discover_plugins(force=True)``; a non-forced call+ short-circuits on ``_discovered`` and never fires). See+ :func:`hermes_cli.plugins_activation.plugin_activation_summary` for the payload: ``activated_now``+ (gateway commands/transforms/hooks/callbacks, live at once) vs ``deferred`` (``tools``/``prompt``+ until the next session, ``mcp_servers`` — the plugin's mcp.json server names — until ``mcp.reload``).+ Listeners belong to the process (gateway runner, TUI server), not to a plugin, so ``unload()``+ never clears them. Returns an unsubscribe callable. Fires on the discovering thread with the+ discovery lock released; marshal onto your own loop."""+ if not callable(callback):+ raise ValueError("on_plugin_loaded requires a callable")+ listeners = self._plugin_loaded_listeners+ listeners.append(callback)++ def _unsubscribe() -> None:+ try:+ listeners.remove(callback)+ except ValueError:+ pass+ return _unsubscribe++ def _notify_plugin_loaded(self, loaded_before: frozenset) -> None:+ """Fire every :meth:`on_plugin_loaded` listener for the plugins this sweep added over+ ``loaded_before``; nothing new = no event. One raising listener never starves the rest."""+ if not self._plugin_loaded_listeners:+ return+ from hermes_cli.plugins_activation import activation_summaries+ summaries = [s for s in activation_summaries(self) if s["key"] not in loaded_before]+ if not summaries:+ return+ for callback in list(self._plugin_loaded_listeners):+ try:+ callback(summaries)+ except Exception:+ logger.warning("plugin-loaded listener %r raised", callback, exc_info=True)+@staticmethoddef _platform_name_from_manifest(manifest: PluginManifest) -> str:"""Derive the platform name without importing the adapter: strip a trailing ``-platform`` from thediff --git a/plugins/AGENTS.md b/plugins/AGENTS.mdindex b3f21bacbd9..ec6b44a5c4d 100644--- a/plugins/AGENTS.md+++ b/plugins/AGENTS.md@@ -61,7 +61,11 @@ bare names resolve through the catalog or error.**Discovery timing pitfall:** `discover_plugins()` runs only as a side effect of importing`model_tools.py`. Code that reads plugin state without importing `model_tools.py` first must call`discover_plugins()` explicitly (idempotent). Hooks are invoked from `model_tools.py` (pre/post-tool) and `run_agent.py` (lifecycle). Auxiliary LLM calls (titling, compression, MoA, vision, ...)+tool) and `run_agent.py` (lifecycle). A non-forced `discover_plugins()` short-circuits on `_discovered`: every+mid-run load path (install/enable/update on any surface, `reload-plugins` verb) runs+`discover_plugins(force=True)`, and `PluginManager.on_plugin_loaded` fires from inside that sweep for the+newly loaded plugins with an activation summary (`hermes_cli/plugins_activation.py`: handlers live now;+tools/prompt next session; `deferred.mcp_servers` until `mcp.reload`). Never emit that event from an RPC. Auxiliary LLM calls (titling, compression, MoA, vision, ...)fire `pre_auxiliary_call`/`post_auxiliary_call` from `agent/auxiliary_hooks.py` (payload = the`*_api_request` shape + `aux_task`); they never fire the turn-scoped `pre/post_api_request` (#79733). When a plugin changes a default, add a migration guard keyedon an "existing config" signal (`_explicitly_configured`) so existing users keep the old default.diff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.pyindex b377ec3d04d..b38211b6725 100644--- a/plugins/platforms/slack/adapter.py+++ b/plugins/platforms/slack/adapter.py@@ -1685,13 +1685,19 @@ class SlackAdapter(BasePlatformAdapter):def _register_plugin_action_handlers(self) -> None:"""Wire ``ctx.register_slack_action_handler`` callbacks; each is wrapped so a plugin- exception is logged and slack_bolt still sees a clean ack."""+ exception is logged and slack_bolt still sees a clean ack. Idempotent per ``AsyncApp``:+ a ``(action_id, plugin)`` already registered on the live app is skipped, so the late+ re-wire (#87770) never stacks a second listener that would run the callback twice."""try:from hermes_cli.plugins import get_plugin_manager_plugin_handlers = get_plugin_manager().get_slack_action_handlers()except Exception as e: # pragma: no cover - defensivelogger.warning("[Slack] Could not load plugin action handlers: %s", e)_plugin_handlers = []+ if self._plugin_actions_app is not self._app:+ self._plugin_actions_app, self._plugin_actions_wired = self._app, set()+ _plugin_handlers = [(a, cb, n) for a, cb, n in _plugin_handlers+ if (repr(a), n) not in self._plugin_actions_wired]# Closure factory: slack_bolt passes ``None`` for unrecognised listener params, so loop# vars captured as default args (``_cb=_cb``) would be silently clobbered at dispatch.def _make_wrapper(cb, plugin_name):@@ -1712,11 +1718,23 @@ class SlackAdapter(BasePlatformAdapter):for _action_id, _cb, _plugin_name in _plugin_handlers:self._app.action(_action_id)(_make_wrapper(_cb, _plugin_name))+ self._plugin_actions_wired.add((repr(_action_id), _plugin_name))logger.debug("[Slack] Registered plugin action handler %s (from %s)", _action_id, _plugin_name)if _plugin_handlers:logger.info("[Slack] Wired %d plugin action handler(s)", len(_plugin_handlers))+ # ``(repr(action_id), plugin)`` pairs registered on ``_plugin_actions_app``; reset per AsyncApp.+ _plugin_actions_app: Any = None+ _plugin_actions_wired: set = frozenset()++ def rewire_plugin_handlers(self) -> None:+ """Late plugin loads carry both registries: action handlers and ``register_platform_handler``+ factories (base). Both are per-app idempotent."""+ if self._app is not None and self._plugin_actions_app is self._app:+ self._register_plugin_action_handlers()+ super().rewire_plugin_handlers()+@staticmethoddef _new_web_client(token: str, proxy_url: Optional[str]) -> Any:client = AsyncWebClient(token=token, user_agent_prefix=_HERMES_SLACK_USER_AGENT_PREFIX)diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex c6c68ae3056..ede20eb9677 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -2916,6 +2916,8 @@ class TelegramAdapter(BasePlatformAdapter):def _register_handlers(self, app) -> None:"""Register every PTB handler on ``app`` (initial connect and the transient-init rebuild)."""+ table = getattr(app, "handlers", None)+ core_before = {g: len(hs) for g, hs in table.items()} if isinstance(table, dict) else {}app.add_handler(TelegramMessageHandler(filters.TEXT & ~filters.COMMAND, self._handle_text_message))app.add_handler(TelegramMessageHandler(filters.COMMAND, self._handle_command))app.add_handler(TelegramMessageHandler(@@ -2928,6 +2930,30 @@ class TelegramAdapter(BasePlatformAdapter):app.add_handler(InlineQueryHandler(self._handle_inline_query))# gateway_platform_event observer: group 99 observes alongside, never displaces, core handlers.app.add_handler(TypeHandler(Update, self._on_platform_update), group=99)+ # Everything appended above is core; a late plugin re-wire must land BEFORE these (#87770).+ if isinstance(table, dict):+ self._core_handler_ids = {id(h) for g, hs in table.items() for h in hs[core_before.get(g, 0):]}++ def _wire_plugin_handlers(self, native: Any = None) -> None:+ """PTB dispatches the FIRST matching handler per group and core registers catch-alls+ (``filters.COMMAND``, ``CallbackQueryHandler``), so a plugin handler appended after connect+ would never fire. Move whatever a late factory added ahead of the first core handler of its+ group, keeping the plugin handlers' own relative order."""+ handlers = getattr(native, "handlers", None)+ core_ids = getattr(self, "_core_handler_ids", None)+ if not isinstance(handlers, dict) or not core_ids:+ super()._wire_plugin_handlers(native) # first wire runs before core registers: nothing to hoist+ return+ before = {g: list(hs) for g, hs in handlers.items()}+ super()._wire_plugin_handlers(native)+ for group, current in handlers.items():+ prior = before.get(group, [])+ prior_ids = {id(h) for h in prior}+ added = [h for h in current if id(h) not in prior_ids]+ first_core = next((i for i, h in enumerate(prior) if id(h) in core_ids), None)+ if not added or first_core is None:+ continue+ current[:] = prior[:first_core] + added + prior[first_core:]async def _build_ptb_requests(self) -> tuple:"""Build the (general, getUpdates) HTTPXRequest pair: fallback-IP transport, explicit proxy, or@@ -3079,7 +3105,10 @@ class TelegramAdapter(BasePlatformAdapter):old_app = self._appself._app = builder.build()self._bot = self._app.bot- self._register_handlers(self._app) # keep core and observer handlers in lockstep+ # Same order as connect(): plugin handlers first (the wired-set is keyed per app, so+ # the rebuilt app gets them again), then core and the observer in lockstep.+ self._wire_plugin_handlers(self._app)+ self._register_handlers(self._app)with contextlib.suppress(Exception):await _shutdown_abandoned_app(old_app)diff --git a/tests/gateway/test_late_plugin_rewire.py b/tests/gateway/test_late_plugin_rewire.pynew file mode 100644index 00000000000..1d12cc58655--- /dev/null+++ b/tests/gateway/test_late_plugin_rewire.py@@ -0,0 +1,147 @@+"""#87770 — plugins loaded after the gateway started get their platform handlers wired.++Invariants (each red on base):+* ``PluginManager.on_plugin_loaded`` fires after a discovery pass with an activation summary per plugin+ (what is live now vs deferred), through the real discovery path.+* ``rewire_plugin_handlers()`` is idempotent: a factory runs once per native client, however often+ the loaded event fires (a force re-discovery hands back NEW factory objects for the same plugin).+* Telegram: a late plugin handler is hoisted ahead of core's catch-all ``filters.COMMAND`` handler.+* Slack: a late ``register_slack_action_handler`` registers one Bolt listener, never two.+* The runner subscribes at boot and re-wires every live adapter on the loop.+"""++from __future__ import annotations++import asyncio+import os+import textwrap+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest++from gateway.config import PlatformConfig, Platform+from gateway.run_plugin_rewire import GatewayPluginRewireMixin+from hermes_cli.plugins import PluginContext, PluginManager, PluginManifest, discover_plugins, get_plugin_manager+from plugins.platforms.telegram.adapter import TelegramAdapter+++def _write_plugin(home: Path, name: str = "late_cmd") -> None:+ d = home / "plugins" / name+ d.mkdir(parents=True)+ (d / "plugin.yaml").write_text(f"name: {name}\nversion: '0.1'\ndescription: t\nprovides_tools: [late_tool]\n")+ (d / "__init__.py").write_text(textwrap.dedent('''+ def register(ctx):+ ctx.register_command("late", lambda raw: "hi", description="late")+ ctx.register_platform_handler("telegram", lambda app, adapter: None)+ '''))+ (home / "config.yaml").write_text(f"plugins:\n enabled: [{name}]\n")+++def test_on_plugin_loaded_fires_with_activation_summary_after_a_late_load():+ home = Path(os.environ["HERMES_HOME"])+ manager = get_plugin_manager()+ discover_plugins() # boot: plugin not on disk yet+ events: list = []+ unsubscribe = manager.on_plugin_loaded(events.append)+ _write_plugin(home)+ discover_plugins(force=True) # the mid-run load+ late = [e for e in events[-1] if e["name"] == "late_cmd"]+ assert late == [{"name": "late_cmd", "key": "late_cmd",+ "activated_now": {"gateway_commands": ["late"], "callbacks": ["telegram"]},+ "deferred": {"tools": ["late_tool"]}}]+ assert len(events) == 1 # only the sweep that added it fires — and only for the newcomer+ discover_plugins(force=True) # nothing new: no event (the gateway re-wire is not spammed)+ assert len(events) == 1+ unsubscribe()+++def _factory_manager(calls: list, plugin: str = "p") -> PluginManager:+ mgr = PluginManager()+ ctx = PluginContext(manifest=PluginManifest(name=plugin, version="0", description=""), manager=mgr)++ def factory(native, adapter):+ calls.append(native)+ ctx.register_platform_handler("telegram", factory)+ return mgr+++def test_rewire_is_idempotent_per_native_client():+ calls: list = []+ adapter = TelegramAdapter(PlatformConfig(enabled=True, token="t", extra={}))+ with patch("hermes_cli.plugins.get_plugin_manager", return_value=_factory_manager(calls)):+ adapter.rewire_plugin_handlers() # before connect wired anything: nothing to do+ assert calls == []+ adapter._wire_plugin_handlers("app-1")+ adapter.rewire_plugin_handlers()+ adapter.rewire_plugin_handlers()+ assert calls == ["app-1"]+ # A force re-discovery re-registers a NEW factory object for the same plugin: still once.+ with patch("hermes_cli.plugins.get_plugin_manager", return_value=_factory_manager(calls)):+ adapter.rewire_plugin_handlers()+ assert calls == ["app-1"]+ adapter._wire_plugin_handlers("app-2") # rebuilt native client: wired again, once+ assert calls == ["app-1", "app-2"]+++class _PtbApp:+ """``Application.add_handler`` semantics that matter: append to ``handlers[group]``; PTB dispatches+ the first matching handler per group in that list order (tests/gateway mocks the real SDK)."""++ def __init__(self):+ self.handlers: dict = {}++ def add_handler(self, handler, group: int = 0):+ self.handlers.setdefault(group, []).append(handler)+++def test_telegram_late_plugin_handler_precedes_core_catch_all():+ app = _PtbApp()+ adapter = TelegramAdapter(PlatformConfig(enabled=True, token="t", extra={}))+ plugin_handler = object()+ mgr = PluginManager()+ ctx = PluginContext(manifest=PluginManifest(name="p", version="0", description=""), manager=mgr)+ with patch("hermes_cli.plugins.get_plugin_manager", return_value=mgr):+ adapter._wire_plugin_handlers(app) # connect(): plugins first (none yet), then core+ adapter._register_handlers(app)+ core = list(app.handlers[0]) # text catch-all, COMMAND catch-all, ..., CallbackQueryHandler+ ctx.register_platform_handler("telegram", lambda a, _adapter: a.add_handler(plugin_handler))+ adapter.rewire_plugin_handlers()+ adapter.rewire_plugin_handlers()+ group0 = app.handlers[0]+ assert group0 == [plugin_handler] + core # ahead of every core catch-all, core order untouched+ assert app.handlers[99] and plugin_handler not in app.handlers[99] # the group-99 observer stays alone+++def test_slack_late_action_handler_registers_one_listener():+ from plugins.platforms.slack.adapter import SlackAdapter+ adapter = SlackAdapter(PlatformConfig(enabled=True, token="xoxb-t", extra={}))+ adapter._app = MagicMock()+ mgr = PluginManager()+ ctx = PluginContext(manifest=PluginManifest(name="p", version="0", description=""), manager=mgr)+ with patch("hermes_cli.plugins.get_plugin_manager", return_value=mgr):+ adapter._register_plugin_action_handlers() # connect+ async def cb(ack, body, action):+ pass+ ctx.register_slack_action_handler("late_btn", cb)+ adapter.rewire_plugin_handlers()+ adapter.rewire_plugin_handlers()+ assert [c.args[0] for c in adapter._app.action.call_args_list] == ["late_btn"]+++def test_runner_rewires_live_adapters_on_the_loop_when_plugins_load():+ class Runner(GatewayPluginRewireMixin):+ adapters = {Platform.TELEGRAM: MagicMock()}++ _write_plugin(Path(os.environ["HERMES_HOME"])) # something must actually load for the event to fire+ mgr = PluginManager()++ async def scenario():+ runner = Runner()+ runner._subscribe_plugin_rewire(mgr)+ runner._subscribe_plugin_rewire(mgr) # a served-profile rescan re-enters: one listener+ await asyncio.to_thread(mgr.discover_and_load, True) # fires on another thread+ await asyncio.sleep(0)+ return runner.adapters[Platform.TELEGRAM].rewire_plugin_handlers.call_count++ assert asyncio.run(scenario()) == 1diff --git a/tests/hermes_cli/test_plugins_cmd_activation_keys.py b/tests/hermes_cli/test_plugins_cmd_activation_keys.pyindex b4228836445..bf340b4009d 100644--- a/tests/hermes_cli/test_plugins_cmd_activation_keys.py+++ b/tests/hermes_cli/test_plugins_cmd_activation_keys.py@@ -60,7 +60,11 @@ def test_dashboard_toggle_writes_canonical_key_and_clears_stale_aliases(home):result = plugins_cmd.dashboard_set_agent_plugin_enabled("zzprobe", enabled=True)- assert result == {"ok": True, "name": "obs/zzprobe", "unchanged": False, "restart_required": True}+ # The enable also loads the plugin now (#87770): with no gateway answering, a restart is still the+ # honest hint and the activation summary rides along.+ assert {k: result[k] for k in ("ok", "name", "unchanged", "restart_required")} == {+ "ok": True, "name": "obs/zzprobe", "unchanged": False, "restart_required": True}+ assert result["gateway_reloaded"] is Falseenabled, disabled = _lists()assert enabled == {"obs/zzprobe"} and disabled == set()manifest = next(m for m in collect_directory_manifests() if m.name == "zz-probe-manifest")diff --git a/tests/tui_gateway/test_plugins_manage_late_activation.py b/tests/tui_gateway/test_plugins_manage_late_activation.pynew file mode 100644index 00000000000..0d15448bcbf--- /dev/null+++ b/tests/tui_gateway/test_plugins_manage_late_activation.py@@ -0,0 +1,66 @@+"""#87770 — a Desktop/TUI ``plugins.manage install`` is a mid-run load path too: the install performs a REAL+forced rescan in the serving process, ``PluginManager.on_plugin_loaded`` fires from inside it for the newcomer,+and the RESULT carries the activation summary (live now vs deferred, ``deferred.mcp_servers`` naming the+plugin's mcp.json servers) plus ``gateway_reloaded`` / ``restart_required``.++The broken invariant: before, ``_plugins_install`` returned with no rescan, so a later non-forced+``discover_plugins()`` (``tools/mcp_tool_config._portable_mcp_servers`` → ``reload.mcp``) short-circuited on+``_discovered`` and never saw the new plugin's MCP servers until a full relaunch."""++from __future__ import annotations++import json+import os+from pathlib import Path+from unittest.mock import patch++from hermes_cli.plugins import get_plugin_manager+from tui_gateway import server+++def _fake_install_core(identifier, *, force=False, ref=None):+ """Stand-in for the git clone: a portable plugin (mcp.json + a skill) under the sandbox plugins dir,+ returning ``(target, manifest, name)`` like the real core."""+ from hermes_cli.agent_plugins import MCP_SCHEMA_V1, PLUGIN_SCHEMA_V1+ from hermes_cli.plugins_cmd import _plugins_dir, _read_manifest+ target = _plugins_dir() / "late-mcp"+ (target / "skills" / "late").mkdir(parents=True)+ (target / "plugin.json").write_text(json.dumps({"$schema": PLUGIN_SCHEMA_V1, "name": "late-mcp"}))+ (target / "skills" / "late" / "SKILL.md").write_text("---\nname: late\ndescription: d\n---\nBody.\n")+ (target / "mcp.json").write_text(json.dumps({+ "$schema": MCP_SCHEMA_V1, "mcpServers": {"worker": {"type": "stdio", "command": "python"}}}))+ return target, _read_manifest(target), "late-mcp"+++def test_plugins_manage_install_rescans_fires_on_plugin_loaded_and_exposes_mcp_servers():+ (Path(os.environ["HERMES_HOME"]) / "plugins").mkdir(exist_ok=True)+ manager = get_plugin_manager()+ manager.discover_and_load() # the serve process booted long before the install+ events: list = []+ manager.on_plugin_loaded(events.append)+ from hermes_cli import plugins_cmd+ real_install = plugins_cmd.dashboard_install_plugin++ def _install(*args, **kwargs):+ result = real_install(*args, **kwargs)+ # ``PluginsManageResult.python_dependencies`` ships in a sibling PR; until it lands the strict+ # contract rejects the key. Everything else is the real core.+ result.pop("python_dependencies", None)+ return result++ with patch("hermes_cli.plugins_cmd.dashboard_install_plugin", _install), \+ patch("hermes_cli.plugins_cmd._install_plugin_core", _fake_install_core), \+ patch("hermes_cli.plugins_cmd._install_python_dependencies_quietly", return_value=[]), \+ patch("gateway.control_socket.reload_gateway_plugins", return_value=None): # no gateway running+ resp = server.handle_request({"id": "1", "method": "plugins.manage",+ "params": {"action": "install", "repo": "owner/late-mcp", "enable": True}})+ result = resp["result"]+ assert [e["name"] for e in events[-1]] == ["late-mcp"] # fired from inside the rescan, newcomer only+ servers = result["activation"]["deferred"]["mcp_servers"]+ assert servers and all(s.endswith("__worker") for s in servers)+ assert result["gateway_reloaded"] is False and result["restart_required"] is True+ # The invariant that was broken: a later NON-forced discovery (what reload.mcp runs) sees the servers.+ from tools.mcp_tool_config import _portable_mcp_servers+ merged: dict = {}+ _portable_mcp_servers(merged)+ assert set(merged) == set(servers)diff --git a/tui_gateway/contracts/tools_mcp_plugins.py b/tui_gateway/contracts/tools_mcp_plugins.pyindex 5ca8a9a53fd..75b58c47a61 100644--- a/tui_gateway/contracts/tools_mcp_plugins.py+++ b/tui_gateway/contracts/tools_mcp_plugins.py@@ -671,10 +671,27 @@ class AgentPluginRow(Result):settings_schema: list[PluginSettingField] | None = None+class PluginActivation(Result):+ """What a plugin loaded mid-run does NOW vs later (``hermes_cli.plugins_activation``), ``{kind: [names]}``+ with only non-empty kinds present. ``activated_now`` kinds: ``gateway_commands`` (slash names),+ ``gateway_transforms`` / ``hooks`` (hook names), ``callbacks`` (platforms / ``slack:<action_id>``) — live in+ the running gateway once it reloaded (``gateway_reloaded``). ``deferred`` kinds: ``tools`` (tool names) and+ ``prompt`` (section ids) apply from the next session; ``mcp_servers`` lists the plugin's mcp.json server+ names (``<namespace>__<server>``, as ``mcp.servers.*`` know them) — not connected until ``mcp.reload``.+ The Desktop "Installed. Connect its servers now" card reads exactly ``deferred.mcp_servers``."""++ name: str+ key: str+ activated_now: dict[str, list[str]] = Field(default_factory=dict)+ deferred: dict[str, list[str]] = Field(default_factory=dict)++class PluginsManageResult(Result):"""``list`` → ``plugins`` + counts; ``toggle`` → ``ok``/``unchanged``/``restart_required``/``name``(the canonical key written)/``plugin``; ``install`` → ``hermes_cli.plugins_cmd.dashboard_install_plugin``'s- ok payload; ``update`` → ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the+ ok payload; ``toggle``/``install``/``update`` that loaded a plugin also carry ``gateway_reloaded`` (the+ running gateway picked it up and re-wired its handlers) and ``activation`` — the honest split of what is+ live now vs deferred, so ``restart_required`` is True only when no gateway answered; ``update`` → ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the``delta`` (``{surface: [added...]}``) / ``delta_lines`` a widened pin adds — nothing changed until theclient retries with ``accept_capabilities``; ``remove`` → ``ok``/``name`` plus``cleared_memory_provider`` when the removed plugin was the live ``memory.provider``."""@@ -685,6 +702,8 @@ class PluginsManageResult(Result):ok: bool | None = Noneunchanged: bool | None = Nonerestart_required: bool | None = None+ gateway_reloaded: bool | None = None+ activation: PluginActivation | None = Nonecleared_memory_provider: bool | None = Nonename: str | None = Noneplugin: AgentPluginRow | None = Nonediff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.pyindex 6bc6b93f031..9208e0189eb 100644--- a/tui_gateway/methods_tools.py+++ b/tui_gateway/methods_tools.py@@ -1537,6 +1537,35 @@ def _plugin_rows() -> list[dict]:return out+# Latest ``on_plugin_loaded`` summaries by plugin name — the TUI server's own subscription, so an+# install/toggle/update result reports what the load actually activated (#87770). One listener per manager.+_plugin_activations: dict = {}+_plugin_activation_subscribed: set = set()+++def _ensure_plugin_activation_listener() -> None:+ from hermes_cli.plugins import get_plugin_manager+ manager = get_plugin_manager()+ if manager.scope_key in _plugin_activation_subscribed:+ return+ _plugin_activation_subscribed.add(manager.scope_key)++ def _on_loaded(summaries) -> None:+ for entry in summaries:+ _plugin_activations[entry["name"]] = entry+ _plugin_activations[entry["key"]] = entry+ manager.on_plugin_loaded(_on_loaded)+++def _with_activation(result: dict, name: str) -> dict:+ """Prefer the summary this process's listener captured over the core's own copy."""+ for key in (name, result.get("plugin_name"), result.get("name")):+ if key and key in _plugin_activations:+ result["activation"] = _plugin_activations[key]+ break+ return result++def _plugins_list(rid, params):rows = _plugin_rows()user_count = sum(1 for r in rows if r["source"] != "bundled")@@ -1548,6 +1577,7 @@ def _plugins_toggle(rid, params):ident = (params.get("key") or params.get("name") or "").strip()if not ident:return _err(rid, 4019, "plugins.toggle requires a 'key' or 'name'")+ _ensure_plugin_activation_listener()toggle = _tools_mod("hermes_cli.plugins_cmd").dashboard_set_agent_plugin_enabledresult = toggle(ident, enabled=bool(params.get("enable")))if not result.get("ok"):@@ -1555,8 +1585,11 @@ def _plugins_toggle(rid, params):# The toggle resolves a bare leaf / manifest name to the canonical key it wrote; report that key.key = result.get("name") or identrow = next((r for r in _plugin_rows() if key in (r["key"], r["name"])), None)- return _ok(rid, {"ok": True, "unchanged": bool(result.get("unchanged")),- "restart_required": bool(result.get("restart_required")), "name": key, "plugin": row})+ return _ok(rid, _with_activation({+ "ok": True, "unchanged": bool(result.get("unchanged")),+ "restart_required": bool(result.get("restart_required")),+ "gateway_reloaded": bool(result.get("gateway_reloaded")), "activation": result.get("activation"),+ "name": key, "plugin": row}, key))def _plugins_install(rid, params):@@ -1566,10 +1599,13 @@ def _plugins_install(rid, params):catalog_name = str(params.get("catalog_name") or "").strip()if not ident and not catalog_name:return _err(rid, 4019, "plugins.install requires 'identifier', 'repo', or 'catalog_name'")+ _ensure_plugin_activation_listener()result = _tools_mod("hermes_cli.plugins_cmd").dashboard_install_plugin(ident, force=bool(params.get("force")), enable=params.get("enable", True), catalog_name=catalog_name or None,ref=str(params.get("ref") or "").strip() or None)- return _ok(rid, result) if result.get("ok") else _err(rid, 5026, result.get("error") or "install failed")+ if not result.get("ok"):+ return _err(rid, 5026, result.get("error") or "install failed")+ return _ok(rid, _with_activation(result, str(result.get("plugin_name") or "")) if result.get("enabled") else result)def _plugins_update(rid, params):@@ -1593,8 +1629,13 @@ def _plugins_update(rid, params):"delta_lines": cat.surface_delta_lines(e.delta), "error": str(e)})except pc.PluginOperationError as e:return _err(rid, 4021, str(e))- return _ok(rid, {"ok": True, "unchanged": not result.changed, "sha": result.sha, "name": result.installed_name,- "warnings": list(result.warnings)})+ payload = {"ok": True, "unchanged": not result.changed, "sha": result.sha, "name": result.installed_name,+ "warnings": list(result.warnings)}+ if result.changed:+ _ensure_plugin_activation_listener()+ activate = _tools_mod("hermes_cli.plugins_activation").activate_plugin_now+ payload = _with_activation({**payload, **activate(result.installed_name)}, result.installed_name)+ return _ok(rid, payload)def _plugins_remove(rid, params):diff --git a/website/docs/developer-guide/gateway-internals.md b/website/docs/developer-guide/gateway-internals.mdindex 543793d5076..5333ba3576e 100644--- a/website/docs/developer-guide/gateway-internals.md+++ b/website/docs/developer-guide/gateway-internals.md@@ -288,6 +288,27 @@ With `gateway.multiplex_profiles: true` one process serves the default profile pSecret reads fail closed (`agent.secret_scope.get_secret` raises `UnscopedSecretError`) only after `set_multiplex_active(True)`, which the gateway, cron, `gateway migrate` and the Desktop/dashboard `serve` backend set. Adapter YAML never reaches `os.environ` under multiplex: `gateway/platforms/_shared.py::apply_yaml_bridge` seeds `PlatformConfig.extra` and skips the environ write under a secondary's scope; gates read through `platform_gate_env`. Shared-ingress platforms (WhatsApp bridge, Relay) run on the default profile only; a secondary that enables one is logged once and stamped into runtime status (`run_adapters.py::_note_unserved_secondary_platform`). Per-profile isolation as the user sees it: [Multi-profile gateways § What is isolated per profile](../user-guide/multi-profile-gateways.md#what-is-isolated-per-profile).+## Mid-run plugin loading++Plugins that load after the adapters connected (install/enable from the CLI, Desktop, dashboard or+`plugins.manage`; a tool-triggered force re-discovery) re-wire their platform handlers without a restart+(#87770). The pieces, all in `gateway/run_plugin_rewire.py`:++- **Discovery listener** — `_start_recover_previous_run` subscribes `PluginManager.on_plugin_loaded` for the+ launch profile and `_load_secondary_profile_config` does so per served profile. The event fires from inside+ `discover_and_load` (never from an RPC) for the newly loaded plugins; the callback hops onto the gateway+ loop with `call_soon_threadsafe`.+- **Idempotent re-wire** — `BasePlatformAdapter.rewire_plugin_handlers()` re-reads+ `get_platform_handler_factories(platform)` and runs only factories not yet wired on the live native+ client (keyed `(plugin, qualname)` because a force reload hands back new function objects). Telegram+ hoists the added handlers ahead of core's catch-alls; Slack also re-registers missing+ `register_slack_action_handler` callbacks once per `AsyncApp`.+- **`reload-plugins` control verb** — other processes (`hermes plugins install`, `hermes serve`) ask the+ running gateway to force-rescan the requested (served) home; the answer carries `plugins`, per-plugin+ `activations` and `adapters_rewired`, so the caller can say "active now" truthfully.+- **Scope limit** — handlers only. Tools and system-prompt sections of a late plugin wait for the next+ session (prompt-cache invariant); portable MCP servers wait for `mcp.reload`. Nothing un-wires on disable.+## Related Docs- [Session Storage](./session-storage.md)diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.mdindex 812594637fd..4e1f87e2cc5 100644--- a/website/docs/developer-guide/plugins/index.md+++ b/website/docs/developer-guide/plugins/index.md@@ -1459,6 +1459,36 @@ def register(ctx):ctx.register_platform_handler("discord", _wire)```+### Mid-run plugin loading: what activates now vs next session++A plugin can load while the gateway (or the TUI/Desktop server) is already running: `hermes plugins+install`/`enable`, a Desktop or dashboard install, a catalog re-pin, or a tool-triggered force+re-discovery. Every one of those paths runs a **real forced rescan** (`discover_plugins(force=True)`) and+`PluginManager.on_plugin_loaded(callback)` fires from inside it with one summary per **newly** loaded plugin+(`hermes_cli/plugins_activation.py`):++```python+{"name": "late-mcp", "key": "late-mcp",+ "activated_now": {"gateway_commands": ["late"], "callbacks": ["telegram"]},+ "deferred": {"tools": ["late_tool"], "prompt": ["late.section"], "mcp_servers": ["late_mcp__worker"]}}+```++- **Active immediately** — gateway slash commands, gateway transform hooks / other hooks, and platform+ callbacks: the gateway runner subscribes at boot and calls every live adapter's idempotent+ `rewire_plugin_handlers()`, so a `register_platform_handler` factory (or Slack action handler) registered+ by a late plugin is wired without a restart. Re-wiring is deduped per native client by `(plugin, factory+ qualname)`; on Telegram the late handlers are hoisted ahead of core's catch-all `filters.COMMAND` /+ `CallbackQueryHandler` (PTB dispatches the first match per group), exactly as they would sit at connect.+- **Deferred** — `tools` and `prompt` sections apply from the **next session** (the running session's+ prompt/tool schema is cache-stable, same rule as `/skills install`); `mcp_servers` (the plugin's+ `mcp.json` servers, named `<namespace>__<server>`) connect on `mcp.reload` or the next session.+- There is no un-wire: disabling a plugin mid-run keeps its already-wired handlers until the gateway+ restarts, and the surfaces say so.++Install surfaces report exactly this split: `hermes plugins install/enable` prints it after nudging the running+gateway (`reload-plugins` control-socket verb), `plugins.manage install/toggle/update` returns `activation` ++`gateway_reloaded` (`restart_required` is true only when no gateway answered).+:::tipThis guide covers **general plugins** (tools, hooks, slash commands, CLI commands). The sections below sketch the authoring pattern for each specialized plugin type; each links to its full guide for field reference and examples.:::