Skip to content

The agent that grows with you

refactor(cli/plugins): repack multi-line statements to <=100 cols (AST-identical) across plugins*.py

Tekniumd7c64815a713
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.py
index 572a670b128..b7dd1af9721 100644
--- a/hermes_cli/plugins.py
+++ b/hermes_cli/plugins.py
@@ -404,12 +404,7 @@ class PluginContext:
return ValueError(f"Plugin '{self.manifest.name}' tried to register {what}.")
def _track(
- self,
- kind: str,
- key: str,
- release: Callable[[], None],
- *,
- persistent: bool = False,
+ self, kind: str, key: str, release: Callable[[], None], *, persistent: bool = False,
) -> PluginRegistration:
"""Record host-owned cleanup for a successful registration (see
:meth:`PluginManager._track_registration` for ``persistent``)."""
@@ -436,8 +431,7 @@ class PluginContext:
"""
mapping[key] = entry
return self._track_replacement(
- kind, key,
- slot=("manager_mapping", builtins.id(mapping), key),
+ kind, key, slot=("manager_mapping", builtins.id(mapping), key),
current=entry, previous=previous,
restore=lambda replacement: self._manager._restore_mapping(
mapping, key, entry, replacement
@@ -445,17 +439,9 @@ class PluginContext:
)
def _register_scoped_provider(
- self,
- provider: Any,
- *,
- kind: str,
- base_class: type,
- registry: Any,
- label: str,
- article: str = "a",
- normalize: Optional[Callable[[str], str]] = lambda n: n.strip(),
- register: Optional[Callable[..., Any]] = None,
- reject_message: Optional[str] = None,
+ self, provider: Any, *, kind: str, base_class: type, registry: Any, label: str,
+ article: str = "a", normalize: Optional[Callable[[str], str]] = lambda n: n.strip(),
+ register: Optional[Callable[..., Any]] = None, reject_message: Optional[str] = None,
) -> Optional[PluginRegistration]:
"""Shared body of the ``register_<category>_provider`` methods.
@@ -502,8 +488,7 @@ class PluginContext:
never a live agent or private registry."""
if self._subagent_lifecycle is None:
from agent.subagent_lifecycle import (
- SubagentLifecycleService,
- get_active_subagent_parent,
+ SubagentLifecycleService, get_active_subagent_parent,
)
self._subagent_lifecycle = SubagentLifecycleService(get_active_subagent_parent)
return self._subagent_lifecycle
@@ -551,11 +536,7 @@ class PluginContext:
"""Register a human approval transport, inactive until ``security.approval.transport:
<name>`` selects it. It receives a redacted ``ApprovalRequest`` and returns only a
correlated decision; policy and persistence stay host-owned. ``present_fn`` may be async."""
- self._manager.register_approval_transport(
- name,
- present_fn,
- plugin_id=self.plugin_id,
- )
+ self._manager.register_approval_transport(name, present_fn, plugin_id=self.plugin_id)
# 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()
@@ -567,17 +548,9 @@ class PluginContext:
@_serialized_replacement
def register_tool(
- self,
- name: str,
- toolset: str,
- schema: dict,
- handler: Callable,
- check_fn: Callable | None = None,
- requires_env: list | None = None,
- is_async: bool = False,
- description: str = "",
- emoji: str = "",
- override: bool = False,
+ self, name: str, toolset: str, schema: dict, handler: Callable,
+ check_fn: Callable | None = None, requires_env: list | None = None, is_async: bool = False,
+ description: str = "", emoji: str = "", override: bool = False,
) -> Optional[PluginRegistration]:
"""Register a tool in the global registry and track it as plugin-provided.
@@ -588,8 +561,7 @@ class PluginContext:
"""
if override and not self._tool_override_allowed(name):
raise PluginToolOverrideError(
- f"Plugin {self.manifest.name!r} cannot override built-in tool "
- f"{name!r}. Set "
+ f"Plugin {self.manifest.name!r} cannot override built-in tool " f"{name!r}. Set "
f"plugins.entries.{self.plugin_id}.allow_tool_override: true "
f"in config.yaml to allow this plugin to replace built-in tools."
)
@@ -602,28 +574,17 @@ class PluginContext:
if previous is None and effective is not None and not override:
logger.warning(
"Plugin %s tried to shadow global tool %s without override=True",
- self.manifest.name,
- name,
+ self.manifest.name, name,
)
return None
registry.register(
- name=name,
- toolset=toolset,
- schema=schema,
- handler=handler,
- check_fn=check_fn,
- requires_env=requires_env,
- is_async=is_async,
- description=description,
- emoji=emoji,
- override=override,
- scope=scope,
+ name=name, toolset=toolset, schema=schema, handler=handler, check_fn=check_fn,
+ requires_env=requires_env, is_async=is_async, description=description, emoji=emoji,
+ override=override, scope=scope,
)
registered = registry.snapshot_registration(name, scope=scope)
if (
- registered is not None
- and registered is not previous
- and registered.handler is handler
+ registered is not None and registered is not previous and registered.handler is handler
):
self._manager._plugin_tool_names.add(name)
handle = self._manager._track_scoped_registration(
@@ -650,10 +611,7 @@ class PluginContext:
return plugin_capability_granted(self.plugin_id, capability)
def call_mcp(
- self,
- server: str,
- tool: str,
- arguments: Optional[Dict[str, Any]] = None,
+ self, server: str, tool: str, arguments: Optional[Dict[str, Any]] = None,
timeout: float = 30,
) -> Dict[str, Any]:
"""Call ``tool`` on MCP ``server`` synchronously through the native client in
@@ -755,11 +713,7 @@ class PluginContext:
return plugin_capability_granted(self.plugin_id, "tools.override", config=cfg)
def inject_message(
- self,
- content: str,
- role: str = "user",
- *,
- session_key: str | None = None,
+ self, content: str, role: str = "user", *, session_key: str | None = None,
) -> bool:
"""Inject a message into a CLI or gateway conversation (new turn if idle, interrupt if
running).
@@ -784,8 +738,7 @@ class PluginContext:
if not self._gateway_injection_allowed():
logger.warning(
"inject_message: gateway injection denied for plugin %s; set "
- "plugins.entries.%s.allow_gateway_injection: true to allow it",
- self.plugin_id,
+ "plugins.entries.%s.allow_gateway_injection: true to allow it", self.plugin_id,
self.plugin_id,
)
return False
@@ -797,15 +750,12 @@ class PluginContext:
try:
return bool(
self._manager.inject_gateway_message(
- session_key=session_key,
- content=msg,
- plugin_id=self.plugin_id,
+ session_key=session_key, content=msg, plugin_id=self.plugin_id,
)
)
except Exception:
logger.warning(
- "inject_message: gateway scheduling failed for plugin %s",
- self.plugin_id,
+ "inject_message: gateway scheduling failed for plugin %s", self.plugin_id,
exc_info=True,
)
return False
@@ -819,36 +769,21 @@ class PluginContext:
return (
cfg_get(
- cfg,
- "plugins",
- "entries",
- self.plugin_id,
- "allow_gateway_injection",
- default=False,
- )
- is True
+ cfg, "plugins", "entries", self.plugin_id, "allow_gateway_injection", default=False,
+ ) is True
)
@_serialized_replacement
def register_cli_command(
- self,
- name: str,
- help: str,
- setup_fn: Callable,
- handler_fn: Callable | None = None,
+ self, name: str, help: str, setup_fn: Callable, handler_fn: Callable | None = None,
description: str = "",
) -> PluginRegistration:
"""Register a CLI subcommand (``hermes <name> ...``). *setup_fn* receives the argparse
subparser; *handler_fn* becomes ``set_defaults(func=...)``."""
previous = self._manager._cli_commands.get(name)
entry = {
- "name": name,
- "help": help,
- "description": description,
- "setup_fn": setup_fn,
- "handler_fn": handler_fn,
- "plugin": self.manifest.name,
- "plugin_key": self.plugin_id,
+ "name": name, "help": help, "description": description, "setup_fn": setup_fn,
+ "handler_fn": handler_fn, "plugin": self.manifest.name, "plugin_key": self.plugin_id,
}
handle = self._track_mapping_entry(
"cli_command", name, self._manager._cli_commands, entry, previous
@@ -858,11 +793,7 @@ class PluginContext:
@_serialized_replacement
def register_command(
- self,
- name: str,
- handler: Callable,
- description: str = "",
- args_hint: str = "",
+ self, name: str, handler: Callable, description: str = "", args_hint: str = "",
argument_mode: str | None = None,
) -> Optional[PluginRegistration]:
"""Register an in-session slash command (``/name``) for CLI and gateway sessions.
@@ -874,8 +805,7 @@ class PluginContext:
clean = name.lower().strip().lstrip("/").replace(" ", "-")
if not clean:
logger.warning(
- "Plugin '%s' tried to register a command with an empty name.",
- self.manifest.name,
+ "Plugin '%s' tried to register a command with an empty name.", self.manifest.name,
)
return
@@ -885,8 +815,7 @@ class PluginContext:
if resolve_command(clean) is not None:
logger.warning(
"Plugin '%s' tried to register command '/%s' which conflicts "
- "with a built-in command. Skipping.",
- self.manifest.name, clean,
+ "with a built-in command. Skipping.", self.manifest.name, clean,
)
return
except Exception:
@@ -898,11 +827,8 @@ class PluginContext:
"text" if hint else None
)
entry = {
- "handler": handler,
- "description": description or "Plugin command",
- "plugin": self.manifest.name,
- "plugin_key": self.plugin_id,
- "args_hint": hint,
+ "handler": handler, "description": description or "Plugin command",
+ "plugin": self.manifest.name, "plugin_key": self.plugin_id, "args_hint": hint,
"argument_mode": mode,
}
handle = self._track_mapping_entry(
@@ -957,8 +883,7 @@ class PluginContext:
defines ``@<prefix>:``. Built-in prefixes (diff, staged, file, folder, git, url) are
rejected."""
from agent.context_references import (
- ContextReferenceProvider as _CRP,
- register_context_reference_provider as _register,
+ ContextReferenceProvider as _CRP, register_context_reference_provider as _register,
)
if self._wrong_type(provider, _CRP, "context reference provider"):
@@ -967,13 +892,11 @@ class PluginContext:
_register(provider)
except ValueError as exc:
logger.warning(
- "Plugin '%s' context reference registration failed: %s",
- self.manifest.name, exc,
+ "Plugin '%s' context reference registration failed: %s", self.manifest.name, exc,
)
return
logger.info(
- "Plugin '%s' registered context reference: @%s:",
- self.manifest.name, provider.prefix,
+ "Plugin '%s' registered context reference: @%s:", self.manifest.name, provider.prefix,
)
def register_memory_provider(self, provider) -> None:
@@ -997,8 +920,7 @@ class PluginContext:
are ignored, never raised."""
from hermes_cli.dashboard_auth import DashboardAuthProvider
from hermes_cli.dashboard_auth.registry import (
- register_global_provider,
- unregister_global_provider,
+ register_global_provider, unregister_global_provider,
)
if self._wrong_type(provider, DashboardAuthProvider, "dashboard-auth provider"):
@@ -1011,16 +933,13 @@ class PluginContext:
register_global_provider(provider)
except (TypeError, ValueError) as e:
logger.warning(
- "Plugin '%s' failed to register dashboard-auth provider "
- "%r: %s",
+ "Plugin '%s' failed to register dashboard-auth provider %r: %s",
self.manifest.name, getattr(provider, "name", "?"), e,
)
return
handle = self._track(
- "dashboard_auth_provider",
- registry_name,
- lambda: unregister_global_provider(registry_name, provider),
- persistent=True,
+ "dashboard_auth_provider", registry_name,
+ lambda: unregister_global_provider(registry_name, provider), persistent=True,
)
logger.info(
"Plugin '%s' registered dashboard-auth provider: %s (%s)",
@@ -1030,15 +949,9 @@ class PluginContext:
@_serialized_replacement
def register_platform(
- self,
- name: str,
- label: str,
- adapter_factory: Callable,
- check_fn: Callable,
- validate_config: Callable | None = None,
- required_env: list | None = None,
- install_hint: str = "",
- **entry_kwargs: Any,
+ self, name: str, label: str, adapter_factory: Callable, check_fn: Callable,
+ validate_config: Callable | None = None, required_env: list | None = None,
+ install_hint: str = "", **entry_kwargs: Any,
) -> Optional[PluginRegistration]:
"""Register a gateway platform adapter (``adapter_factory(PlatformConfig) ->
BasePlatformAdapter``).
@@ -1053,15 +966,9 @@ class PluginContext:
entry_kwargs.setdefault("plugin_name", self.manifest.name)
entry = PlatformEntry(
- name=name,
- label=label,
- adapter_factory=adapter_factory,
- check_fn=check_fn,
- validate_config=validate_config,
- required_env=required_env or [],
- install_hint=install_hint,
- source="plugin",
- **entry_kwargs,
+ name=name, label=label, adapter_factory=adapter_factory, check_fn=check_fn,
+ validate_config=validate_config, required_env=required_env or [],
+ install_hint=install_hint, source="plugin", **entry_kwargs,
)
scope = self._manager.scope_key
previous = platform_registry.snapshot_registration(name, scope=scope)
@@ -1078,9 +985,7 @@ class PluginContext:
return handle
def register_slack_action_handler(
- self,
- action_id: Any,
- callback: Callable,
+ self, action_id: Any, callback: Callable,
) -> PluginRegistration:
"""Register a Slack Block Kit action handler, wired into ``slack_bolt.AsyncApp`` at connect.
@@ -1095,8 +1000,7 @@ class PluginContext:
entry = (action_id, callback, self.manifest.name)
self._manager._slack_action_handlers.append(entry)
handle = self._track(
- "slack_action_handler",
- repr(action_id),
+ "slack_action_handler", repr(action_id),
lambda: self._manager._remove_identity(
self._manager._slack_action_handlers, entry
),
@@ -1124,8 +1028,7 @@ class PluginContext:
(factory, self.manifest.name)
)
logger.debug(
- "Plugin %s registered %s handler factory: %s",
- self.manifest.name, key,
+ "Plugin %s registered %s handler factory: %s", self.manifest.name, key,
getattr(factory, "__name__", repr(factory)),
)
@@ -1138,11 +1041,7 @@ class PluginContext:
@_serialized_replacement
def register_auxiliary_task(
- self,
- key: str,
- *,
- display_name: str,
- description: str,
+ self, key: str, *, display_name: str, description: str,
defaults: Optional[Dict[str, Any]] = None,
) -> PluginRegistration:
"""Register an auxiliary LLM task with its own ``auxiliary.<key>`` config block (picker
@@ -1179,8 +1078,7 @@ class PluginContext:
if existing is not None and existing.get("plugin") != owner_id:
raise ValueError(
f"Plugin '{self.manifest.name}' cannot register auxiliary task "
- f"{key!r} — already registered by plugin "
- f"'{existing.get('plugin')}'"
+ f"{key!r} — already registered by plugin " f"'{existing.get('plugin')}'"
)
# Plugin owns the schema; routing fields are guaranteed present so consumers don't crash.
@@ -1191,21 +1089,14 @@ class PluginContext:
merged_defaults.update(defaults or {})
entry = {
- "key": key,
- "display_name": display_name,
- "description": description,
- "defaults": merged_defaults,
- "plugin": owner_id,
- "plugin_key": owner_id,
+ "key": key, "display_name": display_name, "description": description,
+ "defaults": merged_defaults, "plugin": owner_id, "plugin_key": owner_id,
}
handle = self._track_mapping_entry(
"auxiliary_task", key, self._manager._aux_tasks, entry, existing
)
logger.debug(
- "Plugin %s registered auxiliary task: %s (%s)",
- self.manifest.name,
- key,
- display_name,
+ "Plugin %s registered auxiliary task: %s (%s)", self.manifest.name, key, display_name,
)
return handle
@@ -1223,8 +1114,7 @@ class PluginContext:
count = _register(patterns, source=f"plugin:{self.manifest.name}")
except Exception as exc:
logger.warning(
- "Plugin '%s' redaction pattern registration failed: %s",
- self.manifest.name, exc,
+ "Plugin '%s' redaction pattern registration failed: %s", self.manifest.name, exc,
)
return 0
logger.debug("Plugin %s registered %d redaction pattern(s)", self.manifest.name, count)
@@ -1232,9 +1122,7 @@ class PluginContext:
def register_hook(self, hook_name: str, callback: Callable) -> PluginRegistration:
"""Register a lifecycle hook callback (unknown names warn but are still stored)."""
- return self._track_callback(
- "hook", hook_name, callback, self._manager._hooks, VALID_HOOKS
- )
+ return self._track_callback("hook", hook_name, callback, self._manager._hooks, VALID_HOOKS)
def _track_callback(
self, kind: str, key: str, callback: Callable, mapping: Dict[str, List[Callable]],
@@ -1254,12 +1142,8 @@ class PluginContext:
return handle
def register_system_prompt_section(
- self,
- id: str,
- content: Union[str, Callable[[Mapping[str, Any]], str]],
- *,
- position: str = "after_memory",
- max_chars: int = DEFAULT_SYSTEM_PROMPT_SECTION_MAX_CHARS,
+ self, id: str, content: Union[str, Callable[[Mapping[str, Any]], str]], *,
+ position: str = "after_memory", max_chars: int = DEFAULT_SYSTEM_PROMPT_SECTION_MAX_CHARS,
) -> PluginRegistration:
"""Register bounded context frozen into each new session prompt. Callables receive a
read-only session-info mapping; the rendered prompt is persisted by core verbatim."""
@@ -1276,8 +1160,7 @@ class PluginContext:
+ ", ".join(sorted(SYSTEM_PROMPT_SECTION_POSITIONS))
)
if (
- isinstance(max_chars, bool)
- or not isinstance(max_chars, int)
+ isinstance(max_chars, bool) or not isinstance(max_chars, int)
or not 0 < max_chars <= MAX_SYSTEM_PROMPT_SECTION_CHARS
):
raise ValueError(
@@ -1291,11 +1174,7 @@ class PluginContext:
f"plugin {existing.plugin!r}"
)
section = PluginSystemPromptSection(
- id=id,
- content=content,
- position=position,
- max_chars=max_chars,
- plugin=self.plugin_id,
+ id=id, content=content, position=position, max_chars=max_chars, plugin=self.plugin_id,
)
handle = self._track_mapping_entry(
"system_prompt_section", id, self._manager._system_prompt_sections, section, existing
@@ -1320,8 +1199,7 @@ class PluginContext:
"Plugin '%s' tried to emit namespaced/reserved event '%s' — "
"a plugin may only emit bare event names under its own '%s:' "
"namespace (the '%s:' prefix is reserved for core, and foreign "
- "namespaces are forbidden)",
- plugin_key, event, plugin_key, HERMES_EVENT_NAMESPACE,
+ "namespaces are forbidden)", plugin_key, event, plugin_key, HERMES_EVENT_NAMESPACE,
)
raise ValueError(
f"Plugin '{plugin_key}' may not emit '{event}': emit only the "
@@ -1338,8 +1216,7 @@ class PluginContext:
emitting is namespace-gated). Owner-tagged so unload removes zombie callbacks."""
if not event or not isinstance(event, str):
raise ValueError(
- f"Plugin '{self.manifest.name}' subscribe() requires a "
- f"non-empty event name"
+ f"Plugin '{self.manifest.name}' subscribe() requires a " f"non-empty event name"
)
plugin_key = self.plugin_id
self._manager._subscribe_event(plugin_key, event, callback)
@@ -1354,10 +1231,7 @@ class PluginContext:
@_serialized_replacement
def register_skill(
- self,
- name: str,
- path: Path,
- description: str = "",
+ self, name: str, path: Path, description: str = "",
frontmatter: Optional[Mapping[str, Any]] = None,
) -> PluginRegistration:
"""Register a read-only skill resolvable as ``'<plugin_name>:<name>'`` via ``skill_view()``.
@@ -1382,12 +1256,8 @@ class PluginContext:
raise ValueError(f"Plugin skill '{qualified}' is already registered")
previous = self._manager._plugin_skills.get(qualified)
entry = {
- "path": path,
- "plugin": namespace,
- "plugin_key": self.plugin_id,
- "bare_name": name,
- "description": description,
- "frontmatter": dict(frontmatter or {}),
+ "path": path, "plugin": namespace, "plugin_key": self.plugin_id, "bare_name": name,
+ "description": description, "frontmatter": dict(frontmatter or {}),
}
handle = self._track_mapping_entry(
"skill", qualified, self._manager._plugin_skills, entry, previous
@@ -1459,8 +1329,7 @@ def _make_scoped_provider_registrar(method_name, kind, registry_mod, base_ref, l
base_mod, base_attr = base_ref.split(":")
normalize = options.get("normalize", "strip")
normalize_fn = (
- None if normalize is None
- else (lambda n: n.strip().lower()) if normalize == "lower"
+ None if normalize is None else (lambda n: n.strip().lower()) if normalize == "lower"
else (lambda n: n.strip())
)
@@ -1469,13 +1338,8 @@ def _make_scoped_provider_registrar(method_name, kind, registry_mod, base_ref, l
base_class = getattr(importlib.import_module(base_mod), base_attr)
register_fn = options.get("register")
return self._register_scoped_provider(
- provider,
- kind=kind,
- base_class=base_class,
- registry=registry,
- label=label,
- article=options.get("article", "a"),
- normalize=normalize_fn,
+ provider, kind=kind, base_class=base_class, registry=registry, label=label,
+ article=options.get("article", "a"), normalize=normalize_fn,
register=getattr(registry, register_fn) if register_fn else None,
reject_message=options.get("reject_message"),
)
@@ -1513,15 +1377,13 @@ def _resolve_hook_callback_timeout() -> float:
if timeout < 0:
logger.warning(
- "plugins.hook_callback_timeout=%g is negative; using default %gs",
- timeout,
+ "plugins.hook_callback_timeout=%g is negative; using default %gs", timeout,
_HOOK_CALLBACK_TIMEOUT_SECS,
)
return _HOOK_CALLBACK_TIMEOUT_SECS
if timeout > _MAX_HOOK_CALLBACK_TIMEOUT_SECS:
logger.warning(
- "plugins.hook_callback_timeout=%g exceeds max %gs; clamping",
- timeout,
+ "plugins.hook_callback_timeout=%g exceeds max %gs; clamping", timeout,
_MAX_HOOK_CALLBACK_TIMEOUT_SECS,
)
return _MAX_HOOK_CALLBACK_TIMEOUT_SECS
@@ -1717,8 +1579,7 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):
if stale_relay_keys:
logger.warning(
"Removed Hermes plugin %s is still listed in plugins.enabled; "
- "remove it and configure native Relay plugins with %s",
- ", ".join(stale_relay_keys),
+ "remove it and configure native Relay plugins with %s", ", ".join(stale_relay_keys),
RELAY_PLUGINS_CONFIG_ENV,
)
# Later sources win on key collision (project > user > bundled); gate the winners, then
@@ -1736,8 +1597,7 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):
if manifests:
logger.info(
- "Plugin discovery complete: %d found, %d enabled",
- len(self._plugins),
+ "Plugin discovery complete: %d found, %d enabled", len(self._plugins),
sum(1 for p in self._plugins.values() if p.enabled),
)
@@ -1751,10 +1611,7 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):
self._plugins[manifest_key(manifest)] = loaded
def _gate_manifest(
- self,
- manifest: PluginManifest,
- disabled: Set[str],
- enabled: Optional[Set[str]],
+ self, manifest: PluginManifest, disabled: Set[str], enabled: Optional[Set[str]],
) -> bool:
"""Route one winning manifest per :func:`gate_manifest`: load now, defer, or record as
skipped. Returns True only for plugins that go through the dependency-ordered load pass."""
@@ -1772,11 +1629,7 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):
return False
def register_approval_transport(
- self,
- name: str,
- present_fn: Callable,
- *,
- plugin_id: str,
+ self, name: str, present_fn: Callable, *, plugin_id: str,
) -> None:
"""Register one plugin-owned approval transport for this profile."""
from hermes_cli.approval_transport import RegisteredApprovalTransport
@@ -1792,9 +1645,7 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):
owner = self._approval_transports[clean].plugin_id
raise ValueError(f"approval transport {clean!r} is already registered by {owner!r}")
self._approval_transports[clean] = RegisteredApprovalTransport(
- name=clean,
- present=present_fn,
- plugin_id=plugin_id,
+ name=clean, present=present_fn, plugin_id=plugin_id,
profile_home=str(get_hermes_home().resolve()),
)
logger.info("Plugin %s registered approval transport: %s", plugin_id, clean)
@@ -1843,12 +1694,8 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):
from hermes_cli.agent_plugins import _discover_mcp
if _discover_mcp(
- Path(manifest.path),
- get_hermes_home()
- / "plugin-data"
- / (manifest.skill_namespace or lookup_key),
- [],
- create_data=False,
+ Path(manifest.path), get_hermes_home() / "plugin-data"
+ / (manifest.skill_namespace or lookup_key), [], create_data=False,
):
return True
except (OSError, RuntimeError, ValueError):
@@ -1856,10 +1703,7 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):
return False
def _scan_directory(
- self,
- path: Path,
- source: str,
- skip_names: Optional[Set[str]] = None,
+ self, path: Path, source: str, skip_names: Optional[Set[str]] = None,
) -> List[PluginManifest]:
"""Read manifests under *path* (see :func:`scan_directory`)."""
return scan_directory(path, source, skip_names=skip_names)
@@ -1885,18 +1729,13 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):
for key, loaded in sorted(self._plugins.items()):
result.append(
{
- "name": loaded.manifest.name,
- "key": manifest_key(loaded.manifest),
- "kind": loaded.manifest.kind,
- "version": loaded.manifest.version,
- "description": loaded.manifest.description,
- "source": loaded.manifest.source,
- "enabled": loaded.enabled,
- "tools": len(loaded.tools_registered),
+ "name": loaded.manifest.name, "key": manifest_key(loaded.manifest),
+ "kind": loaded.manifest.kind, "version": loaded.manifest.version,
+ "description": loaded.manifest.description, "source": loaded.manifest.source,
+ "enabled": loaded.enabled, "tools": len(loaded.tools_registered),
"hooks": len(loaded.hooks_registered),
"middleware": len(loaded.middleware_registered),
- "commands": len(loaded.commands_registered),
- "error": loaded.error,
+ "commands": len(loaded.commands_registered), "error": loaded.error,
}
)
return result
@@ -1910,21 +1749,16 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):
"""Return sorted bare names of all skills registered by *plugin_name*."""
prefix = f"{plugin_name}:"
return sorted(
- e["bare_name"]
- for qn, e in self._plugin_skills.items()
- if qn.startswith(prefix)
+ e["bare_name"] for qn, e in self._plugin_skills.items() if qn.startswith(prefix)
)
def list_plugin_skill_metadata(self) -> List[Dict[str, Any]]:
"""Return progressive-disclosure metadata for registered plugin skills."""
return [
{
- "name": qualified,
- "description": str(entry.get("description", "")),
- "category": "plugin",
- "frontmatter": dict(entry.get("frontmatter", {})),
- }
- for qualified, entry in sorted(self._plugin_skills.items())
+ "name": qualified, "description": str(entry.get("description", "")),
+ "category": "plugin", "frontmatter": dict(entry.get("frontmatter", {})),
+ } for qualified, entry in sorted(self._plugin_skills.items())
]
def get_portable_mcp_servers(self) -> Dict[str, Dict[str, Any]]:
@@ -1985,8 +1819,7 @@ def get_plugin_manager() -> PluginManager:
# Tests/embedders monkeypatch ``_plugin_manager`` directly: adopt a single-slot manager the
# keyed cache doesn't know about at all.
if (
- _plugin_manager is not None
- and _plugin_manager not in _plugin_managers_by_home.values()
+ _plugin_manager is not None and _plugin_manager not in _plugin_managers_by_home.values()
):
_plugin_managers_by_home[current_home] = _plugin_manager
return _plugin_manager
@@ -2192,13 +2025,8 @@ def iter_hook_callbacks(hook_name: str) -> tuple[Callable, ...]:
def fire_pre_command_hook(
- *,
- surface: str,
- command: str,
- alias_used: str,
- args_raw: str,
- session_key: Optional[str] = None,
- platform: Optional[str] = None,
+ *, surface: str, command: str, alias_used: str, args_raw: str,
+ session_key: Optional[str] = None, platform: Optional[str] = None,
) -> None:
"""Fire the observer-only ``pre_command`` hook; never raises. Directive-shaped returns are
logged at debug so future block/rewrite adopters are discoverable."""
@@ -2207,23 +2035,15 @@ def fire_pre_command_hook(
if not manager.has_hook("pre_command"):
return
results = manager.invoke_hook(
- "pre_command",
- surface=surface,
- command=command,
- alias_used=alias_used,
- args_raw=args_raw,
- session_key=session_key,
- platform=platform,
+ "pre_command", surface=surface, command=command, alias_used=alias_used,
+ args_raw=args_raw, session_key=session_key, platform=platform,
)
for result in results:
- if isinstance(result, dict) and (
- "action" in result or "decision" in result
- ):
+ if isinstance(result, dict) and ("action" in result or "decision" in result):
logger.debug(
"pre_command is observer-only in v1: ignoring directive "
"%r for /%s (surface=%s). Block/rewrite will arrive with "
- "the command middleware variant (#64204/#64231).",
- result, command, surface,
+ "the command middleware variant (#64204/#64231).", result, command, surface,
)
except Exception as exc: # pragma: no cover - defensive
logger.debug("pre_command hook dispatch failed (non-fatal): %s", exc)
@@ -2269,15 +2089,9 @@ def _get_pre_tool_call_directive_details(
from hermes_cli.lifecycle import invoke_hook as invoke_lifecycle_hook
hook_results = invoke_lifecycle_hook(
- "pre_tool_call",
- tool_name=tool_name,
- args=args if isinstance(args, dict) else {},
- task_id=task_id,
- session_id=session_id,
- tool_call_id=tool_call_id,
- turn_id=turn_id,
- api_request_id=api_request_id,
- middleware_trace=list(middleware_trace or []),
+ "pre_tool_call", tool_name=tool_name, args=args if isinstance(args, dict) else {},
+ task_id=task_id, session_id=session_id, tool_call_id=tool_call_id, turn_id=turn_id,
+ api_request_id=api_request_id, middleware_trace=list(middleware_trace or []),
)
modified_args: Optional[Dict[str, Any]] = None
@@ -2306,8 +2120,7 @@ def _get_pre_tool_call_directive_details(
rule_key = result.get("rule_key") if action == "approve" else None
rule_key = (rule_key.strip() or None) if isinstance(rule_key, str) else None
return _PreToolCallDirective(
- action=action, message=message, rule_key=rule_key,
- modified_args=modified_args,
+ action=action, message=message, rule_key=rule_key, modified_args=modified_args,
)
return _PreToolCallDirective(modified_args=modified_args)
@@ -2339,11 +2152,7 @@ def resolve_pre_tool_block(
def _resolve_block_from_details(
- details: "_PreToolCallDirective",
- tool_name: str,
- *,
- turn_id: str = "",
- tool_call_id: str = "",
+ details: "_PreToolCallDirective", tool_name: str, *, turn_id: str = "", tool_call_id: str = "",
session_id: str = "",
) -> Optional[str]:
"""The ONE place for the fail-closed approval logic: ``block`` blocks with its message; an
@@ -2354,8 +2163,7 @@ def _resolve_block_from_details(
return None
try:
from tools.approval import (
- request_tool_approval,
- reset_current_observability_context,
+ request_tool_approval, reset_current_observability_context,
set_current_observability_context,
)
@@ -2396,27 +2204,15 @@ def _dispatch_pre_tool_call_hooks(
def get_pre_verify_continue_message(
- *,
- session_id: str = "",
- platform: str = "",
- model: str = "",
- coding: bool = False,
- attempt: int = 0,
- final_response: str = "",
- changed_paths: Optional[List[str]] = None,
+ *, session_id: str = "", platform: str = "", model: str = "", coding: bool = False,
+ attempt: int = 0, final_response: str = "", changed_paths: Optional[List[str]] = None,
) -> Optional[str]:
"""Check ``pre_verify`` hooks for ``{"action": "continue", "message"}`` (or Claude-Code Stop
``{"decision": "block", "reason"}``) to keep the turn going; first non-empty message wins, any
other return lets the turn finish. ``coding``/``attempt`` let hooks scope and self-throttle."""
hook_results = invoke_hook(
- "pre_verify",
- session_id=session_id,
- platform=platform,
- model=model,
- coding=coding,
- attempt=attempt,
- final_response=final_response,
- changed_paths=list(changed_paths or []),
+ "pre_verify", session_id=session_id, platform=platform, model=model, coding=coding,
+ attempt=attempt, final_response=final_response, changed_paths=list(changed_paths or []),
)
for result in hook_results:
@@ -2433,17 +2229,9 @@ def get_pre_verify_continue_message(
def get_plugin_error_classification(
- *,
- provider: str = "",
- model: str = "",
- status_code: Optional[int] = None,
- error_type: str = "",
- error_code: str = "",
- error_message: str = "",
- error_body: Optional[Dict[str, Any]] = None,
- error: Optional[BaseException] = None,
- approx_tokens: int = 0,
- context_length: int = 0,
+ *, provider: str = "", model: str = "", status_code: Optional[int] = None, error_type: str = "",
+ error_code: str = "", error_message: str = "", error_body: Optional[Dict[str, Any]] = None,
+ error: Optional[BaseException] = None, approx_tokens: int = 0, context_length: int = 0,
num_messages: int = 0,
) -> Optional[Dict[str, Any]]:
"""Consult ``transform_api_error_classification`` hooks BEFORE the built-in classifier.
@@ -2456,17 +2244,10 @@ def get_plugin_error_classification(
from agent.error_classifier import FailoverReason
hook_results = invoke_hook(
- "transform_api_error_classification",
- provider=provider,
- model=model,
- status_code=status_code,
- error_type=error_type,
- error_code=error_code,
- error_message=error_message,
- error_body=error_body if isinstance(error_body, dict) else {},
- error=error,
- approx_tokens=approx_tokens,
- context_length=context_length,
+ "transform_api_error_classification", provider=provider, model=model,
+ status_code=status_code, error_type=error_type, error_code=error_code,
+ error_message=error_message, error_body=error_body if isinstance(error_body, dict) else {},
+ error=error, approx_tokens=approx_tokens, context_length=context_length,
num_messages=num_messages,
)
@@ -2489,12 +2270,7 @@ def get_plugin_error_classification(
continue
out: Dict[str, Any] = {"reason": reason}
- for key in (
- "retryable",
- "should_compress",
- "should_rotate_credential",
- "should_fallback",
- ):
+ for key in ("retryable", "should_compress", "should_rotate_credential", "should_fallback"):
if key in result:
out[key] = bool(result[key])
message = result.get("message")
@@ -2509,8 +2285,7 @@ def get_plugin_error_classification(
logger.warning(
"transform_api_error_classification: skipped %d valid "
"classification(s) after the first result in registration order "
- "won (run-all-then-pick-first)",
- skipped_valid,
+ "won (run-all-then-pick-first)", skipped_valid,
)
return winner
diff --git a/hermes_cli/plugins_discovery.py b/hermes_cli/plugins_discovery.py
index 01eb0ac93d2..7e1ea680b6a 100644
--- a/hermes_cli/plugins_discovery.py
+++ b/hermes_cli/plugins_discovery.py
@@ -17,12 +17,8 @@ from hermes_cli.config import cfg_get
from hermes_cli.plugin_capabilities import VALID_CAPABILITY_IDS
from hermes_cli.plugin_capabilities import parse_declared_capabilities as _parse_declared_capabilities
from hermes_cli.plugins_manifest import (
- PluginManifest,
- _detect_kind_from_source,
- manifest_key,
- _resolve_module_source,
- parse_manifest_file,
- portable_plugin_manifest,
+ PluginManifest, _detect_kind_from_source, manifest_key, _resolve_module_source,
+ parse_manifest_file, portable_plugin_manifest,
)
from hermes_cli.relay_plugin_cutover import LEGACY_RELAY_PLUGIN_KEYS, RELAY_PLUGINS_CONFIG_ENV
@@ -67,24 +63,17 @@ def discover_entrypoint_manifests() -> List["PluginManifest"]:
for capability in VALID_CAPABILITY_IDS:
declaration_name = f"{ep.name}.{capability}"
if any(
- declaration.name == declaration_name
- and declaration.value == ep.value
+ declaration.name == declaration_name and declaration.value == ep.value
for declaration in capability_eps
):
capabilities.append(capability)
dist = getattr(ep, "dist", None)
metadata = getattr(dist, "metadata", None)
manifest = PluginManifest(
- name=ep.name,
- version=str(getattr(dist, "version", "") or ""),
+ name=ep.name, version=str(getattr(dist, "version", "") or ""),
description=(
- str(metadata.get("Summary", "") or "")
- if metadata is not None
- else ""
- ),
- source="entrypoint",
- path=ep.value,
- key=ep.name,
+ str(metadata.get("Summary", "") or "") if metadata is not None else ""
+ ), source="entrypoint", path=ep.value, key=ep.name,
capabilities=_parse_declared_capabilities(
capabilities, ep.name
),
@@ -134,11 +123,7 @@ def _get_enabled_plugins() -> Optional[set]:
def scan_directory(
- path: Path,
- source: str,
- *,
- skip_names: Optional[Set[str]] = None,
- prefix: str = "",
+ path: Path, source: str, *, skip_names: Optional[Set[str]] = None, prefix: str = "",
depth: int = 0,
) -> List[PluginManifest]:
"""Read manifests under *path*: flat ``<root>/<name>/plugin.yaml`` (key ``name``) or category
diff --git a/hermes_cli/plugins_dispatch.py b/hermes_cli/plugins_dispatch.py
index 81bcd13dc95..93b4c1b2d31 100644
--- a/hermes_cli/plugins_dispatch.py
+++ b/hermes_cli/plugins_dispatch.py
@@ -29,18 +29,9 @@ logger = logging.getLogger("hermes_cli.plugins")
# subagent_start (observer); pre_gateway_dispatch (policy gate — neither fail mode is acceptable);
# pre/post_approval_* (approval UX has its own timeout); kanban_* (own heartbeat/stale reclaim).
_HOOK_TIMEOUT_BOUNDED_HOOKS: Set[str] = {
- "post_tool_call",
- "transform_terminal_output",
- "transform_tool_result",
- "transform_llm_output",
- "pre_llm_call",
- "post_llm_call",
- "pre_api_request",
- "post_api_request",
- "api_request_error",
- "pre_verify",
- "on_session_start",
- "on_session_end",
+ "post_tool_call", "transform_terminal_output", "transform_tool_result", "transform_llm_output",
+ "pre_llm_call", "post_llm_call", "pre_api_request", "post_api_request", "api_request_error",
+ "pre_verify", "on_session_start", "on_session_end",
}
@@ -98,8 +89,7 @@ def format_system_prompt_section(section_id: str, content: str) -> str:
"""Render an auditable, length-framed block recoverable from the full prompt."""
return (
f"{_SYSTEM_PROMPT_SECTION_HEADING_PREFIX}{section_id}\n"
- f"<!-- hermes-plugin-section-chars:{len(content)} -->\n\n"
- f"{content}"
+ f"<!-- hermes-plugin-section-chars:{len(content)} -->\n\n" f"{content}"
)
@@ -182,8 +172,7 @@ def _hook_uses_callback_timeout(hook_name: str, timeout: float) -> bool:
if timeout <= 0 or hook_name in _HOOK_CALLER_THREAD_HOOKS:
return False
return (
- hook_name in _HOOK_TIMEOUT_BOUNDED_HOOKS
- or hook_name in _HOOK_TIMEOUT_FAIL_CLOSED_HOOKS
+ hook_name in _HOOK_TIMEOUT_BOUNDED_HOOKS or hook_name in _HOOK_TIMEOUT_FAIL_CLOSED_HOOKS
)
@@ -202,19 +191,15 @@ class PluginDispatchMixin:
return callback(**payload) # no introspectable signature: historical behavior
if any(
- parameter.kind == inspect.Parameter.VAR_KEYWORD
- for parameter in parameters.values()
+ parameter.kind == inspect.Parameter.VAR_KEYWORD for parameter in parameters.values()
):
return callback(**payload)
accepted_payload = {
- name: value
- for name, value in payload.items()
- if name in parameters
+ name: value for name, value in payload.items() if name in parameters
and parameters[name].kind
in {
- inspect.Parameter.POSITIONAL_OR_KEYWORD,
- inspect.Parameter.KEYWORD_ONLY,
+ inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY,
}
}
return callback(**accepted_payload)
@@ -255,10 +240,8 @@ class PluginDispatchMixin:
results.append(ret)
except Exception as exc:
logger.warning(
- "Hook '%s' callback %s raised: %s",
- hook_name,
- getattr(cb, "__name__", repr(cb)),
- exc,
+ "Hook '%s' callback %s raised: %s", hook_name,
+ getattr(cb, "__name__", repr(cb)), exc,
)
return results
@@ -278,9 +261,7 @@ class PluginDispatchMixin:
if (suppressed_until is not None and suppressed_until > now) or running:
logger.warning(
"Hook '%s' callback %s skipped after previous "
- "timeout or while still running",
- hook_name,
- callback_name,
+ "timeout or while still running", hook_name, callback_name,
)
return _HOOK_SKIPPED
if suppressed_until is not None:
@@ -304,9 +285,7 @@ class PluginDispatchMixin:
done.set()
thread = threading.Thread(
- target=_runner,
- name=f"hermes-hook-{callback_name}"[:40],
- daemon=True,
+ target=_runner, name=f"hermes-hook-{callback_name}"[:40], daemon=True,
)
thread.start()
if not done.wait(timeout=timeout): # do not join — that would reintroduce the hang
@@ -315,9 +294,7 @@ class PluginDispatchMixin:
time.monotonic() + self._hook_timeout_suppression_seconds
)
logger.warning(
- "Hook '%s' callback %s timed out after %gs — skipping",
- hook_name,
- callback_name,
+ "Hook '%s' callback %s timed out after %gs — skipping", hook_name, callback_name,
timeout,
)
return _HOOK_SKIPPED
@@ -354,9 +331,7 @@ class PluginDispatchMixin:
return
dispatch_queue = self._event_queue
worker = threading.Thread(
- target=self._event_worker_loop,
- args=(dispatch_queue,),
- name="hermes-plugin-events",
+ target=self._event_worker_loop, args=(dispatch_queue,), name="hermes-plugin-events",
daemon=True,
)
self._event_worker = worker
@@ -409,10 +384,8 @@ class PluginDispatchMixin:
resolve_plugin_command_result(result)
except Exception as exc:
logger.warning(
- "Event '%s' subscriber %s raised: %s",
- item.event,
- getattr(callback, "__name__", repr(callback)),
- exc,
+ "Event '%s' subscriber %s raised: %s", item.event,
+ getattr(callback, "__name__", repr(callback)), exc,
)
finally:
self._emit_depth.value = previous_depth
@@ -422,8 +395,7 @@ class PluginDispatchMixin:
with self._event_idle:
generation = self._event_generation
return self._event_idle.wait_for(
- lambda: self._event_pending_by_generation.get(generation, 0) == 0,
- timeout=timeout,
+ lambda: self._event_pending_by_generation.get(generation, 0) == 0, timeout=timeout,
)
def _dispatch_event(self, event: str, payload: Dict[str, Any]) -> int:
@@ -433,8 +405,7 @@ class PluginDispatchMixin:
if depth >= _EVENT_EMIT_DEPTH_CAP:
logger.warning(
"Event bus recursion cap (%d) exceeded while dispatching '%s' "
- "— dropping this emit to prevent an infinite loop",
- _EVENT_EMIT_DEPTH_CAP, event,
+ "— dropping this emit to prevent an infinite loop", _EVENT_EMIT_DEPTH_CAP, event,
)
return 0
@@ -447,16 +418,11 @@ class PluginDispatchMixin:
if pending >= _EVENT_PENDING_CAP:
logger.warning(
"Event bus pending budget (%d) exhausted while dispatching "
- "'%s' — dropping this emit",
- _EVENT_PENDING_CAP,
- event,
+ "'%s' — dropping this emit", _EVENT_PENDING_CAP, event,
)
return 0
item = _QueuedPluginEvent(
- event=event,
- payload=dict(payload),
- subscriptions=subscriptions,
- depth=depth + 1,
+ event=event, payload=dict(payload), subscriptions=subscriptions, depth=depth + 1,
generation=generation,
)
try:
@@ -464,9 +430,7 @@ class PluginDispatchMixin:
except queue.Full:
logger.warning(
"Event bus pending budget (%d) exhausted while dispatching "
- "'%s' — dropping this emit",
- _EVENT_PENDING_CAP,
- event,
+ "'%s' — dropping this emit", _EVENT_PENDING_CAP, event,
)
return 0
self._event_pending_by_generation[generation] = pending + 1
@@ -493,9 +457,7 @@ class PluginDispatchMixin:
if len(rendered) >= MAX_SYSTEM_PROMPT_SECTIONS:
logger.warning(
"Plugin system prompt section %s exceeded the section-count "
- "budget (%d) and was skipped",
- section.id,
- MAX_SYSTEM_PROMPT_SECTIONS,
+ "budget (%d) and was skipped", section.id, MAX_SYSTEM_PROMPT_SECTIONS,
)
continue
text = self._render_prompt_section_text(section, frozen_info)
@@ -507,27 +469,19 @@ class PluginDispatchMixin:
if total_chars + rendered_chars > MAX_SYSTEM_PROMPT_SECTIONS_TOTAL_CHARS:
logger.warning(
"Plugin system prompt section %s (%s) exceeded the aggregate "
- "session budget (%d chars) and was skipped",
- section.id,
- section.plugin,
+ "session budget (%d chars) and was skipped", section.id, section.plugin,
MAX_SYSTEM_PROMPT_SECTIONS_TOTAL_CHARS,
)
continue
rendered.append(
RenderedPluginSystemPromptSection(
- id=section.id,
- content=text,
- position=section.position,
- plugin=section.plugin,
+ id=section.id, content=text, position=section.position, plugin=section.plugin,
)
)
total_chars += rendered_chars
logger.info(
- "Session plugin prompt section: id=%s plugin=%s position=%s chars=%d",
- section.id,
- section.plugin,
- section.position,
- len(text),
+ "Session plugin prompt section: id=%s plugin=%s position=%s chars=%d", section.id,
+ section.plugin, section.position, len(text),
)
return rendered
@@ -538,8 +492,7 @@ class PluginDispatchMixin:
"""Evaluate one section; return its stripped text or None (with a warning) when skipped."""
def _skip(detail: str, *args: Any) -> None:
logger.warning(
- "Plugin system prompt section %s (%s) " + detail,
- section.id, section.plugin, *args,
+ "Plugin system prompt section %s (%s) " + detail, section.id, section.plugin, *args,
)
try:
@@ -576,9 +529,7 @@ class PluginDispatchMixin:
results.append(ret)
except Exception as exc:
logger.warning(
- "Middleware '%s' callback %s raised: %s",
- kind,
- getattr(cb, "__name__", repr(cb)),
- exc,
+ "Middleware '%s' callback %s raised: %s", kind,
+ getattr(cb, "__name__", repr(cb)), exc,
)
return results
diff --git a/hermes_cli/plugins_ledger.py b/hermes_cli/plugins_ledger.py
index 26750f56777..b4fb4bd3b8c 100644
--- a/hermes_cli/plugins_ledger.py
+++ b/hermes_cli/plugins_ledger.py
@@ -56,12 +56,7 @@ class PluginRegistration:
class PluginLedgerMixin:
def _track_registration(
- self,
- manifest: PluginManifest,
- kind: str,
- key: str,
- release: Callable[[], None],
- *,
+ self, manifest: PluginManifest, kind: str, key: str, release: Callable[[], None], *,
persistent: bool = False,
) -> PluginRegistration:
"""Record one registration under its canonical plugin key.
@@ -72,11 +67,7 @@ class PluginLedgerMixin:
"""
plugin_key = manifest_key(manifest)
registration = PluginRegistration(
- kind=kind,
- key=key,
- release=release,
- plugin_key=plugin_key,
- persistent=persistent,
+ kind=kind, key=key, release=release, plugin_key=plugin_key, persistent=persistent,
)
registration._on_dispose = lambda disposed: self._forget_registrations([disposed])
self._ownership_ledger.setdefault(plugin_key, []).append(registration)
@@ -85,15 +76,8 @@ class PluginLedgerMixin:
return registration
def _track_scoped_registration(
- self,
- manifest: PluginManifest,
- kind: str,
- name: str,
- registry: Any,
- current: Any,
- previous: Any,
- *,
- finalize: Optional[Callable[[], None]] = None,
+ self, manifest: PluginManifest, kind: str, name: str, registry: Any, current: Any,
+ previous: Any, *, finalize: Optional[Callable[[], None]] = None,
) -> PluginRegistration:
"""Lease one ``(kind, scope, name)`` slot of a scope-keyed process-global registry.
@@ -102,13 +86,10 @@ class PluginLedgerMixin:
"""
scope = self.scope_key
lease = replacement_coordinator.acquire(
- (kind, scope, name),
- current=current,
- previous=previous,
+ (kind, scope, name), current=current, previous=previous,
restore=lambda replacement: registry.restore_registration(
name, current, replacement, scope=scope
- ),
- finalize=finalize,
+ ), finalize=finalize,
)
return self._track_registration(manifest, kind, name, lease.dispose)
@@ -121,23 +102,17 @@ class PluginLedgerMixin:
parked = self._persistent_carryover
self._persistent_carryover = []
current = {
- (registration.kind, registration.key)
- for owned in self._ownership_ledger.values()
- for registration in owned
- if registration.persistent and registration.active
+ (registration.kind, registration.key) for owned in self._ownership_ledger.values()
+ for registration in owned if registration.persistent and registration.active
}
stale = [
- registration
- for registration in parked
- if registration.active
+ registration for registration in parked if registration.active
and (registration.kind, registration.key) not in current
]
for registration in stale:
logger.info(
"Evicting persistent registration %s/%s: plugin '%s' no "
- "longer supplies it after re-discovery",
- registration.kind,
- registration.key,
+ "longer supplies it after re-discovery", registration.kind, registration.key,
registration.plugin_key,
)
self._dispose_registrations(stale)
@@ -152,10 +127,7 @@ class PluginLedgerMixin:
return False
def _remove_callback(
- self,
- mapping: Dict[str, List[Callable]],
- key: str,
- callback: Callable,
+ self, mapping: Dict[str, List[Callable]], key: str, callback: Callable,
) -> None:
callbacks = mapping.get(key)
if callbacks is None:
@@ -165,11 +137,7 @@ class PluginLedgerMixin:
mapping.pop(key, None)
def _restore_mapping(
- self,
- mapping: Dict[str, Any],
- key: str,
- current: Any,
- previous: Optional[Any],
+ self, mapping: Dict[str, Any], key: str, current: Any, previous: Optional[Any],
) -> bool:
"""Restore a manager-local mapping only when *current* is still present."""
if mapping.get(key) is not current:
@@ -190,9 +158,7 @@ class PluginLedgerMixin:
def _remove_name_if_unowned(self, kind: str, names: Set[str], name: str) -> None:
"""Drop *name* from the manager-local name set once no active ledger entry owns it."""
if not any(
- registration.active
- and registration.kind == kind
- and registration.key == name
+ registration.active and registration.kind == kind and registration.key == name
for registration in self._registration_order
):
names.discard(name)
@@ -208,15 +174,12 @@ class PluginLedgerMixin:
return
registration_ids = {id(registration) for registration in registrations}
self._registration_order = [
- registration
- for registration in self._registration_order
+ registration for registration in self._registration_order
if id(registration) not in registration_ids
]
for plugin_key, owned in list(self._ownership_ledger.items()):
remaining = [
- registration
- for registration in owned
- if id(registration) not in registration_ids
+ registration for registration in owned if id(registration) not in registration_ids
]
if remaining:
self._ownership_ledger[plugin_key] = remaining
@@ -232,11 +195,8 @@ class PluginLedgerMixin:
registration.dispose()
except Exception as exc: # pragma: no cover - defensive cleanup
logger.warning(
- "Failed to unload plugin registration %s/%s: %s",
- registration.plugin_key,
- registration.key,
- exc,
- exc_info=_PLUGINS_DEBUG,
+ "Failed to unload plugin registration %s/%s: %s", registration.plugin_key,
+ registration.key, exc, exc_info=_PLUGINS_DEBUG,
)
@staticmethod
@@ -268,16 +228,14 @@ class PluginLedgerMixin:
else:
target_keys = self._unload_target_keys(self._resolve_plugin_key(plugin))
registrations = [
- registration
- for registration in self._registration_order
+ registration for registration in self._registration_order
if registration.plugin_key in target_keys
]
# Persistent registrations are absent from _registration_order (unload-all keeps them),
# but a *targeted* unload is the disable/uninstall path: a disabled auth plugin's
# provider must NOT stay live process-wide.
registrations.extend(
- registration
- for key in target_keys
+ registration for key in target_keys
for registration in self._ownership_ledger.get(key, [])
if registration.persistent and registration.active
)
@@ -312,14 +270,10 @@ class PluginLedgerMixin:
# Ledger-owned tool names are excluded: their handles already restored the previous entry,
# and blanket deregistration would remove what the ledger just restored.
ledger_tool_names = {
- registration.key
- for registration in registrations
- if registration.kind == "tool"
+ registration.key for registration in registrations if registration.kind == "tool"
}
preledger_tools = tuple(
- name
- for name in self._plugin_tool_names
- if name not in ledger_tool_names
+ name for name in self._plugin_tool_names if name not in ledger_tool_names
)
if preledger_tools:
try:
@@ -336,11 +290,8 @@ class PluginLedgerMixin:
# carry them over so force re-discovery can evict the ones whose plugin does not come back.
carryover_ids = {id(registration) for registration in self._persistent_carryover}
self._persistent_carryover.extend(
- registration
- for owned in self._ownership_ledger.values()
- for registration in owned
- if registration.persistent
- and registration.active
+ registration for owned in self._ownership_ledger.values() for registration in owned
+ if registration.persistent and registration.active
and id(registration) not in carryover_ids
)
for container in (
diff --git a/hermes_cli/plugins_loader.py b/hermes_cli/plugins_loader.py
index 21065b4876d..8671ab9d211 100644
--- a/hermes_cli/plugins_loader.py
+++ b/hermes_cli/plugins_loader.py
@@ -103,9 +103,7 @@ class PluginLoaderMixin:
# predecessor and this loader must publish nothing; if loading won, unload waits
# and disposes the completed set.
with self._discovery_lock, _plugin_home_scope(self.home_path):
- if platform_registry.is_deferred_load_cancelled(
- platform_name, scope=scope
- ):
+ if platform_registry.is_deferred_load_cancelled(platform_name, scope=scope):
return
self._load_plugin_scoped(_manifest)
@@ -119,15 +117,12 @@ class PluginLoaderMixin:
finalize=lambda: self._remove_platform_name_if_unowned(platform_name),
)
logger.debug(
- "Registered deferred platform loader: %s (plugin=%s)",
- platform_name,
- lookup_key,
+ "Registered deferred platform loader: %s (plugin=%s)", platform_name, lookup_key,
)
except Exception:
# Fall back to eager loading so the platform is never silently lost.
logger.debug(
- "Deferred platform registration failed for '%s'; eager-loading",
- lookup_key,
+ "Deferred platform registration failed for '%s'; eager-loading", lookup_key,
exc_info=True,
)
self._load_plugin(manifest)
@@ -156,8 +151,7 @@ class PluginLoaderMixin:
# Declared but undeliverable — staying quiet reproduces the very symptom this fixes.
logger.warning(
"Plugin '%s' declares provides_tools %s but has no tools.py; "
- "those tools will not be available in CLI/TUI sessions.",
- lookup_key,
+ "those tools will not be available in CLI/TUI sessions.", lookup_key,
list(manifest.provides_tools),
)
return
@@ -176,9 +170,7 @@ class PluginLoaderMixin:
logger.warning(
"Plugin '%s' declares provides_tools %s but its tools.py "
"has no register_tools(ctx); those tools will not be "
- "available in CLI/TUI sessions.",
- lookup_key,
- list(manifest.provides_tools),
+ "available in CLI/TUI sessions.", lookup_key, list(manifest.provides_tools),
)
return
@@ -188,10 +180,8 @@ class PluginLoaderMixin:
loaded.tools_registered = registered
self._predeclared_tools[lookup_key] = registered
logger.debug(
- "Deferred platform '%s': pre-registered %d client tool(s) %s",
- lookup_key,
- len(registered),
- registered,
+ "Deferred platform '%s': pre-registered %d client tool(s) %s", lookup_key,
+ len(registered), registered,
)
except Exception as exc:
# Tools registered before the raise are live: credit them or `hermes plugins list`
@@ -211,13 +201,9 @@ class PluginLoaderMixin:
else:
scope = f"after registering {len(partial)} of {declared} declared tool(s)"
logger.warning(
- "Plugin '%s': client-tool pre-registration failed %s (%s).%s",
- lookup_key,
- scope,
- exc,
- "" if len(partial) >= declared else
- " The remainder will be missing from CLI/TUI sessions.",
- exc_info=_PLUGINS_DEBUG,
+ "Plugin '%s': client-tool pre-registration failed %s (%s).%s", lookup_key, scope,
+ exc, "" if len(partial) >= declared else
+ " The remainder will be missing from CLI/TUI sessions.", exc_info=_PLUGINS_DEBUG,
)
def _warn_python_dependencies(self, manifest: PluginManifest) -> None:
@@ -243,8 +229,7 @@ class PluginLoaderMixin:
"Plugin %s declares Python dependencies that are not "
"installed: %s. Hermes does not install plugin dependencies "
"automatically; install them yourself, e.g.: pip install %s",
- key, ", ".join(missing),
- " ".join(f"'{m}'" for m in missing),
+ key, ", ".join(missing), " ".join(f"'{m}'" for m in missing),
)
else:
logger.debug("Plugin %s python_dependencies satisfied: %s", key, ", ".join(deps))
@@ -268,9 +253,7 @@ class PluginLoaderMixin:
settings = raw if isinstance(raw, Mapping) else {}
except Exception:
settings = {}
- for warning in validate_config_schema(
- plugin_id, manifest.config_schema, settings
- ):
+ for warning in validate_config_schema(plugin_id, manifest.config_schema, settings):
logger.warning("Plugin %s config: %s", plugin_id, warning)
def _load_plugin(self, manifest: PluginManifest) -> None:
@@ -318,8 +301,7 @@ class PluginLoaderMixin:
except Exception as exc:
owned = [
- registration
- for registration in self._registration_order
+ registration for registration in self._registration_order
if registration.plugin_key == plugin_key
]
self._dispose_registrations(owned)
@@ -329,8 +311,7 @@ class PluginLoaderMixin:
# reachable from later event dispatch.
self._remove_plugin_subscriptions(plugin_key)
logger.warning(
- "Failed to load plugin '%s': %s",
- manifest.name, exc, exc_info=_PLUGINS_DEBUG,
+ "Failed to load plugin '%s': %s", manifest.name, exc, exc_info=_PLUGINS_DEBUG,
)
# The failure path swept this plugin's whole ledger (not just the registration_start slice),
# so discovery-time pre-registrations are gone too.
@@ -349,19 +330,14 @@ class PluginLoaderMixin:
module_name, scope=self.scope_key
)
current_policy = _registry.register_plugin_override_policy(
- module_name,
- PluginContext(manifest, self)._tool_override_allowed(""),
+ module_name, PluginContext(manifest, self)._tool_override_allowed(""),
scope=self.scope_key,
)
policy_lease = replacement_coordinator.acquire(
- ("tool_override_policy", self.scope_key, module_name),
- current=current_policy,
+ ("tool_override_policy", self.scope_key, module_name), current=current_policy,
previous=previous_policy,
restore=lambda replacement: _registry.restore_plugin_override_policy(
- module_name,
- current_policy,
- replacement,
- scope=self.scope_key,
+ module_name, current_policy, replacement, scope=self.scope_key,
),
)
self._track_registration(
@@ -373,8 +349,7 @@ class PluginLoaderMixin:
) -> None:
"""Fill ``loaded.*_registered`` from the ledger slice this plugin's register() produced."""
registrations = [
- registration
- for registration in self._registration_order[registration_start:]
+ registration for registration in self._registration_order[registration_start:]
if registration.plugin_key == plugin_key and registration.active
]
@@ -384,8 +359,7 @@ class PluginLoaderMixin:
# Discovery-time tools predate registration_start; credit them back or `hermes plugins
# list` under-reports once the deferred adapter materializes.
_predeclared = [
- t for t in self._predeclared_tools.pop(plugin_key, [])
- if t in self._plugin_tool_names
+ t for t in self._predeclared_tools.pop(plugin_key, []) if t in self._plugin_tool_names
]
loaded.tools_registered = _predeclared + [
key for key in _keys("tool") if key not in _predeclared
@@ -395,10 +369,8 @@ class PluginLoaderMixin:
loaded.commands_registered = _keys("command")
logger.debug(
" registered: %d tool(s), %d hook(s), %d middleware, %d slash command(s), %d CLI command(s)",
- len(loaded.tools_registered),
- len(loaded.hooks_registered),
- len(loaded.middleware_registered),
- len(loaded.commands_registered),
+ len(loaded.tools_registered), len(loaded.hooks_registered),
+ len(loaded.middleware_registered), len(loaded.commands_registered),
sum(1 for c in self._cli_commands if c in _keys("cli_command")),
)
@@ -411,39 +383,27 @@ class PluginLoaderMixin:
from hermes_cli.agent_plugins import load_agent_plugin
package = load_agent_plugin(
- Path(manifest.path),
- get_hermes_home() / "plugin-data" / manifest.skill_namespace,
+ Path(manifest.path), get_hermes_home() / "plugin-data" / manifest.skill_namespace,
)
ctx = PluginContext(manifest, self)
for diagnostic in package.diagnostics:
logger.warning(
- "Agent Plugin '%s' [%s]: %s",
- lookup_key,
- diagnostic.scope,
- diagnostic.message,
+ "Agent Plugin '%s' [%s]: %s", lookup_key, diagnostic.scope, diagnostic.message,
)
for skill in package.skills:
try:
ctx.register_skill(
- skill.name,
- skill.skill_md,
- skill.description,
- skill.frontmatter,
+ skill.name, skill.skill_md, skill.description, skill.frontmatter,
)
except Exception as exc:
logger.warning(
- "Agent Plugin '%s' skill '%s' skipped: %s",
- lookup_key,
- skill.name,
- exc,
+ "Agent Plugin '%s' skill '%s' skipped: %s", lookup_key, skill.name, exc,
)
for server_name, config in package.mcp_servers.items():
internal_name = f"{manifest.skill_namespace}__{server_name}"
if internal_name in self._portable_mcp_servers:
logger.warning(
- "Agent Plugin '%s' MCP server collision: %s",
- lookup_key,
- internal_name,
+ "Agent Plugin '%s' MCP server collision: %s", lookup_key, internal_name,
)
continue
self._portable_mcp_servers[internal_name] = dict(config)
@@ -477,10 +437,7 @@ class PluginLoaderMixin:
return self._directory_module_name(manifest)
def _load_directory_module(
- self,
- manifest: PluginManifest,
- *,
- module_name: Optional[str] = None,
+ self, manifest: PluginManifest, *, module_name: Optional[str] = None,
) -> types.ModuleType:
"""Import a directory plugin as ``hermes_plugins.<slug>`` (slug from ``manifest.key`` so
``image_gen/openai`` cannot collide with ``tts/openai``)."""
@@ -504,9 +461,7 @@ class PluginLoaderMixin:
_evict_modules(module_name)
spec = importlib.util.spec_from_file_location(
- module_name,
- init_file,
- submodule_search_locations=[str(plugin_dir)],
+ module_name, init_file, submodule_search_locations=[str(plugin_dir)],
)
if spec is None or spec.loader is None:
raise ImportError(f"Cannot create module spec for {init_file}")
diff --git a/hermes_cli/plugins_manifest.py b/hermes_cli/plugins_manifest.py
index 68c1f586245..bab47297a80 100644
--- a/hermes_cli/plugins_manifest.py
+++ b/hermes_cli/plugins_manifest.py
@@ -37,8 +37,7 @@ def _portable_skill_namespace(key: str) -> str:
"""Return a readable, collision-resistant namespace for a portable plugin."""
slug = "".join(
- ch if ch.isascii() and (ch.isalnum() or ch in "_-") else "-"
- for ch in key.lower()
+ ch if ch.isascii() and (ch.isalnum() or ch in "_-") else "-" for ch in key.lower()
)
slug = slug.strip("-_") or "plugin"
digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:8]
@@ -49,9 +48,7 @@ def _display_author(value: object) -> str:
"""Normalize a manifest author value for the string PluginManifest field."""
if isinstance(value, Mapping):
return ", ".join(
- str(value[field])
- for field in ("name", "email", "url")
- if value.get(field)
+ str(value[field]) for field in ("name", "email", "url") if value.get(field)
)
return "" if value is None else str(value)
@@ -77,18 +74,9 @@ SUPPORTED_MANIFEST_VERSION = 2
_CONFIG_SCHEMA_TYPES: Dict[str, tuple] = {
- "str": (str,),
- "string": (str,),
- "int": (int,),
- "integer": (int,),
- "float": (int, float),
- "number": (int, float),
- "bool": (bool,),
- "boolean": (bool,),
- "list": (list,),
- "array": (list,),
- "dict": (dict,),
- "object": (dict,),
+ "str": (str,), "string": (str,), "int": (int,), "integer": (int,), "float": (int, float),
+ "number": (int, float), "bool": (bool,), "boolean": (bool,), "list": (list,), "array": (list,),
+ "dict": (dict,), "object": (dict,),
}
@@ -111,8 +99,7 @@ def _parse_manifest_v2_fields(data: Mapping, key: str) -> Dict[str, Any]:
mv = int(raw_mv)
except (TypeError, ValueError):
logger.warning(
- "Plugin %s: manifest_version %r is not an integer; treating as 1",
- key, raw_mv,
+ "Plugin %s: manifest_version %r is not an integer; treating as 1", key, raw_mv,
)
mv = 1
if mv > SUPPORTED_MANIFEST_VERSION:
@@ -194,8 +181,7 @@ def _parse_manifest_v2_fields(data: Mapping, key: str) -> Dict[str, Any]:
log = logger.warning if mv >= 2 else logger.debug
log(
"Plugin %s: unknown manifest field(s) ignored: %s "
- "(newer manifest schema or typo; plugin still loads)",
- key, ", ".join(unknown),
+ "(newer manifest schema or typo; plugin still loads)", key, ", ".join(unknown),
)
return out
@@ -264,8 +250,7 @@ def resolve_plugin_load_order(manifests: Mapping[str, "PluginManifest"]) -> List
logger.warning(
"Plugin %s requires plugin '%s' which is not enabled/"
"installed; loading anyway (probe availability at runtime "
- "via ctx.has_plugin). Run `hermes plugins enable %s` if "
- "it is installed.",
+ "via ctx.has_plugin). Run `hermes plugins enable %s` if it is installed.",
k, dep_id, dep_id,
)
continue
@@ -281,8 +266,7 @@ def resolve_plugin_load_order(manifests: Mapping[str, "PluginManifest"]) -> List
cycle = exc.args[1] if len(exc.args) > 1 else []
logger.warning(
"Plugin dependency cycle detected (%s); falling back to "
- "alphabetical load order for all plugins",
- " -> ".join(str(c) for c in cycle),
+ "alphabetical load order for all plugins", " -> ".join(str(c) for c in cycle),
)
return keys
@@ -432,15 +416,9 @@ def portable_plugin_manifest(child: Path, source: str, prefix: str) -> PluginMan
logger.warning("Agent Plugin '%s': %s", child, diagnostic.message)
key = f"{prefix}/{child.name}" if prefix else data["name"]
return PluginManifest(
- name=data["name"],
- version=data.get("version", ""),
- description=data.get("description", ""),
- author=_display_author(data.get("author", "")),
- source=source,
- path=str(child),
- key=key,
- portable=True,
- skill_namespace=_portable_skill_namespace(key),
+ name=data["name"], version=data.get("version", ""), description=data.get("description", ""),
+ author=_display_author(data.get("author", "")), source=source, path=str(child), key=key,
+ portable=True, skill_namespace=_portable_skill_namespace(key),
)
@@ -487,20 +465,14 @@ def parse_manifest_file(
key, name, kind, source, plugin_dir,
)
return PluginManifest(
- name=name,
- version=str(data.get("version", "")),
- description=data.get("description", ""),
- author=_display_author(data.get("author", "")),
+ name=name, version=str(data.get("version", "")),
+ description=data.get("description", ""), author=_display_author(data.get("author", "")),
requires_env=data.get("requires_env", []),
provides_tools=data.get("provides_tools", []),
- provides_hooks=data.get("provides_hooks", []),
- source=source,
- path=str(plugin_dir),
- kind=kind,
- key=key,
+ provides_hooks=data.get("provides_hooks", []), source=source, path=str(plugin_dir),
+ kind=kind, key=key,
capabilities=_parse_declared_capabilities(data.get("capabilities"), name),
- **_parse_manifest_v2_fields(data, key),
- emits=data.get("emits") or [],
+ **_parse_manifest_v2_fields(data, key), emits=data.get("emits") or [],
listens=data.get("listens") or [],
)
except Exception as exc:
diff --git a/hermes_cli/plugins_state.py b/hermes_cli/plugins_state.py
index d009aa785a7..f8d08adc736 100644
--- a/hermes_cli/plugins_state.py
+++ b/hermes_cli/plugins_state.py
@@ -39,13 +39,10 @@ def _plugin_relative_segments(key: str) -> tuple[str, ...]:
raise ValueError("Expected a plugin-relative config key string")
segments = tuple(key.split("."))
if (
- not key
- or "/" in key
- or "\\" in key
+ not key or "/" in key or "\\" in key
or any(
not _PLUGIN_SETTING_SEGMENT_RE.fullmatch(segment) for segment in segments
- )
- or segments[0].lower() in _PLUGIN_SETTING_RESERVED_ROOTS
+ ) or segments[0].lower() in _PLUGIN_SETTING_RESERVED_ROOTS
):
raise ValueError(
"Expected a plugin-relative config key such as 'endpoint' or "
@@ -74,8 +71,7 @@ def _plugin_data_namespace(plugin_id: str, skill_namespace: str) -> str:
"""Return one Windows-safe directory component for plugin-owned data."""
candidate = skill_namespace or plugin_id
if (
- skill_namespace
- and candidate.startswith("agent-plugin-")
+ skill_namespace and candidate.startswith("agent-plugin-")
and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]{0,191}", candidate)
):
# Portable Agent Plugins already receive this exact PLUGIN_DATA path.
@@ -142,11 +138,7 @@ class PluginState:
@staticmethod
def _validate_key(key: str) -> None:
- if (
- not isinstance(key, str)
- or not _PLUGIN_STATE_KEY_RE.fullmatch(key)
- or ".." in key
- ):
+ if (not isinstance(key, str) or not _PLUGIN_STATE_KEY_RE.fullmatch(key) or ".." in key):
raise ValueError(
"Plugin state keys must be 1-128 characters using letters, "
"numbers, '_', '-', '.', or ':' (without '..')"