Skip to content

The agent that grows with you

feat(plugins): widen ownership ledger to all registration surfaces

Teknium221974799060
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.py
index 6b244814393..21ac1e71be6 100644
--- a/hermes_cli/plugins.py
+++ b/hermes_cli/plugins.py
@@ -1270,6 +1270,45 @@ class PluginContext:
except Exception:
return "default"
+ # -- lifecycle: unload callbacks and supervised tasks --------------------
+
+ def on_unload(self, callback: Callable[[], None]) -> PluginRegistration:
+ """Register a cleanup callback that runs when this plugin unloads.
+
+ Callbacks are recorded in the ownership ledger, so they run in
+ reverse acquisition order interleaved with registration teardown,
+ and each is isolated — an exception is logged, never propagated
+ (see :meth:`PluginManager._dispose_registrations`).
+ """
+ if not callable(callback):
+ raise TypeError("on_unload callback must be callable")
+ handle = self._track("on_unload", getattr(callback, "__name__", "callback"), callback)
+ logger.debug("Plugin %s registered on_unload callback", self.manifest.name)
+ return handle
+
+ def spawn_task(self, coro, *, name: Optional[str] = None) -> "asyncio.Task":
+ """Spawn a supervised background asyncio task owned by this plugin.
+
+ The task is recorded in the ownership ledger; unloading the plugin
+ (or a force reload) cancels it. Requires a running event loop.
+ """
+ if not asyncio.iscoroutine(coro):
+ raise TypeError("spawn_task expects a coroutine")
+ loop = asyncio.get_running_loop()
+ task_name = name or f"plugin:{self.plugin_id}:task"
+ task = loop.create_task(coro, name=task_name)
+
+ def _cancel_task() -> None:
+ if not task.done():
+ task.cancel()
+
+ handle = self._track("background_task", task_name, _cancel_task)
+ task.add_done_callback(lambda _t: handle.dispose())
+ logger.debug(
+ "Plugin %s spawned supervised task: %s", self.manifest.name, task_name
+ )
+ return task
+
# -- approval transport registration ------------------------------------
def register_approval_transport(self, name: str, present_fn: Callable) -> None:
@@ -1286,6 +1325,26 @@ class PluginContext:
present_fn,
plugin_id=self.manifest.key or self.manifest.name,
)
+ # Record ownership so unload/force-reload removes this transport.
+ # Duplicate names are rejected above (raise), so there is never a
+ # displaced previous entry to restore.
+ clean = str(name).strip().lower()
+ entry = self._manager._approval_transports.get(clean)
+ if entry is not None:
+ self._track_replacement(
+ "approval_transport",
+ clean,
+ slot=(
+ "manager_mapping",
+ id(self._manager._approval_transports),
+ clean,
+ ),
+ current=entry,
+ previous=None,
+ restore=lambda replacement: self._manager._restore_mapping(
+ self._manager._approval_transports, clean, entry, replacement
+ ),
+ )
# -- tool registration --------------------------------------------------
@@ -2575,7 +2634,7 @@ class PluginContext:
*,
position: str = "after_memory",
max_chars: int = DEFAULT_SYSTEM_PROMPT_SECTION_MAX_CHARS,
- ) -> None:
+ ) -> PluginRegistration:
"""Register bounded context that is frozen into each new session prompt.
Callables receive a read-only session-info mapping. The rendered full
@@ -2610,13 +2669,40 @@ class PluginContext:
f"plugin {existing.plugin!r}"
)
plugin_id = self.manifest.key or self.manifest.name
- self._manager._system_prompt_sections[id] = PluginSystemPromptSection(
+ section = PluginSystemPromptSection(
id=id,
content=content,
position=position,
max_chars=max_chars,
plugin=plugin_id,
)
+ self._manager._system_prompt_sections[id] = section
+ # Record ownership so unload/force-reload removes this section.
+ # Duplicate ids are rejected above (raise), so there is never a
+ # displaced previous entry to restore. The parameter ``id`` shadows
+ # the builtin, so capture the mapping identity via ``builtins.id``.
+ import builtins
+
+ handle = self._track_replacement(
+ "system_prompt_section",
+ id,
+ slot=(
+ "manager_mapping",
+ builtins.id(self._manager._system_prompt_sections),
+ id,
+ ),
+ current=section,
+ previous=existing,
+ restore=lambda replacement: self._manager._restore_mapping(
+ self._manager._system_prompt_sections, id, section, replacement
+ ),
+ )
+ logger.debug(
+ "Plugin %s registered system prompt section: %s",
+ self.manifest.name,
+ id,
+ )
+ return handle
# -- inter-plugin event bus --------------------------------------------
@@ -2849,6 +2935,19 @@ class PluginManager:
self._slack_action_handlers: List[tuple] = []
# Registration handles are kept both per plugin (ownership lookup) and
# globally (reverse-order teardown for overrides spanning plugins).
+ #
+ # Multi-profile constraint (#65593): several process-global registries
+ # (tools, platforms, providers) are shared across profiles while
+ # multiple PluginManager instances may coexist in one process (keyed
+ # by resolved hermes home). The ledger is therefore keyed per manager
+ # — i.e. per (hermes_home, plugin_id) — and every release/restore
+ # closure is identity-conditional, so one profile's unload can never
+ # clear another profile's registrations. Registry overlays keyed by
+ # scope_key (see tools/registry.py and gateway/platform_registry.py)
+ # carry the profile dimension; anything still process-global is
+ # guarded by the identity checks. TODO(#64178): extend explicit
+ # profile keying to any remaining process-global slots when the
+ # symmetric force-reload lands.
self._ownership_ledger: Dict[str, List[PluginRegistration]] = {}
self._registration_order: List[PluginRegistration] = []
@@ -2902,10 +3001,10 @@ class PluginManager:
def _restore_mapping(
self,
- mapping: Dict[str, dict],
+ mapping: Dict[str, Any],
key: str,
- current: dict,
- previous: Optional[dict],
+ current: Any,
+ previous: Optional[Any],
) -> bool:
"""Restore a manager-local mapping only when *current* is still present."""
if mapping.get(key) is not current:
@@ -3014,8 +3113,9 @@ class PluginManager:
reverse acquisition order. Registry inverses are conditional on the
exact object still being current, so a later registration is never
removed accidentally. ``plugin=None`` is the lifecycle operation
- used by force rediscovery; lifecycle callbacks and supervised tasks
- are intentionally left for the follow-up slice of #64229.
+ used by force rediscovery. ``on_unload`` callbacks and supervised
+ background tasks registered through :class:`PluginContext` are
+ disposed through the same reverse-order ledger walk.
Returns ``True`` when at least one plugin or registration was found.
"""
diff --git a/tests/hermes_cli/test_plugin_ownership_ledger.py b/tests/hermes_cli/test_plugin_ownership_ledger.py
index f52854f94df..35d0bbaa771 100644
--- a/tests/hermes_cli/test_plugin_ownership_ledger.py
+++ b/tests/hermes_cli/test_plugin_ownership_ledger.py
@@ -33,6 +33,8 @@ def _write_plugin(hermes_home: Path) -> None:
"def _middleware(**kwargs):\n"
" return {'middleware': 'ledger'}\n"
"\n"
+ "UNLOADED = []\n"
+ "\n"
"def register(ctx):\n"
" ctx.register_tool(\n"
" name='ledger_probe_tool',\n"
@@ -65,6 +67,13 @@ def _write_plugin(hermes_home: Path) -> None:
" 'ledger-probe', Path(__file__).with_name('SKILL.md'),\n"
" 'Ledger skill',\n"
" )\n"
+ " ctx.register_system_prompt_section(\n"
+ " 'ledger-probe-section', 'ledger probe section content',\n"
+ " )\n"
+ " ctx.register_approval_transport(\n"
+ " 'ledger_probe_transport', lambda request: 'deny',\n"
+ " )\n"
+ " ctx.on_unload(lambda: UNLOADED.append('ledger_probe'))\n"
)
(hermes_home / "config.yaml").write_text(
yaml.safe_dump({"plugins": {"enabled": ["ledger_probe"]}})
@@ -147,7 +156,12 @@ def test_load_force_reload_and_unload_remove_every_manager_registration(
"auxiliary_task",
"skill",
"tool_override_policy",
+ "system_prompt_section",
+ "approval_transport",
+ "on_unload",
}
+ assert "ledger-probe-section" in manager._system_prompt_sections
+ assert "ledger_probe_transport" in manager._approval_transports
manager.discover_and_load(force=True)
@@ -178,6 +192,16 @@ def test_load_force_reload_and_unload_remove_every_manager_registration(
assert "ledger-probe-command" not in manager._plugin_commands
assert "ledger-probe-cli" not in manager._cli_commands
assert "ledger_probe:ledger-probe" not in manager._plugin_skills
+ assert "ledger-probe-section" not in manager._system_prompt_sections
+ assert "ledger_probe_transport" not in manager._approval_transports
+ assert manager._plugins == {} or "ledger_probe" not in manager._plugins
+ reloaded_module_name = None
+ import sys as _sys
+ for _name, _mod in list(_sys.modules.items()):
+ if getattr(_mod, "UNLOADED", None) and "ledger_probe" in _mod.UNLOADED:
+ reloaded_module_name = _name
+ break
+ assert reloaded_module_name is not None, "on_unload callback never fired"
assert manager._aux_tasks == {}
assert manager._ownership_ledger == {}
assert registry.snapshot_plugin_override_policy(
@@ -1273,3 +1297,68 @@ def test_same_slug_profiles_allocate_distinct_modules_concurrently(
modules = [manager._plugins["profile_probe"].module.__name__ for manager in managers]
assert modules[0] != modules[1]
+
+
+def test_spawned_supervised_task_is_cancelled_on_unload():
+ """A plugin-spawned background task is tracked and cancelled on unload."""
+ import asyncio
+
+ from hermes_cli.plugins import PluginContext, PluginManager, PluginManifest
+
+ manager = PluginManager()
+ manifest = PluginManifest(
+ name="task_probe", version="0.1", description="", source="user",
+ )
+ ctx = PluginContext(manifest, manager)
+ cancelled = []
+
+ async def scenario():
+ async def forever():
+ try:
+ await asyncio.sleep(3600)
+ except asyncio.CancelledError:
+ cancelled.append(True)
+ raise
+
+ task = ctx.spawn_task(forever(), name="probe-task")
+ await asyncio.sleep(0)
+ kinds = {
+ registration.kind
+ for registration in manager._ownership_ledger["task_probe"]
+ }
+ assert "background_task" in kinds
+ assert manager.unload("task_probe") is True
+ with __import__("pytest").raises(asyncio.CancelledError):
+ await task
+ # Done-callback disposal removes the handle from the ledger.
+ await asyncio.sleep(0)
+ assert "task_probe" not in manager._ownership_ledger
+
+ asyncio.run(scenario())
+ assert cancelled == [True]
+
+
+def test_on_unload_exception_does_not_block_other_teardown():
+ """A raising on_unload callback is isolated; later cleanup still runs."""
+ from hermes_cli.plugins import PluginContext, PluginManager, PluginManifest
+
+ manager = PluginManager()
+ manifest = PluginManifest(
+ name="boom_probe", version="0.1", description="", source="user",
+ )
+ ctx = PluginContext(manifest, manager)
+ order = []
+
+ ctx.on_unload(lambda: order.append("first"))
+
+ def _boom():
+ order.append("boom")
+ raise RuntimeError("cleanup failed")
+
+ ctx.on_unload(_boom)
+ ctx.on_unload(lambda: order.append("last"))
+
+ assert manager.unload("boom_probe") is True
+ # Reverse acquisition order, exception isolated.
+ assert order == ["last", "boom", "first"]
+ assert "boom_probe" not in manager._ownership_ledger