plugins.py 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163
  1. """Hermes Plugin System — discovers, loads, and manages plugins.
  2. Sources, later overriding earlier on key collision: bundled ``<repo>/plugins/<name>/`` (``memory/``
  3. and ``context_engine/`` have their own discovery), user ``~/.hermes/plugins/<name>/``, project
  4. ``./.hermes/plugins/<name>/`` (opt-in via ``HERMES_ENABLE_PROJECT_PLUGINS``), and pip packages in
  5. the ``hermes_agent.plugins`` entry-point group. A directory plugin needs a ``plugin.yaml`` manifest
  6. and an ``__init__.py`` exposing ``register(ctx)``. Plugins register callbacks for ``VALID_HOOKS``
  7. (core fires ``invoke_hook(name, **kwargs)``) and tools via ``PluginContext.register_tool()``.
  8. """
  9. from __future__ import annotations
  10. import asyncio
  11. import importlib.metadata
  12. import json
  13. import logging
  14. import os
  15. import queue
  16. import re
  17. import sys
  18. import threading
  19. import types
  20. from contextlib import suppress
  21. from dataclasses import dataclass, field
  22. from functools import cached_property, wraps
  23. from pathlib import Path
  24. from typing import Any, Callable, Dict, List, Mapping, Optional, Set, Tuple, Union
  25. from hermes_constants import get_hermes_home, get_process_hermes_home, hermes_home_key
  26. from registration_lifecycle import replacement_coordinator
  27. from utils import env_var_enabled
  28. from hermes_cli.config import load_config_readonly
  29. from hermes_cli.middleware import VALID_MIDDLEWARE
  30. from hermes_cli.plugin_capabilities import plugin_capability_granted
  31. from hermes_cli.relay_plugin_cutover import RELAY_PLUGINS_CONFIG_ENV, legacy_relay_plugin_keys
  32. # Sibling modules' names are re-exported here (origin) so plugins and tests keep one import path.
  33. from hermes_cli.plugins_manifest import (
  34. _CONFIG_SCHEMA_TYPES, SUPPORTED_MANIFEST_VERSION, PluginManifest, _portable_data_namespace,
  35. manifest_key, parse_manifest_file, resolve_module_origin, resolve_plugin_load_order,
  36. validate_config_schema,
  37. )
  38. from hermes_cli.plugins_discovery import (
  39. ENTRY_POINTS_GROUP, _get_disabled_plugins, _get_enabled_plugins, collect_directory_manifests,
  40. discover_entrypoint_manifests, gate_manifest, plugin_discovery_suppressed, resolve_manifest_winners,
  41. scan_directory,
  42. )
  43. from hermes_cli.plugins_loader import (
  44. PluginLoaderMixin, _BARE_MODULE_SCOPE, _MODULE_NAMESPACE_LOCK, _NS_PARENT, _evict_modules,
  45. _plugin_home_scope, _serialized_replacement, in_plugin_load_worker,
  46. )
  47. from hermes_cli.plugins_dispatch import (
  48. DEFAULT_SYSTEM_PROMPT_SECTION_MAX_CHARS, HERMES_EVENT_NAMESPACE, MAX_SYSTEM_PROMPT_SECTION_CHARS,
  49. MAX_SYSTEM_PROMPT_SECTIONS_TOTAL_CHARS, PLUGIN_SECTIONS_END, PLUGIN_SECTIONS_START,
  50. SYSTEM_PROMPT_SECTION_POSITIONS, _EVENT_EMIT_DEPTH_CAP, _EVENT_PENDING_CAP,
  51. _HOOK_CALLBACK_TIMEOUT_SECS, _HOOK_TIMEOUT_SUPPRESSION_SECONDS, _MAX_HOOK_CALLBACK_TIMEOUT_SECS,
  52. _PRE_TOOL_CALL_TIMEOUT_BLOCK_MESSAGE, PluginDispatchMixin, PluginSystemPromptSection,
  53. RenderedPluginSystemPromptSection, _EventSubscription, format_system_prompt_sections,
  54. is_valid_system_prompt_section_id, resolve_plugin_command_result,
  55. )
  56. from hermes_cli.plugins_capability_ctx import PluginCapabilityCtxMixin
  57. from hermes_cli.plugins_ledger import PluginLedgerMixin, PluginRegistration
  58. from hermes_cli.plugins_registrars import _SCOPED_PROVIDER_REGISTRARS, make_scoped_provider_registrar
  59. from hermes_cli.plugins_state import (
  60. PluginState, _locked_plugin_state, _nested_plugin_mapping, _nested_plugin_value,
  61. _plugin_relative_segments, _plugin_settings_entry, save_plugin_setting,
  62. )
  63. def get_bundled_plugins_dir() -> Path:
  64. """Bundled ``plugins/`` dir: ``HERMES_BUNDLED_PLUGINS`` (Nix wrapper / packaged installs, read-only
  65. store paths) first, else the in-repo path."""
  66. env_override = os.getenv("HERMES_BUNDLED_PLUGINS")
  67. if env_override:
  68. return Path(env_override)
  69. return Path(__file__).resolve().parent.parent / "plugins"
  70. class PluginToolOverrideError(PermissionError):
  71. """Plugin tried to override a built-in tool without ``plugins.entries.<id>.allow_tool_override``."""
  72. logger = logging.getLogger(__name__)
  73. # ``HERMES_PLUGINS_DEBUG=1`` tees verbose discovery logs to stderr in addition to agent.log. Read
  74. # once at import; tests flip it mid-process via ``_install_plugin_debug_handler(force=True)``.
  75. _PLUGINS_DEBUG = env_var_enabled("HERMES_PLUGINS_DEBUG")
  76. _DEBUG_HANDLER_INSTALLED = False
  77. def _install_plugin_debug_handler(force: bool = False) -> None:
  78. """When HERMES_PLUGINS_DEBUG is on, tee plugin logs to stderr at DEBUG (once per process)."""
  79. global _DEBUG_HANDLER_INSTALLED, _PLUGINS_DEBUG
  80. if force:
  81. _PLUGINS_DEBUG = env_var_enabled("HERMES_PLUGINS_DEBUG")
  82. if not _PLUGINS_DEBUG or _DEBUG_HANDLER_INSTALLED:
  83. return
  84. handler = logging.StreamHandler(sys.stderr)
  85. handler.setLevel(logging.DEBUG)
  86. handler.setFormatter(logging.Formatter("[plugins] %(levelname)s %(message)s"))
  87. logger.addHandler(handler)
  88. logger.setLevel(logging.DEBUG)
  89. logger.propagate = True
  90. _DEBUG_HANDLER_INSTALLED = True
  91. logger.debug("HERMES_PLUGINS_DEBUG=1 — verbose plugin discovery logging enabled")
  92. _install_plugin_debug_handler()
  93. VALID_HOOKS: set[str] = {
  94. "pre_tool_call", "post_tool_call", "transform_terminal_output", "transform_tool_result",
  95. # transform_llm_output: return a replacement string (first non-None wins) or None.
  96. "transform_llm_output", "pre_llm_call", "post_llm_call",
  97. # Streaming observers (agent.plugin_stream_hooks), off the token path; payloads are immutable
  98. # normalized text/lifecycle and cannot transform the stream.
  99. "on_stream_start", "on_stream_delta", "on_stream_end", "on_interim_message",
  100. # pre_verify: once per turn when the agent edited code and is about to verify/finish. Return
  101. # {"action": "continue", "message"} (or Claude-Code Stop {"decision": "block", "reason"}) to keep
  102. # going; anything else finishes. Bounded by agent.max_verify_nudges.
  103. "pre_verify", "pre_api_request", "post_api_request", "api_request_error",
  104. # pre/post_auxiliary_call: once per physical provider attempt of an auxiliary LLM call
  105. # (agent/auxiliary_hooks.py — titling, compression, MoA, vision, approval, ...). Same payload
  106. # shape as pre/post_api_request plus ``aux_task``; distinct events so turn-scoped
  107. # ``*_api_request`` subscribers never receive auxiliary traffic (#79733). Observers; fail-open.
  108. "pre_auxiliary_call", "post_auxiliary_call",
  109. # transform_api_error_classification: once per failed API call BEFORE
  110. # agent/error_classifier.classify_api_error(). Kwargs: provider, model, status_code, error_type,
  111. # error_code, error_message, error_body, error, approx_tokens, context_length, num_messages.
  112. # Return None or {"reason": <FailoverReason name> (required), "retryable"/"should_compress"/
  113. # "should_rotate_credential"/"should_fallback": bool, "message": str, "error_context": dict}.
  114. # Run-all-then-pick-first (see get_plugin_error_classification). Privacy: error_message/
  115. # error_body may be unredacted.
  116. "transform_api_error_classification", "on_session_start", "on_session_end",
  117. "on_session_finalize", "on_session_reset", "on_session_delete",
  118. # on_skill_lifecycle: successful skill lifecycle facts (local skill name visible to plugins).
  119. "on_skill_lifecycle", "subagent_start", "subagent_stop",
  120. # pre_gateway_dispatch: once per incoming MessageEvent, after the internal-event guard, BEFORE
  121. # auth/pairing and dispatch. Kwargs: event, gateway, session_store. Return {"action": "skip",
  122. # "reason"} -> drop; {"action": "rewrite", "text"} -> replace event.text; "allow"/None -> normal.
  123. "pre_gateway_dispatch", "post_gateway_admission", # post_*: fail-open consume, gateway/run_inbound_consumer.py
  124. # agent_loop_stopped: an agent turn was interrupted mid-run (/stop, or the running-agent
  125. # fast-path of /new; see gateway/run.py::_interrupt_and_clear_session). Kwargs: session_key,
  126. # platform, reason, invalidation_reason. Return values are ignored.
  127. "agent_loop_stopped",
  128. # Approval observers (returns ignored; veto via pre_tool_call). Kwargs: command, description, pattern_key,
  129. # pattern_keys, session_key, surface ("cli"|"gateway"|"smart"|"mcp-elicitation/<server>"|"mcp-trust/<server>"|
  130. # "vault-payment"); post_approval_response adds choice/decided_by. on_human_input_*: tools/human_input_hooks.py.
  131. "pre_approval_request", "post_approval_response", "on_human_input_request", "on_human_input_resolved",
  132. # on_room_member_activity: a hosted Group Chat member's live runtime events (tool.started/completed,
  133. # request.opened, message.delta, reasoning.delta, turn.error, ...) stamped with room_id, thread_id,
  134. # member_id, turn_id, task_id, execution_generation. Observer, queued per consumer off the token
  135. # path (agent.plugin_stream_hooks); never written to the durable room log. Kwargs: those
  136. # coordinates + kind, seq, payload (the client-safe session event payload, approvals redacted).
  137. "on_room_member_activity",
  138. # pre_transcription: after provider resolution, BEFORE any backend runs. Kwargs: file_path,
  139. # provider, model, language, prompt, source. Return None or a dict mutating prompt/language/
  140. # model (registration order, last-writer-wins; file_path is read-only).
  141. "pre_transcription",
  142. # Kanban task observers (hermes_cli.kanban_db), fired AFTER the DB commit so a slow plugin never
  143. # holds the SQLite write lock; returns ignored. claimed fires in the DISPATCHER right before
  144. # spawn; completed/blocked fire in the WORKER (or whichever process drove it). Kwargs: task_id,
  145. # board, assignee, run_id, profile_name; completed adds summary, blocked adds reason.
  146. "kanban_task_claimed", "kanban_task_completed", "kanban_task_blocked",
  147. # Kanban worker/mutation/tick observers; returns ignored; fire sites short-circuit on
  148. # has_hook(). Kwargs: task_id, profile_name, board, assignee, run_id plus, per hook:
  149. # worker_spawned (DISPATCHER, after PID persisted, inside the dispatch lock — stay fast):
  150. # worker_pid, workspace_path (privacy: project layout/usernames).
  151. # worker_exited (tick-derived on dead-PID reclaim): worker_pid, exit_kind ("clean_exit" |
  152. # "rate_limited" | "nonzero_exit" | "signaled" | "unknown"), exit_code, outcome, retry_status.
  153. # worker_stale_claim (TTL-expired claim reclaimed; live-PID extensions do NOT fire):
  154. # worker_pid, heartbeat_stale, retry_status.
  155. # task_updated (committed task-row write outside claim/complete/block, in whichever process
  156. # committed it): changed_fields — field NAMES only, never values.
  157. # dispatch_tick (once per dispatch_once, strictly AFTER the dispatch lock is released): board,
  158. # profile_name, dry_run, outcome ("ok"|"skipped_locked"|"idle"), result: DispatchResult
  159. # (privacy: task ids, assignees, workspace paths).
  160. "on_kanban_worker_spawned", "on_kanban_worker_exited", "on_kanban_worker_stale_claim",
  161. "on_kanban_task_updated", "on_kanban_dispatch_tick",
  162. # gateway_platform_event: normalized envelopes only, never raw SDK objects or adapter handles.
  163. # Kwargs: platform, event_type, payload (event_type-local; see hooks.md). New event types land
  164. # only together with real fire-sites.
  165. # on_kanban_dispatch_tick fires once per dispatcher tick in dispatch_once, strictly AFTER the board's
  166. # single-writer dispatch lock has been released (the #56066 original fired inside the lock — the #64231
  167. # disposition mandates the post-lock re-port), so a slow subscriber can never extend the writer critical
  168. # section. Kwargs: board: str | None, profile_name: str, dry_run: bool, outcome: "ok" | "skipped_locked"
  169. # | "idle", result: hermes_cli.kanban_db.DispatchResult (spawned, reclaimed, promoted,
  170. # reconciled_orphans, crashed, stale, timed_out, auto_blocked, rate_limited, auto_assigned_default,
  171. # respawn_guarded, skipped_per_profile_capped, skipped_unassigned, skipped_nonspawnable,
  172. # skipped_locked). Privacy: result carries task ids, assignees, and workspace paths.
  173. # Gateway platform-boundary observer hooks (#64176). Observer-only; each callback isolated by
  174. # invoke_hook. This surface grants no adapter handles or platform actions. Fired today: Telegram
  175. # "reaction" + "message_edited"; Discord "message_edited", "message_deleted", "thread_created",
  176. # "thread_renamed". Each event type carries its own event-local additive payload contract (see
  177. # hooks.md). Other event types and hook names land here only together with real fire-sites and payload
  178. # contracts; no inert VALID_HOOKS surface is registered ahead of implementation.
  179. "gateway_platform_event",
  180. # pre_command: BEFORE a recognized slash command's handler on CLI and gateway canonical dispatch;
  181. # returns IGNORED in v1. Deliberately NOT fired for the gateway's running-agent intercept path
  182. # (/stop, /approve, busy_policy) — a slow/hostile plugin must not touch the operator's escape
  183. # hatches. Kwargs: surface, command (canonical), alias_used, args_raw, session_key, platform.
  184. # Observer-first (#64204, #64182 rule 3); a directive-shaped return gets a debug log so future
  185. # block/rewrite adopters are discoverable once the middleware variant ships (#64231 taxonomy).
  186. "pre_command",
  187. "post_compaction", # once per committed compaction on every path; observer (hooks.md, #118382)
  188. }
  189. # Hooks whose directive the shell-hook response parser has no channel for. VALID_HOOKS doubles as
  190. # the shell-hook allow-list, so these are refused loudly instead of having output silently ignored.
  191. SHELL_UNSUPPORTED_HOOKS: set[str] = {"transform_api_error_classification"}
  192. _env_enabled = env_var_enabled # imported by plugins/memory
  193. _UNSET = object()
  194. @dataclass
  195. class LoadedPlugin:
  196. """Runtime state for a single loaded plugin."""
  197. manifest: PluginManifest
  198. module: Optional[types.ModuleType] = None
  199. tools_registered: list[str] = field(default_factory=list)
  200. hooks_registered: list[str] = field(default_factory=list)
  201. middleware_registered: list[str] = field(default_factory=list)
  202. commands_registered: list[str] = field(default_factory=list)
  203. enabled: bool = False
  204. error: Optional[str] = None
  205. # Bundled platform recorded as a not-yet-imported loader (see _register_deferred_platform).
  206. deferred: bool = False
  207. class PluginContext(PluginCapabilityCtxMixin):
  208. """Facade given to plugins so they can register tools and hooks."""
  209. def __init__(self, manifest: PluginManifest, manager: PluginManager):
  210. self.manifest = manifest
  211. self._manager = manager
  212. self._llm: Any = None # lazy; tests preseed it (see ``llm``)
  213. # Set when this context's load overran ``plugins.load_timeout_seconds``: the abandoned worker may
  214. # still be running register(), and nothing it registers from then on may reach a registry.
  215. self._load_abandoned = False
  216. def _abandon_load(self) -> None:
  217. """Mark this load as timed out; every later ``register_*``/``subscribe``/``on_unload`` is ignored."""
  218. self._load_abandoned = True
  219. @property
  220. def plugin_id(self) -> str:
  221. """Return the effective registry id used for this plugin's namespaces."""
  222. return manifest_key(self.manifest)
  223. def has_plugin(self, plugin_id: str) -> bool:
  224. """Return True when another plugin is loaded and enabled (runtime probe for advisory
  225. ``requires_plugins``, #64165). Matches on registry key or manifest name."""
  226. return any(
  227. loaded.enabled and (key == plugin_id or loaded.manifest.name == plugin_id)
  228. for key, loaded in self._manager._plugins.items()
  229. )
  230. def _segments(self, key: str) -> tuple[str, ...]:
  231. """Validated plugin-relative settings path (warn + re-raise on rejection)."""
  232. try:
  233. return _plugin_relative_segments(key)
  234. except ValueError:
  235. logger.warning("Rejected config path %r from plugin %s", key, self.plugin_id)
  236. raise
  237. def get_config(self, key: str, default: Any = None) -> Any:
  238. """Read plugin-relative ``plugins.entries.<plugin_id>.settings.<key>`` (falls back to the
  239. legacy ``config`` subtree for migration compatibility)."""
  240. segments = self._segments(key)
  241. entry = _plugin_settings_entry(load_config_readonly() or {}, self.plugin_id)
  242. if entry is None:
  243. return default
  244. value = _nested_plugin_value(entry.get("settings"), segments, _UNSET)
  245. if value is not _UNSET:
  246. return value
  247. return _nested_plugin_value(entry.get("config"), segments, default)
  248. def set_config(self, key: str, value: Any) -> None:
  249. """Atomically write one value in this plugin's ``settings`` subtree."""
  250. save_plugin_setting(self.plugin_id, self._segments(key), value)
  251. @cached_property
  252. def state(self) -> PluginState:
  253. """This plugin's profile-scoped durable JSON state facade."""
  254. return PluginState(self.plugin_id, self.manifest.data_namespace)
  255. @cached_property
  256. def platform_actions(self):
  257. """Capability-gated platform action facade (``add_reaction``, ``set_thread_title``). Every call
  258. re-checks ``gateway.platform_actions`` (legacy ``plugins.entries.<id>.allow_platform_actions``,
  259. default OFF) and returns ``{"ok": bool, ...}`` — verbs never raise into hook dispatch; no adapter
  260. handles or raw SDK objects."""
  261. from hermes_cli.platform_actions import PlatformActions
  262. return PlatformActions(self.plugin_id)
  263. def _wrong_type(self, obj: Any, base_class: type, label: str, article: str = "a") -> bool:
  264. """Warn-and-ignore gate shared by every registrar that requires a base class."""
  265. if isinstance(obj, base_class):
  266. return False
  267. logger.warning("Plugin '%s' tried to register %s %s that does not inherit from %s. Ignoring.",
  268. self.manifest.name, article, label, base_class.__name__)
  269. return True
  270. def _refuse(self, what: str) -> ValueError:
  271. """``ValueError`` for a malformed registration (``what`` completes "tried to register ...")."""
  272. return ValueError(f"Plugin '{self.manifest.name}' tried to register {what}.")
  273. def _track(
  274. self, kind: str, key: str, release: Callable[[], None], *, persistent: bool = False,
  275. ) -> PluginRegistration:
  276. """Record host-owned cleanup for a registration (``persistent``: see ``_track_registration``)."""
  277. return self._manager._track_registration(self.manifest, kind, key, release, persistent=persistent)
  278. def _track_replacement(
  279. self, kind: str, key: str, *, slot: tuple, current: Any, previous: Any,
  280. restore: Callable[[Any], bool],
  281. ) -> PluginRegistration:
  282. """Track one generation in a replaceable manager-local registration slot."""
  283. lease = replacement_coordinator.acquire(slot, current=current, previous=previous, restore=restore)
  284. return self._track(kind, key, lease.dispose)
  285. def _track_mapping_entry(
  286. self, kind: str, key: str, mapping: dict[str, Any], entry: Any, previous: Any = _UNSET,
  287. ) -> PluginRegistration:
  288. """Store ``entry`` under ``key`` in a manager-local mapping and lease the slot; unload restores
  289. ``previous`` (default: the displaced entry, or removes the key) only while ``entry`` is still
  290. current."""
  291. if previous is _UNSET:
  292. previous = mapping.get(key)
  293. mapping[key] = entry
  294. return self._track_replacement(
  295. kind, key, slot=("manager_mapping", id(mapping), key), current=entry, previous=previous,
  296. restore=lambda replacement: self._manager._restore_mapping(mapping, key, entry, replacement),
  297. )
  298. def _register_entry(
  299. self, kind: str, key: str, mapping: dict[str, Any], entry: Any, log_fmt: str, *log_args: Any,
  300. previous: Any = _UNSET,
  301. ) -> PluginRegistration:
  302. """Store + lease a manager-mapping entry, then debug-log ``log_fmt % (plugin name, *log_args)``."""
  303. handle = self._track_mapping_entry(kind, key, mapping, entry, previous)
  304. logger.debug(log_fmt, self.manifest.name, *log_args)
  305. return handle
  306. def _register_scoped_provider(
  307. self, provider: Any, *, kind: str, base_class: type, registry: Any, label: str,
  308. article: str = "a", normalize: Optional[Callable[[str], str]] = lambda n: n.strip(),
  309. register: Optional[Callable[..., Any]] = None, reject_message: Optional[str] = None,
  310. ) -> Optional[PluginRegistration]:
  311. """Shared body of the ``register_<category>_provider`` methods: type-check (warn + ignore),
  312. register in the scope-keyed ``registry``, lease the slot so unload restores the displaced entry.
  313. ``None`` when the registry refused/replaced the provider (``ValueError`` with ``reject_message``
  314. set, or a falsy ``register``)."""
  315. if self._wrong_type(provider, base_class, label, article):
  316. return None
  317. registry_name = provider.name if normalize is None else normalize(provider.name)
  318. scope = self._manager.scope_key
  319. previous = registry.snapshot_registration(registry_name, scope=scope)
  320. try:
  321. accepted = (register or registry.register_provider)(provider, scope=scope)
  322. except ValueError as exc:
  323. if reject_message is None:
  324. raise
  325. logger.warning(reject_message, self.manifest.name, exc)
  326. return None
  327. if (register is not None and not accepted) or registry.snapshot_registration(
  328. registry_name, scope=scope
  329. ) is not provider:
  330. return None
  331. handle = self._manager._track_scoped_registration(
  332. self.manifest, kind, registry_name, registry, provider, previous
  333. )
  334. logger.info("Plugin '%s' registered %s: %s", self.manifest.name, label, registry_name)
  335. return handle
  336. @property
  337. def llm(self) -> Any:
  338. """Host-owned :class:`agent.plugin_llm.PluginLlm` facade: completions on the user's active
  339. model/auth. Overrides (model, agent id, auth profile) are fail-closed, gated by
  340. ``plugins.entries.<plugin_id>.llm.*``."""
  341. if self._llm is None:
  342. from agent.plugin_llm import PluginLlm
  343. self._llm = PluginLlm(plugin_id=self.plugin_id)
  344. return self._llm
  345. @cached_property
  346. def subagent_lifecycle(self) -> Any:
  347. """Plugin-safe subagent lifecycle service: serializable handles and immutable snapshots,
  348. never a live agent or private registry."""
  349. from agent.subagent_lifecycle import SubagentLifecycleService, get_active_subagent_parent
  350. return SubagentLifecycleService(get_active_subagent_parent)
  351. @cached_property
  352. def delegation_backends(self) -> Any:
  353. """``agent.delegation_backends.DelegationBackends``: list delegation backends and save one, optionally
  354. rebuilding the calling session's tools now (``/delegation``); a host remote facade on the owner process."""
  355. from agent.delegation_backends import DelegationBackends
  356. return DelegationBackends()
  357. @property
  358. def profile_name(self) -> str:
  359. """Active profile name (``"default"``, the ``~/.hermes/profiles/<name>`` id, or ``"custom"``),
  360. derived from ``HERMES_HOME`` — not ``_cli_ref``, which is None outside the interactive CLI —
  361. so gateway and kanban workers get it too."""
  362. try:
  363. from hermes_cli.profiles import get_active_profile_name
  364. return get_active_profile_name()
  365. except Exception:
  366. return "default"
  367. def current_cron_execution(self) -> Any:
  368. """The cron run executing now (``cron.execution_identity.CronExecution``), else ``None``."""
  369. from cron.execution_identity import current_cron_execution
  370. return current_cron_execution()
  371. def on_unload(self, callback: Callable[[], None]) -> PluginRegistration:
  372. """Register a cleanup callback for unload: runs in reverse acquisition order interleaved
  373. with registration teardown; exceptions are logged, never propagated."""
  374. if not callable(callback):
  375. raise TypeError("on_unload callback must be callable")
  376. handle = self._track("on_unload", getattr(callback, "__name__", "callback"), callback)
  377. logger.debug("Plugin %s registered on_unload callback", self.manifest.name)
  378. return handle
  379. def spawn_task(self, coro, *, name: Optional[str] = None) -> asyncio.Task:
  380. """Spawn a supervised asyncio task; unload/force reload cancels it. Needs a running loop."""
  381. if not asyncio.iscoroutine(coro):
  382. raise TypeError("spawn_task expects a coroutine")
  383. loop = asyncio.get_running_loop()
  384. task_name = name or f"plugin:{self.plugin_id}:task"
  385. task = loop.create_task(coro, name=task_name)
  386. handle = self._track("background_task", task_name, lambda: task.done() or task.cancel())
  387. task.add_done_callback(lambda _t: handle.dispose())
  388. logger.debug("Plugin %s spawned supervised task: %s", self.manifest.name, task_name)
  389. return task
  390. def register_approval_transport(self, name: str, present_fn: Callable) -> None:
  391. """Register a human approval transport, inactive until ``security.approval.transport:
  392. <name>`` selects it. It receives a redacted ``ApprovalRequest`` and returns only a
  393. correlated decision; policy and persistence stay host-owned. ``present_fn`` may be async."""
  394. from hermes_cli.approval_transport import RegisteredApprovalTransport
  395. transports = self._manager._approval_transports
  396. clean = str(name).strip().lower()
  397. if clean == "builtin":
  398. raise ValueError("approval transport name 'builtin' is reserved")
  399. if not re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,63}", clean):
  400. raise ValueError("approval transport name must match [a-z0-9][a-z0-9_-]{0,63}")
  401. if not callable(present_fn):
  402. raise TypeError("approval transport present_fn must be callable")
  403. if clean in transports:
  404. owner = transports[clean].plugin_id
  405. raise ValueError(f"approval transport {clean!r} is already registered by {owner!r}")
  406. entry = RegisteredApprovalTransport(
  407. name=clean, present=present_fn, plugin_id=self.plugin_id,
  408. profile_home=str(get_hermes_home().resolve()),
  409. )
  410. logger.info("Plugin %s registered approval transport: %s", self.plugin_id, clean)
  411. # Duplicate names are rejected above, so there is never a displaced previous entry to restore;
  412. # tracking makes unload/force-reload remove this transport.
  413. self._track_mapping_entry("approval_transport", clean, transports, entry, None)
  414. @_serialized_replacement
  415. def register_tool(
  416. self, name: str, toolset: str, schema: dict, handler: Callable,
  417. check_fn: Callable | None = None, requires_env: list | None = None, is_async: bool = False,
  418. description: str = "", emoji: str = "", override: bool = False,
  419. ) -> Optional[PluginRegistration]:
  420. """Register a tool in the global registry and track it as plugin-provided. ``override=True``
  421. replaces a same-named built-in (without it a name claimed by another toolset is rejected) and
  422. needs operator opt-in via ``plugins.entries.<plugin_id>.allow_tool_override: true`` — otherwise
  423. any enabled plugin could silently replace a privileged built-in like ``write_file`` (#23194)."""
  424. if override and not self._tool_override_allowed(name):
  425. raise PluginToolOverrideError(
  426. f"Plugin {self.manifest.name!r} cannot override built-in tool {name!r}. Set "
  427. f"plugins.entries.{self.plugin_id}.allow_tool_override: true "
  428. f"in config.yaml to allow this plugin to replace built-in tools."
  429. )
  430. from tools.registry import registry
  431. scope = self._manager.scope_key
  432. previous = registry.snapshot_registration(name, scope=scope)
  433. if previous is None and not override and registry.get_entry(name, scope=scope) is not None:
  434. logger.warning("Plugin %s tried to shadow global tool %s without override=True",
  435. self.manifest.name, name)
  436. return None
  437. registry.register(
  438. name=name, toolset=toolset, schema=schema, handler=handler, check_fn=check_fn,
  439. requires_env=requires_env, is_async=is_async, description=description, emoji=emoji,
  440. override=override, scope=scope,
  441. )
  442. registered = registry.snapshot_registration(name, scope=scope)
  443. handle = None
  444. if registered is not None and registered is not previous and registered.handler is handler:
  445. self._manager._plugin_tool_names.add(name)
  446. handle = self._manager._track_scoped_registration(
  447. self.manifest, "tool", name, registry, registered, previous,
  448. finalize=lambda: self._manager._remove_tool_name_if_unowned(name),
  449. )
  450. logger.debug("Plugin %s registered tool: %s%s", self.manifest.name, name,
  451. " (override)" if override else "")
  452. return handle
  453. def call_mcp(
  454. self, server: str, tool: str, arguments: Optional[dict[str, Any]] = None,
  455. timeout: float = 30,
  456. ) -> dict[str, Any]:
  457. """Call ``tool`` on MCP ``server`` synchronously through :mod:`tools.mcp_tool`'s native client
  458. (same trust gates, breaker, reconnect — never a parallel connection). Servers not in
  459. ``plugins.entries.<plugin_id>.mcp_allowlist`` raise ``PermissionError`` (default-deny). ``timeout``
  460. clamps to 1–600s; results over ~64KB are truncated with a marker.
  461. This is a per-server grant, deliberately not ambient authority over every configured server.
  462. TODO(#64228): swap the per-server allowlist for the declared capability model once it lands
  463. (per-tool grants, expiry, ro/rw).
  464. """
  465. if server not in self._mcp_allowlist(self.plugin_id):
  466. raise PermissionError(
  467. f"Plugin {self.manifest.name!r} is not allowed to call MCP "
  468. f"server {server!r}. Add it to "
  469. f"plugins.entries.{self.plugin_id}.mcp_allowlist in config.yaml "
  470. f"to grant access (default is no MCP access)."
  471. )
  472. try:
  473. timeout = float(timeout)
  474. except (TypeError, ValueError):
  475. timeout = 30.0
  476. timeout = max(1.0, min(timeout, 600.0))
  477. from tools.mcp_tool_handlers import _make_tool_handler
  478. raw = _make_tool_handler(server, tool, timeout)(dict(arguments or {}))
  479. logger.debug("Plugin %s called MCP %s/%s (timeout=%ss, %d chars returned)",
  480. self.manifest.name, server, tool, timeout, len(raw or ""))
  481. return self._mcp_envelope(raw)
  482. _MCP_RESULT_CHAR_CAP = 65536
  483. @classmethod
  484. def _mcp_envelope(cls, raw: Any) -> dict[str, Any]:
  485. """Normalize an MCP handler result string into a stable envelope."""
  486. if not isinstance(raw, str):
  487. raw = "" if raw is None else str(raw)
  488. truncated = len(raw) > cls._MCP_RESULT_CHAR_CAP
  489. if truncated:
  490. raw = raw[: cls._MCP_RESULT_CHAR_CAP] + "… [truncated]"
  491. try:
  492. parsed: Any = json.loads(raw)
  493. except (ValueError, TypeError):
  494. parsed = None
  495. if isinstance(parsed, dict) and "error" in parsed:
  496. envelope: dict[str, Any] = {"ok": False, "error": parsed["error"]}
  497. elif isinstance(parsed, dict) and "result" in parsed:
  498. envelope = {"ok": True, "result": parsed["result"]}
  499. if "structuredContent" in parsed:
  500. envelope["structuredContent"] = parsed["structuredContent"]
  501. else:
  502. envelope = {"ok": True, "result": parsed if parsed is not None else raw}
  503. return {**envelope, "truncated": True} if truncated else envelope
  504. @staticmethod
  505. def _mcp_allowlist(plugin_id: str) -> list[str]:
  506. """Operator-granted MCP server allowlist; missing/unreadable -> [] (default-deny)."""
  507. try:
  508. from hermes_cli.config import load_config
  509. cfg = load_config() or {}
  510. except Exception:
  511. return []
  512. allowlist = (_plugin_settings_entry(cfg, plugin_id) or {}).get("mcp_allowlist")
  513. return [str(item) for item in allowlist] if isinstance(allowlist, list) else []
  514. def _tool_override_allowed(self, tool_name: str) -> bool:
  515. """Whether this plugin may override built-in tools: bundled plugins are trusted (a maintainer
  516. choice, not privilege escalation); others need ``tools.override`` via
  517. :func:`plugin_capability_granted` (granted_capabilities OR legacy ``allow_tool_override: true``,
  518. still honored for backward compatibility; #64228)."""
  519. if self.manifest.source == "bundled":
  520. return True
  521. try:
  522. from hermes_cli.config import load_config
  523. with _plugin_home_scope(self._manager.home_path):
  524. cfg = load_config() or {}
  525. except Exception:
  526. return False # fail closed: better to break the override than silently grant it
  527. # Pass THIS manager's profile-scoped config so a multi-profile process never consults the
  528. # active profile's consent state instead.
  529. return plugin_capability_granted(self.plugin_id, "tools.override", config=cfg)
  530. # Fail-closed by construction: any failure to read consent state inside plugin_capability_granted
  531. # returns False. The profile-scoped config is passed through so a multi-profile process consults THIS
  532. # manager's home, never the active profile's (#65593 constraint).
  533. def inject_message(
  534. self, content: str, role: str = "user", *, session_key: str | None = None,
  535. origin: Mapping[str, Any] | None = None,
  536. ) -> bool:
  537. """Queue *content* for a session (``session_key``) or a chat in this plugin's own profile
  538. (``origin``); ``True`` means a host accepted it. Contract: plugins_injection.py, plugin docs."""
  539. from hermes_cli.plugins_injection import inject_plugin_message
  540. return inject_plugin_message(self, content, role, session_key=session_key, origin=origin)
  541. def session_cwd(self) -> str:
  542. """The calling session's recorded cwd, never the gateway's own (``plugin_session``)."""
  543. from hermes_cli.plugin_session import context_cwd
  544. return context_cwd(self._manager)
  545. def session_surface(self) -> str:
  546. """The calling session's client (``cli``/``tui``/``desktop``/``acp``) or messaging platform."""
  547. from hermes_cli.plugin_session import context_surface
  548. return context_surface(self._manager)
  549. def post_message(self, text: str) -> Any:
  550. """Post *text* into the session bound to this call; the handle's ``edit(text)`` updates it in
  551. place. Never raises (``ok=False`` + ``error`` with no conversation): ``plugin_messages.py``."""
  552. from hermes_cli.plugin_messages import post
  553. return post(self, text)
  554. async def apost_message(self, text: str) -> Any:
  555. """``post_message`` for async code on the gateway loop (edit with ``await handle.aedit``)."""
  556. from hermes_cli.plugin_messages import apost
  557. return await apost(self, text)
  558. def ask_choice(self, question: str, choices: list) -> Optional[str]:
  559. """From a sync slash-command handler: ask its user to pick one of *choices* (``str`` or
  560. ``{value, label?, description?}``); the value, or None if unanswerable: ``plugin_choices.py``."""
  561. from hermes_cli.plugin_choices import ask_choice
  562. return ask_choice(question, choices)
  563. def _gateway_injection_allowed(self) -> bool:
  564. """Return whether this plugin may trigger gateway session turns (read from the plugin's
  565. own profile config, never the calling thread's ambient home)."""
  566. try:
  567. with _plugin_home_scope(self._manager.home_path):
  568. cfg = load_config_readonly() or {}
  569. except Exception:
  570. return False
  571. return (_plugin_settings_entry(cfg, self.plugin_id) or {}).get("allow_gateway_injection") is True
  572. @_serialized_replacement
  573. def register_cli_command(
  574. self, name: str, help: str, setup_fn: Callable, handler_fn: Callable | None = None,
  575. description: str = "",
  576. ) -> PluginRegistration:
  577. """Register a CLI subcommand (``hermes <name> ...``). *setup_fn* receives the argparse
  578. subparser; *handler_fn* becomes ``set_defaults(func=...)``."""
  579. entry = {
  580. "name": name, "help": help, "description": description, "setup_fn": setup_fn,
  581. "handler_fn": handler_fn, "plugin": self.manifest.name, "plugin_key": self.plugin_id,
  582. }
  583. return self._register_entry("cli_command", name, self._manager._cli_commands, entry,
  584. "Plugin %s registered CLI command: %s", name)
  585. @_serialized_replacement
  586. def register_command(
  587. self, name: str, handler: Callable, description: str = "", args_hint: str = "",
  588. argument_mode: str | None = None,
  589. ) -> Optional[PluginRegistration]:
  590. """Register an in-session slash command (``/name``); handler ``fn(raw_args: str) -> str | None``
  591. (sync or async), plus the session-context keywords it declares (``plugin_command_dispatch``). ``args_hint`` (e.g. ``"<file>"``) lets adapters like Discord surface an argument
  592. field; without it the command registers parameterless there but still accepts trailing text."""
  593. clean = name.lower().strip().lstrip("/").replace(" ", "-")
  594. if not clean:
  595. logger.warning("Plugin '%s' tried to register a command with an empty name.", self.manifest.name)
  596. return
  597. with suppress(Exception): # reject if it conflicts with a built-in command
  598. from hermes_cli.commands import resolve_command
  599. if resolve_command(clean) is not None:
  600. logger.warning("Plugin '%s' tried to register command '/%s' which conflicts "
  601. "with a built-in command. Skipping.", self.manifest.name, clean)
  602. return
  603. hint = (args_hint or "").strip()
  604. entry = {
  605. "handler": handler, "description": description or "Plugin command",
  606. "plugin": self.manifest.name, "plugin_key": self.plugin_id, "args_hint": hint,
  607. "argument_mode": argument_mode if argument_mode in {"options", "text", "mixed"}
  608. else ("text" if hint else None),
  609. }
  610. return self._register_entry("command", clean, self._manager._plugin_commands, entry,
  611. "Plugin %s registered command: /%s", clean)
  612. def dispatch_tool(self, tool_name: str, args: dict, **kwargs) -> str:
  613. """Dispatch a tool call through the registry with the parent agent (when available)
  614. resolved automatically; returns the handler's JSON string. ``kwargs`` forward to dispatch."""
  615. from tools.registry import registry
  616. # In gateway mode _cli_ref is None — tools degrade gracefully (no spinner, TERMINAL_CWD).
  617. if "parent_agent" not in kwargs:
  618. agent = getattr(self._manager._cli_ref, "agent", None)
  619. if agent is not None:
  620. kwargs["parent_agent"] = agent
  621. return registry.dispatch(tool_name, args, scope=self._manager.scope_key, **kwargs)
  622. @_serialized_replacement
  623. def register_context_engine(self, engine) -> Optional[PluginRegistration]:
  624. """Register the (single) ``agent.context_engine.ContextEngine`` replacing the built-in
  625. ContextCompressor; a second registration is rejected with a warning."""
  626. if self._manager._context_engine is not None:
  627. logger.warning("Plugin '%s' tried to register a context engine, but one is "
  628. "already registered. Only one context engine plugin is allowed.",
  629. self.manifest.name)
  630. return
  631. from agent.context_engine import ContextEngine
  632. if self._wrong_type(engine, ContextEngine, "context engine"):
  633. return
  634. previous = self._manager._context_engine # always None here; kept for the restore contract
  635. self._manager._context_engine = engine
  636. handle = self._track_replacement(
  637. "context_engine", engine.name, slot=("manager_value", id(self._manager), "_context_engine"),
  638. current=engine, previous=previous,
  639. restore=lambda replacement: self._manager._restore_value("_context_engine", engine, replacement),
  640. )
  641. logger.info("Plugin '%s' registered context engine: %s", self.manifest.name, engine.name)
  642. return handle
  643. def register_context_reference(self, provider) -> None:
  644. """Register a :class:`agent.context_references.ContextReferenceProvider`; ``provider.prefix``
  645. defines ``@<prefix>:``. Built-in prefixes (diff, staged, file, folder, git, url) are
  646. rejected."""
  647. from agent.context_references import (
  648. ContextReferenceProvider as _CRP, register_context_reference_provider as _register,
  649. )
  650. if self._wrong_type(provider, _CRP, "context reference provider"):
  651. return
  652. try:
  653. _register(provider)
  654. except ValueError as exc:
  655. logger.warning("Plugin '%s' context reference registration failed: %s", self.manifest.name, exc)
  656. return
  657. logger.info("Plugin '%s' registered context reference: @%s:", self.manifest.name, provider.prefix)
  658. def register_memory_provider(self, provider) -> None:
  659. """Record a memory provider (inert). Activation is owned by ``plugins/memory`` via
  660. ``memory.provider``; a provider reaching here was loaded by the general manager, and
  661. without this method its ``register()`` would fail on a missing attribute."""
  662. from agent.memory_provider import MemoryProvider
  663. if self._wrong_type(provider, MemoryProvider, "memory provider"):
  664. return
  665. self._memory_provider = provider
  666. logger.debug("Plugin '%s' registered memory provider: %s", self.manifest.name,
  667. getattr(provider, "name", "?"))
  668. @_serialized_replacement
  669. def register_dashboard_auth_provider(self, provider) -> Optional[PluginRegistration]:
  670. """Register a :class:`hermes_cli.dashboard_auth.DashboardAuthProvider` for the dashboard
  671. auth gate (non-loopback bind without ``--insecure``). Wrong type / duplicate name warn and
  672. are ignored, never raised."""
  673. from hermes_cli.dashboard_auth import DashboardAuthProvider
  674. from hermes_cli.dashboard_auth.registry import register_global_provider, unregister_global_provider
  675. if self._wrong_type(provider, DashboardAuthProvider, "dashboard-auth provider"):
  676. return
  677. launch_scope = hermes_home_key(get_process_hermes_home())
  678. if self._manager.scope_key != launch_scope:
  679. logger.warning(
  680. "Plugin '%s' tried to register dashboard-auth provider %r "
  681. "from profile scope %s; ignoring it because dashboard auth "
  682. "is owned by launch scope %s.",
  683. self.manifest.name,
  684. provider.name,
  685. self._manager.scope_key,
  686. launch_scope,
  687. )
  688. return
  689. registry_name = provider.name
  690. # The auth registry is process-global (lifetime = web server). Disposing it on a routine
  691. # per-home manager teardown emptied it for the WHOLE process and disabled sign-in until
  692. # restart — so upsert and keep it out of reverse-order teardown (``persistent=True``).
  693. try:
  694. # A per-home manager is torn down routinely (profile-scoped dashboard activity, force
  695. # re-discovery), and disposing this registration on that teardown emptied the auth registry for
  696. # the WHOLE process, permanently disabling sign-in until restart (#91701). The handle still
  697. # disposes explicitly (identity- conditional), and a forced re-discovery rotates the provider in
  698. # place via the upsert.
  699. register_global_provider(provider)
  700. except (TypeError, ValueError) as e:
  701. logger.warning("Plugin '%s' failed to register dashboard-auth provider %r: %s",
  702. self.manifest.name, getattr(provider, "name", "?"), e)
  703. return
  704. handle = self._track("dashboard_auth_provider", registry_name,
  705. lambda: unregister_global_provider(registry_name, provider), persistent=True)
  706. logger.info("Plugin '%s' registered dashboard-auth provider: %s (%s)", self.manifest.name,
  707. registry_name, provider.display_name)
  708. return handle
  709. @_serialized_replacement
  710. def register_platform(
  711. self, name: str, label: str, adapter_factory: Callable, check_fn: Callable,
  712. validate_config: Callable | None = None, required_env: list | None = None,
  713. install_hint: str = "", **entry_kwargs: Any,
  714. ) -> Optional[PluginRegistration]:
  715. """Register a gateway platform adapter (``adapter_factory(PlatformConfig) -> BasePlatformAdapter``).
  716. ``check_fn`` is a PASSIVE "deps importable?" probe that must never install (status displays call
  717. it freely); an ACTIVE installer goes in ``ensure_deps_fn`` (called from ``create_adapter()`` when
  718. ``check_fn`` is False). Extra kwargs (``setup_fn``, ``emoji``, ``allowed_users_env``,
  719. ``platform_hint``, ``ensure_deps_fn``) forward to ``PlatformEntry``; unknown keys raise TypeError."""
  720. from gateway.platform_registry import core_ships_platform, platform_registry, PlatformEntry
  721. if entry_kwargs.get("trusted_inbound") and self.manifest.source != "bundled" and core_ships_platform(name):
  722. raise self._refuse(f"core platform '{name}' with trusted_inbound (it would waive allowlists and pairing)")
  723. entry_kwargs.setdefault("plugin_name", self.manifest.name)
  724. entry = PlatformEntry(
  725. name=name, label=label, adapter_factory=adapter_factory, check_fn=check_fn,
  726. validate_config=validate_config, required_env=required_env or [],
  727. install_hint=install_hint, source="plugin", **entry_kwargs,
  728. )
  729. scope = self._manager.scope_key
  730. previous = platform_registry.snapshot_registration(name, scope=scope)
  731. platform_registry.register(entry, scope=scope)
  732. current = platform_registry.snapshot_registration(name, scope=scope)
  733. if current[0] is not entry or current[1] is not None:
  734. return None
  735. self._manager._plugin_platform_names.add(name)
  736. handle = self._manager._track_scoped_registration(
  737. self.manifest, "platform", name, platform_registry, current, previous,
  738. finalize=lambda: self._manager._remove_platform_name_if_unowned(name),
  739. )
  740. logger.debug("Plugin %s registered platform: %s", self.manifest.name, name)
  741. return handle
  742. def register_slack_action_handler(
  743. self, action_id: Any, callback: Callable,
  744. ) -> PluginRegistration:
  745. """Register a Slack Block Kit action handler, wired into ``slack_bolt.AsyncApp`` at connect.
  746. ``action_id`` is anything ``slack_bolt.App.action()`` accepts; ``callback`` is
  747. ``async def handler(ack, body, action)`` (``await ack()`` within 3s). Raises ``ValueError`` for
  748. a non-callable callback or empty ``action_id``."""
  749. if not callable(callback):
  750. raise self._refuse("a Slack action handler with a non-callable callback")
  751. if action_id is None or (isinstance(action_id, str) and not action_id.strip()):
  752. raise self._refuse("a Slack action handler with an empty action_id")
  753. entry = (action_id, callback, self.manifest.name)
  754. handlers = self._manager._slack_action_handlers
  755. handlers.append(entry)
  756. handle = self._track("slack_action_handler", repr(action_id),
  757. lambda: self._manager._remove_identity(handlers, entry))
  758. logger.debug("Plugin %s registered Slack action handler: %s", self.manifest.name, action_id)
  759. return handle
  760. def register_platform_handler(self, platform: str, factory: Callable) -> None:
  761. """Register ``factory(native, adapter)``, invoked at ``connect()`` before/as the core handlers
  762. register (``adapter`` read-only). ``native``: telegram PTB ``Application``, discord
  763. ``commands.Bot``, slack ``AsyncApp``, matrix client, teams ``App``, dingtalk
  764. ``DingTalkStreamClient``, line aiohttp ``web.Application``, others ``None``. Keep SDK imports
  765. inside the factory; exceptions are logged and the platform still connects. Scope handlers in
  766. first-match dispatch tables so core flows keep working. Raises ``ValueError`` when not callable
  767. or platform is empty."""
  768. if not callable(factory):
  769. raise self._refuse("a platform handler factory with a non-callable factory")
  770. key = (platform or "").strip().lower()
  771. if not key:
  772. raise self._refuse("a platform handler factory with an empty platform name")
  773. self._manager._platform_handler_factories.setdefault(key, []).append((factory, self.manifest.name))
  774. logger.debug("Plugin %s registered %s handler factory: %s", self.manifest.name, key,
  775. getattr(factory, "__name__", repr(factory)))
  776. def register_telegram_handler(self, factory: Callable) -> None:
  777. """``register_platform_handler("telegram", factory)``. PTB dispatches only the FIRST matching
  778. handler per group and core registers a catch-all ``CallbackQueryHandler`` — always scope with
  779. ``pattern=`` or you swallow the core button flows."""
  780. self.register_platform_handler("telegram", factory)
  781. @_serialized_replacement
  782. def register_auxiliary_task(
  783. self, key: str, *, display_name: str, description: str,
  784. defaults: Optional[dict[str, Any]] = None,
  785. inherit_from: Optional[str] = None,
  786. ) -> PluginRegistration:
  787. """Register an auxiliary LLM task with its own ``auxiliary.<key>`` config block (picker entry,
  788. ``AUXILIARY_<KEY>_*`` env bridge, defaults merged into loaded configs). ``defaults`` may
  789. override provider/model/base_url/api_key/timeout/extra_body (unknown keys kept verbatim).
  790. ``inherit_from`` names a built-in or already-registered auxiliary task whose effective
  791. configuration becomes the base for this one; it is resolved at read time, so the task tracks
  792. the base's current config instead of snapshotting it (precedence: inherited base, then
  793. ``defaults``, then user config in ``auxiliary.<key>``). An unknown or self-referential
  794. ``inherit_from`` logs a warning and registers the task without inheritance.
  795. Raises ``ValueError`` for an empty/invalid key, a built-in key, or another plugin's key."""
  796. from hermes_cli.plugins_aux_tasks import build_auxiliary_task_entry
  797. existing = self._manager._aux_tasks.get(key)
  798. entry = build_auxiliary_task_entry(
  799. self.manifest.name, self.plugin_id, key, display_name=display_name, description=description,
  800. defaults=defaults, inherit_from=inherit_from, registered=self._manager._aux_tasks)
  801. return self._register_entry("auxiliary_task", key, self._manager._aux_tasks, entry,
  802. "Plugin %s registered auxiliary task: %s (%s)", key, display_name,
  803. previous=existing)
  804. def register_redaction_patterns(self, patterns) -> int:
  805. """Additively register secret-token regexes with :mod:`agent.redact`; returns the count accepted.
  806. Plugins can over-redact, never weaken built-ins; ``security.redact_secrets: false`` applies
  807. equally. Each pattern must compile and start with >= 2 literal characters; invalid entries warn
  808. and are skipped."""
  809. from agent.redact import register_redaction_patterns as _register
  810. try:
  811. count = _register(patterns, source=f"plugin:{self.manifest.name}")
  812. except Exception as exc:
  813. logger.warning("Plugin '%s' redaction pattern registration failed: %s", self.manifest.name, exc)
  814. return 0
  815. logger.debug("Plugin %s registered %d redaction pattern(s)", self.manifest.name, count)
  816. return count
  817. def register_locale(
  818. self, lang: str, source: str | Path | Mapping[str, Any], *, endonym: Optional[str] = None,
  819. rtl: bool = False, surface: str = "core",
  820. ) -> PluginRegistration:
  821. """Register a language-pack layer for ``lang`` (``pl``, ``pt-br``): ``source`` is a YAML file path or
  822. a nested/flat mapping of ``dotted.key: text``. ``surface`` is ``core`` (Python ``t()``), ``tui`` or
  823. ``desktop`` (served to the renderers over ``i18n.catalog``). Partial catalogs are fine; the last
  824. registration wins key by key. Resets the i18n caches; never changes ``display.language``. Raises
  825. ``ValueError`` for a malformed id/surface/file and ``FileNotFoundError`` for a missing path."""
  826. from agent.i18n_layers import (
  827. SURFACES, is_language_id, load_locale_source, normalize_language_id, register_pack, unregister_pack,
  828. )
  829. lang_id = normalize_language_id(lang)
  830. if not is_language_id(lang_id):
  831. raise self._refuse(f"locale with invalid language id {lang!r} (expected e.g. 'pl', 'pt-br')")
  832. if surface not in SURFACES:
  833. raise self._refuse(f"locale {lang_id!r} for unknown surface {surface!r} (one of {', '.join(SURFACES)})")
  834. messages = load_locale_source(source)
  835. entry = register_pack(lang_id, surface, messages, source=f"plugin:{self.manifest.name}",
  836. endonym=endonym, rtl=rtl)
  837. handle = self._track("locale", f"{lang_id}.{surface}", lambda: unregister_pack(entry))
  838. logger.debug("Plugin %s registered locale: %s/%s (%d keys)", self.manifest.name, lang_id, surface,
  839. len(messages))
  840. return handle
  841. def register_locale_dir(
  842. self, path: str | Path, *, metadata: Optional[Mapping[str, Mapping[str, Any]]] = None,
  843. ) -> list[PluginRegistration]:
  844. """Register every ``<lang>[.tui|.desktop].yaml`` under ``path`` (a pack's ``locales/`` dir). The
  845. loader calls this for plugins declaring ``provides_locales``; ``metadata`` maps ids to
  846. ``{endonym, rtl}``. A broken file is skipped with a warning so one typo never disables the pack."""
  847. from agent.i18n_layers import scan_locale_dir
  848. handles: list[PluginRegistration] = []
  849. for lang_id, surface, file in scan_locale_dir(Path(path)):
  850. meta = dict((metadata or {}).get(lang_id) or {})
  851. try:
  852. handles.append(self.register_locale(
  853. lang_id, file, surface=surface, endonym=meta.get("endonym"), rtl=bool(meta.get("rtl", False)),
  854. ))
  855. except Exception as exc:
  856. logger.warning("Plugin '%s' locale file %s skipped: %s", self.manifest.name, file, exc)
  857. return handles
  858. def register_hook(self, hook_name: str, callback: Callable, *, hold_stream: bool = False) -> PluginRegistration:
  859. """Register a lifecycle hook callback (``PluginDispatchMixin.track_hook``)."""
  860. return self._manager.track_hook(self, hook_name, callback, hold_stream=hold_stream)
  861. def register_middleware(self, kind: str, callback: Callable) -> PluginRegistration:
  862. """Register behavior-changing middleware (request kinds rewrite the payload, execution kinds
  863. wrap the callback). Unknown kinds warn but are stored."""
  864. return self._track_callback(
  865. "middleware", kind, callback, self._manager._middleware, VALID_MIDDLEWARE
  866. )
  867. def _track_callback(
  868. self, kind: str, key: str, callback: Callable, mapping: dict[str, list[Callable]],
  869. valid: set[str],
  870. ) -> PluginRegistration:
  871. """Append ``callback`` under ``key`` (warning on unknown ``key``) and lease its removal."""
  872. if key not in valid:
  873. logger.warning("Plugin '%s' registered unknown %s '%s' (valid: %s)", self.manifest.name, kind,
  874. key, ", ".join(sorted(valid)))
  875. mapping.setdefault(key, []).append(callback)
  876. handle = self._track(kind, key, lambda: self._manager._remove_callback(mapping, key, callback))
  877. logger.debug("Plugin %s registered %s: %s", self.manifest.name, kind, key)
  878. return handle
  879. def register_system_prompt_section(
  880. self, id: str, content: str | Callable[[Mapping[str, Any]], str], *,
  881. position: str = "after_memory", max_chars: int = DEFAULT_SYSTEM_PROMPT_SECTION_MAX_CHARS,
  882. ) -> PluginRegistration:
  883. """Register bounded context frozen into each new session prompt. Callables receive a
  884. read-only session-info mapping; the rendered prompt is persisted by core verbatim."""
  885. if not is_valid_system_prompt_section_id(id):
  886. raise ValueError("system prompt section id must be 1-128 lowercase characters "
  887. "using letters, numbers, '.', '_', or '-'")
  888. if not isinstance(content, str) and not callable(content):
  889. raise TypeError("system prompt section content must be a string or callable")
  890. if position not in SYSTEM_PROMPT_SECTION_POSITIONS:
  891. raise ValueError("system prompt section position must be one of: "
  892. + ", ".join(sorted(SYSTEM_PROMPT_SECTION_POSITIONS)))
  893. if (isinstance(max_chars, bool) or not isinstance(max_chars, int)
  894. or not 0 < max_chars <= MAX_SYSTEM_PROMPT_SECTION_CHARS):
  895. raise ValueError(f"system prompt section max_chars must be between 1 and {MAX_SYSTEM_PROMPT_SECTION_CHARS}")
  896. existing = self._manager._system_prompt_sections.get(id)
  897. if existing is not None:
  898. raise ValueError(f"system prompt section {id!r} is already registered by plugin {existing.plugin!r}")
  899. section = PluginSystemPromptSection(
  900. id=id, content=content, position=position, max_chars=max_chars, plugin=self.plugin_id,
  901. )
  902. return self._register_entry("system_prompt_section", id, self._manager._system_prompt_sections,
  903. section, "Plugin %s registered system prompt section: %s", id,
  904. previous=existing)
  905. def emit(self, event: str, payload: Optional[dict] = None) -> int:
  906. """Publish bare *event* as ``<plugin_key>:<event>`` (namespace FORCED to this plugin); return
  907. the subscriber count scheduled. Any ``':'`` in the name (``hermes:x`` is reserved for core,
  908. foreign namespaces forbidden) raises ``ValueError``. Delivery is fire-and-forget via a
  909. single-worker queue: order preserved, a blocking subscriber cannot stall the emitter."""
  910. plugin_key = self.plugin_id
  911. if not event or not isinstance(event, str):
  912. logger.warning("Plugin '%s' tried to emit an invalid event name %r", plugin_key, event)
  913. raise ValueError(f"Plugin '{plugin_key}' emit() requires a non-empty event name")
  914. if ":" in event:
  915. logger.warning("Plugin '%s' tried to emit namespaced/reserved event '%s' — a plugin may only emit "
  916. "bare event names under its own '%s:' namespace (the '%s:' prefix is reserved "
  917. "for core, and foreign namespaces are forbidden)",
  918. plugin_key, event, plugin_key, HERMES_EVENT_NAMESPACE)
  919. raise ValueError(f"Plugin '{plugin_key}' may not emit '{event}': emit only the bare event name; "
  920. f"the namespace is forced to '{plugin_key}:' and the '{HERMES_EVENT_NAMESPACE}:' "
  921. f"prefix is reserved for core")
  922. if payload is not None and not isinstance(payload, dict):
  923. raise TypeError(f"Plugin '{plugin_key}' emit() payload must be a dict or None")
  924. return self._manager._dispatch_event(f"{plugin_key}:{event}", payload or {})
  925. def subscribe(self, event: str, callback: Callable) -> None:
  926. """Subscribe to a fully-qualified ``<plugin_key>:<event>`` name (unrestricted — only
  927. emitting is namespace-gated). Owner-tagged so unload removes zombie callbacks."""
  928. if not event or not isinstance(event, str):
  929. raise ValueError(f"Plugin '{self.manifest.name}' subscribe() requires a non-empty event name")
  930. self._manager._subscribe_event(self.plugin_id, event, callback)
  931. logger.debug("Plugin %s subscribed to event: %s", self.manifest.name, event)
  932. from hermes_cli.plugins_content import register_automation_blueprint, register_skill
  933. # -- scoped provider registrars ------------------------------------------------------------------
  934. # One generated ``register_<category>_provider`` method per row of plugins_registrars.py's table.
  935. for _row in _SCOPED_PROVIDER_REGISTRARS:
  936. setattr(PluginContext, _row[0], make_scoped_provider_registrar(*_row))
  937. del _row
  938. def _ignore_after_abandoned_load(method):
  939. """Turn a registrar into a no-op once the context's load timed out: the abandoned worker thread may
  940. still be executing register(), and a late registration would land in registries that the failure
  941. path already swept (#108139)."""
  942. @wraps(method)
  943. def wrapped(self, *args, **kwargs):
  944. if getattr(self, "_load_abandoned", False):
  945. logger.warning(
  946. "Plugin '%s' called %s() after its load timed out; ignored", self.manifest.name,
  947. method.__name__,
  948. )
  949. return None
  950. return method(self, *args, **kwargs)
  951. return wrapped
  952. # Every mutating entry point plugins reach through ``ctx`` during register(); applied by name so the
  953. # guard cannot drift from the surface as registrars are added.
  954. for _name, _method in list(vars(PluginContext).items()):
  955. if callable(_method) and (_name.startswith("register_") or _name in {"subscribe", "on_unload"}):
  956. setattr(PluginContext, _name, _ignore_after_abandoned_load(_method))
  957. del _name, _method
  958. def _resolve_hook_callback_timeout() -> float:
  959. """Effective hook-callback timeout from ``plugins.hook_callback_timeout`` (default 30s; ``<= 0``
  960. disables the threaded path; clamped to ``_MAX_HOOK_CALLBACK_TIMEOUT_SECS``).
  961. ``invoke_hook`` calls this once per hook invocation; ``load_config_readonly()`` serves cache hits
  962. without ``_CONFIG_LOCK``, so this is a stat + dict lookup per call and needs no memo of its own.
  963. """
  964. default = _HOOK_CALLBACK_TIMEOUT_SECS
  965. try:
  966. plugins_cfg = (load_config_readonly() or {}).get("plugins")
  967. if not isinstance(plugins_cfg, dict) or plugins_cfg.get("hook_callback_timeout") is None:
  968. return default
  969. timeout = float(plugins_cfg["hook_callback_timeout"])
  970. except (TypeError, ValueError):
  971. logger.warning("plugins.hook_callback_timeout is not a number; using default %gs", default)
  972. return default
  973. except Exception:
  974. return default
  975. if timeout < 0:
  976. logger.warning("plugins.hook_callback_timeout=%g is negative; using default %gs", timeout, default)
  977. return default
  978. if timeout > _MAX_HOOK_CALLBACK_TIMEOUT_SECS:
  979. logger.warning("plugins.hook_callback_timeout=%g exceeds max %gs; clamping", timeout,
  980. _MAX_HOOK_CALLBACK_TIMEOUT_SECS)
  981. return _MAX_HOOK_CALLBACK_TIMEOUT_SECS
  982. return timeout
  983. class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):
  984. """Central manager that discovers, loads, and invokes plugins."""
  985. def __init__(self, scope_key: Optional[str] = None) -> None:
  986. # Capture the home immutably. Unload can run from a different ambient
  987. # profile context, but every inverse must target the registration's
  988. # original scope. Normalize through hermes_home_key so the scope
  989. # matches the key the registries store under (normcase on Windows).
  990. self.scope_key = hermes_home_key(scope_key)
  991. self.home_path = Path(self.scope_key)
  992. self._discovery_lock = threading.RLock()
  993. self._discovered: bool = False
  994. # True once a discovery re-applied plugin secret sources for this home: the per-home snapshot and
  995. # the installed scope may then hold plugin-supplied names, and a later discovery that finds NO
  996. # enabled plugin source (plugin removed / disabled) must still reconcile once to drop them.
  997. self._plugin_secret_sources_reconciled: bool = False
  998. self._cli_ref = None # Set by CLI after plugin discovery
  999. self._gateway_message_injector: tuple[object, Callable] | None = None
  1000. # Ink TUI / desktop. Must not alias ``_gateway_message_injector``: a live
  1001. # messaging gateway and a TUI in one process would otherwise clobber each other.
  1002. self._tui_message_injector: tuple[object, Callable] | None = None
  1003. self._context_engine = None # Set by a plugin via register_context_engine()
  1004. # Manager-local registries keyed by name (see the matching ``PluginContext.register_*``):
  1005. # plugins, hooks, middleware, CLI + slash commands, prompt sections, skills (qualified name ->
  1006. # metadata), portable MCP servers, auxiliary tasks, approval transports, Slack action handlers
  1007. # (matcher, callback, plugin_name), platform handler factories (lowercase platform -> list).
  1008. self._plugins: dict[str, LoadedPlugin] = {}
  1009. self._hooks: dict[str, list[Callable]] = {}
  1010. # Fallback hooks registered by a memory provider before general discovery.
  1011. self._memory_hook_registrations: dict[tuple[str, str], list[PluginRegistration]] = {}
  1012. self._middleware: dict[str, list[Callable]] = {}
  1013. self._plugin_tool_names: set[str] = set()
  1014. self._plugin_platform_names: set[str] = set()
  1015. self._cli_commands: dict[str, dict] = {}
  1016. self._plugin_commands: dict[str, dict] = {}
  1017. self._system_prompt_sections: dict[str, PluginSystemPromptSection] = {}
  1018. self._plugin_skills: dict[str, dict[str, Any]] = {}
  1019. self._automation_blueprints: dict[str, Any] = {} # "<plugin>:<key>" -> AutomationBlueprint
  1020. self._portable_mcp_servers: dict[str, dict[str, Any]] = {}
  1021. self._portable_mcp_server_plugins: dict[str, str] = {}
  1022. self._aux_tasks: dict[str, dict[str, Any]] = {}
  1023. self._approval_transports: dict[str, Any] = {}
  1024. self._slack_action_handlers: list[tuple] = []
  1025. self._platform_handler_factories: dict[str, list[tuple]] = {}
  1026. # Process-owned discovery listeners (``on_plugin_loaded``); never cleared by unload().
  1027. self._plugin_loaded_listeners: list[Callable] = []
  1028. # Event bus: owner-tagged subscriptions (unload removes zombies); one daemon worker keeps
  1029. # registration order while emitters never block; per-worker chain depth caps mutual emitters.
  1030. self._subscriptions: dict[str, list[_EventSubscription]] = {}
  1031. self._event_lock = threading.RLock()
  1032. self._event_idle = threading.Condition(self._event_lock)
  1033. self._event_generation = 0
  1034. self._event_pending_by_generation: dict[int, int] = {0: 0}
  1035. self._event_queue: queue.Queue[Any] = queue.Queue(maxsize=_EVENT_PENDING_CAP)
  1036. self._event_worker: Optional[threading.Thread] = None
  1037. self._emit_depth = threading.local()
  1038. # In-flight / recently-timed-out hook callbacks keyed by (hook_name, id(cb), call_identity)
  1039. # so a stuck policy hook cannot spawn a new abandoned thread on every fire.
  1040. self._hook_running_callbacks: dict[tuple, object] = {}
  1041. self._hook_abandoned: dict[tuple, set] = {}
  1042. self._hook_timeout_suppressed_until: dict[tuple, float] = {}
  1043. self._hook_timeout_lock = threading.Lock()
  1044. self._hook_timeout_suppression_seconds = _HOOK_TIMEOUT_SUPPRESSION_SECONDS
  1045. # (hook_name, id(cb), repr(exc)) already reported at WARNING; identical repeats go to DEBUG.
  1046. self._hook_failures_reported: set = set()
  1047. # Ledger per plugin (ownership) plus global order (reverse teardown across plugins). Process-
  1048. # global registries are shared across profiles while several managers coexist, so the ledger
  1049. # is keyed per (hermes_home, plugin_id) and every inverse is identity-conditional — one
  1050. # profile's unload can never clear another's. Persistent registrations that survived an
  1051. # unload-all park in ``_persistent_carryover`` until force re-discovery evicts the stale ones.
  1052. # Registration handles are kept both per plugin (ownership lookup) and globally (reverse-order
  1053. # teardown for overrides spanning plugins). Registry overlays keyed by scope_key (see
  1054. # tools/registry.py and gateway/platform_registry.py) carry the profile dimension; anything still
  1055. # process-global is guarded by the identity checks. TODO(#64178): extend explicit profile keying to
  1056. # any remaining process-global slots when the symmetric force-reload lands.
  1057. self._ownership_ledger: dict[str, list[PluginRegistration]] = {}
  1058. self._registration_order: list[PluginRegistration] = []
  1059. # Force re-discovery drains this via _evict_stale_persistent_registrations(): entries whose plugin
  1060. # re-registered the same (kind, key) are kept (the upsert rotated them in place), the rest are
  1061. # disposed so a disabled/removed auth plugin's provider does not outlive its plugin (#91701
  1062. # follow-up).
  1063. self._persistent_carryover: list[PluginRegistration] = []
  1064. # Deferred platforms whose client tools registered at discovery (see
  1065. # _register_deferred_platform_tools): imported package (don't re-execute on materialize)
  1066. # and contributed tool names (so `hermes plugins list` still attributes them).
  1067. self._predeclared_modules: dict[str, types.ModuleType] = {}
  1068. self._predeclared_tools: dict[str, list[str]] = {}
  1069. @property
  1070. def has_gateway_message_injector(self) -> bool:
  1071. """Return whether a live gateway can accept plugin-triggered turns."""
  1072. return self._gateway_message_injector is not None
  1073. def set_gateway_message_injector(self, owner: object, injector: Callable[..., bool]) -> None:
  1074. """Publish a live gateway injector and its lifecycle owner."""
  1075. self._gateway_message_injector = (owner, injector)
  1076. def clear_gateway_message_injector(self, owner: object) -> None:
  1077. """Clear the injector only when it still belongs to ``owner``."""
  1078. if self._gateway_message_injector is not None and self._gateway_message_injector[0] is owner:
  1079. self._gateway_message_injector = None
  1080. def inject_gateway_message(self, **kwargs: Any) -> bool:
  1081. """Submit a plugin-triggered turn to the live gateway."""
  1082. registered = self._gateway_message_injector
  1083. return registered is not None and bool(registered[1](**kwargs))
  1084. @property
  1085. def has_tui_message_injector(self) -> bool:
  1086. """Return whether a live Ink TUI / desktop host can accept plugin-triggered turns."""
  1087. return self._tui_message_injector is not None
  1088. def set_tui_message_injector(self, owner: object, injector: Callable[..., bool]) -> None:
  1089. """Publish a live TUI/desktop injector. Does not touch the messaging-gateway slot."""
  1090. self._tui_message_injector = (owner, injector)
  1091. def clear_tui_message_injector(self, owner: object) -> None:
  1092. """Clear the TUI injector only when it still belongs to ``owner``."""
  1093. if self._tui_message_injector is not None and self._tui_message_injector[0] is owner:
  1094. self._tui_message_injector = None
  1095. def inject_tui_message(self, **kwargs: Any) -> bool:
  1096. """Submit a plugin-triggered turn to the live TUI/desktop host."""
  1097. registered = self._tui_message_injector
  1098. return registered is not None and bool(registered[1](**kwargs))
  1099. def discover_and_load(self, force: bool = False) -> None:
  1100. """Scan all plugin sources and load each plugin found; ``force`` unloads first so config
  1101. changes / new bundled backends become visible in long-lived sessions."""
  1102. from agent.safe_worker_policy import safe_worker_enabled
  1103. if safe_worker_enabled() or plugin_discovery_suppressed():
  1104. # Safe workers never discover; a config-only read of a profile this process must not
  1105. # load plugins for is suppressed too.
  1106. return
  1107. if self._discovered and not force and in_plugin_load_worker():
  1108. # A plugin whose register() re-enters discovery (importing model_tools does) runs on a
  1109. # deadline worker that cannot re-acquire the sweep's RLock; the flag is already set for the
  1110. # whole sweep, so return where the locked re-entry used to. Every other caller still waits.
  1111. return
  1112. with self._discovery_lock, _plugin_home_scope(self.home_path):
  1113. if self._discovered and not force:
  1114. return
  1115. # ``on_plugin_loaded`` reports the plugins this sweep loads that the process did not have before
  1116. # (boot: everything; a mid-run install/enable: just the newcomer), keyed on the pre-sweep set.
  1117. loaded_before = frozenset(k for k, p in self._plugins.items() if not p.error and not p.deferred)
  1118. if force:
  1119. self.unload() # the ledger owns teardown of process-global registries
  1120. if env_var_enabled("HERMES_SAFE_MODE"):
  1121. logger.info("HERMES_SAFE_MODE=1 — plugin discovery skipped")
  1122. self._discovered = True
  1123. return
  1124. # Flag set up front as a re-entrancy guard (register() can trigger discovery again) but
  1125. # reset on failure so a failed scan is NOT cached as "discovered with an empty registry"
  1126. # — callers swallow the exception and would be stranded on the early return above.
  1127. self._discovered = True
  1128. try:
  1129. self._discover_and_load_inner()
  1130. # Persistent registrations survived the unload-all; now that plugins re-registered,
  1131. # dispose the ones whose plugin did not come back.
  1132. # Now that plugins have had their chance to re-register, dispose the ones whose plugin did
  1133. # not come back (disabled, removed, or omitted from this discovery pass) so e.g. a disabled
  1134. # auth plugin's provider does not stay live process-wide until restart. See #91701.
  1135. self._evict_stale_persistent_registrations()
  1136. # load_hermes_dotenv() ran at import, before plugin secret sources existed: re-pull.
  1137. # Plugin secret sources register during discover; the initial load_hermes_dotenv() already
  1138. # ran at import time. Re-pull so the first process sees plugin backends (tracking #64177).
  1139. self._refresh_secret_sources_after_discovery()
  1140. if force:
  1141. # config.yaml shell hooks / outbound webhooks live in ``_hooks`` but are
  1142. # config-owned; unload() wiped them and cannot restore them.
  1143. # Re-register so force-reload is symmetric (#60036; tracking #64178 — salvaged from PR
  1144. # #64188; outbound webhooks added per #92682 review).
  1145. self._re_register_config_hooks_after_force()
  1146. except BaseException:
  1147. self._discovered = False
  1148. raise
  1149. # Outside the lock: a listener (the gateway's re-wire) may read the registry from another thread.
  1150. self._notify_plugin_loaded(loaded_before)
  1151. def _re_register_config_hooks_after_force(self) -> None:
  1152. """Restore config-owned shell hooks/outbound webhooks after a force clear; each guarded
  1153. independently so one failing does not skip the other."""
  1154. for label, module_name in (("shell-hook", "agent.shell_hooks"),
  1155. ("outbound-webhook", "agent.outbound_webhooks")):
  1156. try:
  1157. importlib.import_module(module_name).re_register_config_hooks()
  1158. except Exception as exc:
  1159. logger.debug("force-reload %s re-register skipped: %s", label, exc)
  1160. def _refresh_secret_sources_after_discovery(self) -> None:
  1161. """If any plugin secret source is enabled (per its own ``is_enabled(cfg)``, honoring custom
  1162. activation), reset the cache and re-apply. Fail-open: never raises into discover_and_load."""
  1163. try:
  1164. from agent.secret_sources.registry import list_plugin_sources
  1165. from hermes_cli.env_loader import load_hermes_dotenv, reset_secret_source_cache
  1166. plugin_sources = list_plugin_sources()
  1167. except Exception:
  1168. return
  1169. enabled_names: list[str] = []
  1170. if plugin_sources:
  1171. try:
  1172. from hermes_cli.config import load_config
  1173. secrets = (load_config() or {}).get("secrets") or {}
  1174. except Exception:
  1175. secrets = {}
  1176. def _enabled(source) -> bool:
  1177. section = secrets.get(getattr(source, "name", ""))
  1178. try:
  1179. return bool(source.is_enabled(section if isinstance(section, dict) else {}))
  1180. except Exception:
  1181. return False # mirrors the orchestrator: a raising is_enabled() is skipped
  1182. enabled_names = [getattr(s, "name", "") for s in plugin_sources if _enabled(s)]
  1183. if not enabled_names:
  1184. # Nothing enabled now. If an earlier discovery re-applied plugin sources for this home, the
  1185. # snapshot and installed scope still carry that plugin's names (force-reload unloads the
  1186. # registration first, so this is exactly the "last plugin source removed" path) — reconcile
  1187. # once so they drop out. A home that never had one stays a no-op: no re-pull, no re-load.
  1188. if not self._plugin_secret_sources_reconciled:
  1189. return
  1190. # The marker is cleared only AFTER the cleanup below succeeds: reset/reload/refresh are
  1191. # fallible, and clearing first left the stale credential active with no retry on the next
  1192. # discovery (review on f5f88d5058).
  1193. else:
  1194. self._plugin_secret_sources_reconciled = True
  1195. try:
  1196. # Reset and reload the SAME home the process (or routed turn) resolves to: under multiplex this
  1197. # runs at gateway boot after sibling profiles may already have hydrated, and a global clear
  1198. # wiped their snapshots; a routed discovery must rebuild the profile it just dropped.
  1199. from hermes_constants import get_hermes_home
  1200. home = get_hermes_home()
  1201. reset_secret_source_cache(home)
  1202. load_hermes_dotenv(hermes_home=home)
  1203. # A scope installed for this home was frozen BEFORE these sources existed — a routed cron
  1204. # fire builds its scope in run_one_job and only then, on its first agent build, discovers
  1205. # plugins; under multiplex semantics the load above is hydrate-only, so fold the values
  1206. # into the installed scope or THIS fire never sees the plugin credential.
  1207. from agent.secret_scope import refresh_installed_secret_scope
  1208. refresh_installed_secret_scope(Path(home))
  1209. if not enabled_names:
  1210. self._plugin_secret_sources_reconciled = False # cleanup succeeded; nothing left to drop
  1211. logger.debug("Re-applied secret sources after plugin discovery for: %s",
  1212. ", ".join(sorted(enabled_names)) or "<none — reconciled removed plugin sources>")
  1213. except Exception as exc:
  1214. logger.debug("secret source re-apply after discovery failed: %s", exc)
  1215. def _discover_and_load_inner(self) -> None:
  1216. """The actual discovery sweep — see :meth:`discover_and_load`."""
  1217. manifests: list[PluginManifest] = self._collect_directory_manifests()
  1218. # Entry points are separate from the directory scan: the startup MCP probe must not import
  1219. # or register them.
  1220. # An installed directory plugin keeps its identity when its own pip dependency also ships an
  1221. # entry point under the same name (the pyproject wrapper shape): the directory is what the
  1222. # user installed, carries catalog provenance and is what update/remove act on.
  1223. directory_keys = {manifest_key(m) for m in manifests}
  1224. ep_manifests = [m for m in self._scan_entry_points() if manifest_key(m) not in directory_keys]
  1225. logger.debug(" entrypoints: %d manifest(s)", len(ep_manifests))
  1226. manifests.extend(ep_manifests)
  1227. disabled = _get_disabled_plugins()
  1228. enabled = _get_enabled_plugins() # None = opt-in default (nothing enabled)
  1229. stale_relay_keys = legacy_relay_plugin_keys(enabled)
  1230. if stale_relay_keys:
  1231. logger.warning("Removed Hermes plugin %s is still listed in plugins.enabled; "
  1232. "remove it and configure a standard user or system Relay plugins.toml, or use %s "
  1233. "for an explicit user-file override",
  1234. ", ".join(stale_relay_keys), RELAY_PLUGINS_CONFIG_ENV)
  1235. # Later sources win on key collision (project > user > bundled) except a flat impostor claiming a
  1236. # bundled key from another directory (resolve_manifest_winners); gate the winners, then
  1237. # load survivors in requires_plugins order (see resolve_plugin_load_order).
  1238. winners = resolve_manifest_winners(manifests)
  1239. to_load = {k: m for k, m in winners.items() if self._gate_manifest(m, disabled, enabled)}
  1240. for lookup_key in resolve_plugin_load_order(to_load):
  1241. manifest = to_load[lookup_key]
  1242. self._warn_python_dependencies(manifest)
  1243. self._validate_plugin_config_schema(manifest)
  1244. self._load_plugin(manifest)
  1245. if manifests:
  1246. logger.info("Plugin discovery complete: %d found, %d enabled", len(self._plugins),
  1247. sum(1 for p in self._plugins.values() if p.enabled))
  1248. def _gate_manifest(
  1249. self, manifest: PluginManifest, disabled: set[str], enabled: Optional[set[str]],
  1250. ) -> bool:
  1251. """Route one winning manifest per :func:`gate_manifest`: load now, defer, or record as
  1252. skipped (introspection-only placeholder). Returns True only for plugins that go through the
  1253. dependency-ordered load pass."""
  1254. verdict = gate_manifest(manifest, disabled, enabled)
  1255. if verdict.action == "load":
  1256. return True
  1257. if verdict.action == "load_now":
  1258. self._load_plugin(manifest)
  1259. elif verdict.action == "defer":
  1260. self._register_deferred_platform(manifest)
  1261. else:
  1262. self._plugins[manifest_key(manifest)] = LoadedPlugin(
  1263. manifest=manifest, enabled=verdict.enabled, error=verdict.error)
  1264. if verdict.log:
  1265. logger.log(*verdict.log)
  1266. return False
  1267. def register_approval_transport(self, name: str, present_fn: Callable, *, plugin_id: str) -> None:
  1268. """Manager-level registration (public API kept for out-of-tree plugins); the PluginContext
  1269. method is the tracked path plugins normally use. Same validation, no unload tracking."""
  1270. from hermes_cli.approval_transport import RegisteredApprovalTransport
  1271. clean = str(name).strip().lower()
  1272. if clean == "builtin":
  1273. raise ValueError("approval transport name 'builtin' is reserved")
  1274. if not re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,63}", clean):
  1275. raise ValueError("approval transport name must match [a-z0-9][a-z0-9_-]{0,63}")
  1276. if not callable(present_fn):
  1277. raise TypeError("approval transport present_fn must be callable")
  1278. if clean in self._approval_transports:
  1279. owner = self._approval_transports[clean].plugin_id
  1280. raise ValueError(f"approval transport {clean!r} is already registered by {owner!r}")
  1281. self._approval_transports[clean] = RegisteredApprovalTransport(
  1282. name=clean, present=present_fn, plugin_id=plugin_id, profile_home=str(get_hermes_home().resolve()),
  1283. )
  1284. logger.info("Plugin %s registered approval transport: %s", plugin_id, clean)
  1285. def get_approval_transport(self, name: str):
  1286. """Return a transport only inside the profile that registered it."""
  1287. registered = self._approval_transports.get(str(name).strip().lower())
  1288. if registered is None or registered.profile_home != str(get_hermes_home().resolve()):
  1289. return None
  1290. return registered
  1291. def _collect_directory_manifests(self) -> list[PluginManifest]:
  1292. """Directory manifests in full-discovery order (see :func:`collect_directory_manifests`)."""
  1293. return collect_directory_manifests()
  1294. def has_enabled_portable_mcp(self, raw_config: Mapping[str, Any]) -> bool:
  1295. """Probe enabled portable MCP packages without loading plugins (shares the full-discovery
  1296. manifest collection so precedence/gating cannot diverge)."""
  1297. if _env_enabled("HERMES_SAFE_MODE"):
  1298. return False
  1299. plugins_config = raw_config.get("plugins")
  1300. if not isinstance(plugins_config, dict):
  1301. return False
  1302. def _names(value: Any) -> set[str]:
  1303. return {v for v in value if isinstance(v, str)} if isinstance(value, list) else set()
  1304. enabled = _names(plugins_config.get("enabled"))
  1305. disabled = _names(plugins_config.get("disabled", []))
  1306. if not enabled:
  1307. return False
  1308. for lookup_key, manifest in {manifest_key(m): m for m in self._collect_directory_manifests()}.items():
  1309. names = {lookup_key, manifest.name}
  1310. if not manifest.portable or names & disabled or not names & enabled:
  1311. continue
  1312. try: # lazy: this is a startup probe, keep agent_plugins unimported unless needed
  1313. from hermes_cli.agent_plugins import _discover_mcp
  1314. if _discover_mcp(Path(manifest.path), get_hermes_home() / "plugin-data"
  1315. / (manifest.data_namespace or lookup_key), [], create_data=False):
  1316. return True
  1317. except (OSError, RuntimeError, ValueError):
  1318. continue # fail closed on an unreadable package; full discovery reports it
  1319. return False
  1320. def _scan_directory(
  1321. self, path: Path, source: str, skip_names: Optional[set[str]] = None,
  1322. ) -> list[PluginManifest]:
  1323. """Read manifests under *path* (see :func:`scan_directory`)."""
  1324. return scan_directory(path, source, skip_names=skip_names)
  1325. def _scan_entry_points(self) -> list[PluginManifest]:
  1326. """Read installed plugin entry points (see :func:`discover_entrypoint_manifests`)."""
  1327. return discover_entrypoint_manifests()
  1328. def get_slack_action_handlers(self) -> list[tuple]:
  1329. """``(action_id, callback, plugin_name)`` tuples for the Slack adapter to wire at connect."""
  1330. return list(self._slack_action_handlers)
  1331. def get_platform_handler_factories(self, platform: str) -> list[tuple]:
  1332. """``(factory, plugin_name)`` tuples for one platform; adapters call ``factory(native,
  1333. adapter)`` at connect (see :meth:`PluginContext.register_platform_handler`)."""
  1334. return list(self._platform_handler_factories.get((platform or "").strip().lower(), []))
  1335. def get_telegram_handler_factories(self) -> list[tuple]:
  1336. """Back-compat alias for ``get_platform_handler_factories("telegram")``."""
  1337. return self.get_platform_handler_factories("telegram")
  1338. def list_plugins(self) -> list[dict[str, Any]]:
  1339. """Return a list of info dicts for all discovered plugins."""
  1340. return [
  1341. {
  1342. "name": p.manifest.name, "key": manifest_key(p.manifest), "kind": p.manifest.kind,
  1343. "version": p.manifest.version, "description": p.manifest.description,
  1344. "source": p.manifest.source, "enabled": p.enabled, "tools": len(p.tools_registered),
  1345. "hooks": len(p.hooks_registered), "middleware": len(p.middleware_registered),
  1346. "commands": len(p.commands_registered), "error": p.error,
  1347. } for _key, p in sorted(self._plugins.items())
  1348. ]
  1349. def find_plugin_skill(self, qualified_name: str) -> Optional[Path]:
  1350. """Return the ``Path`` to a plugin skill's SKILL.md, or ``None``."""
  1351. entry = self._plugin_skills.get(qualified_name)
  1352. return entry["path"] if entry else None
  1353. def list_plugin_skills(self, plugin_name: str) -> list[str]:
  1354. """Return sorted bare names of all skills registered by *plugin_name*."""
  1355. prefix = f"{plugin_name}:"
  1356. return sorted(e["bare_name"] for qn, e in self._plugin_skills.items() if qn.startswith(prefix))
  1357. def list_plugin_skill_metadata(self) -> list[dict[str, Any]]:
  1358. """Return progressive-disclosure metadata for registered plugin skills."""
  1359. return [
  1360. {
  1361. "name": qualified, "description": str(entry.get("description", "")),
  1362. "category": "plugin", "frontmatter": dict(entry.get("frontmatter", {})),
  1363. } for qualified, entry in sorted(self._plugin_skills.items())
  1364. ]
  1365. def list_automation_blueprints(self) -> list[Any]:
  1366. """Plugin-registered ``AutomationBlueprint``s, sorted by key."""
  1367. return [bp for _key, bp in sorted(self._automation_blueprints.items())]
  1368. def has_portable_mcp_servers(self) -> bool:
  1369. return bool(self._portable_mcp_servers)
  1370. def get_portable_mcp_servers(self) -> dict[str, dict[str, Any]]:
  1371. """Return a defensive copy of enabled portable MCP server configs."""
  1372. return {name: dict(config) for name, config in self._portable_mcp_servers.items()}
  1373. def get_portable_mcp_server_plugins(self) -> dict[str, str]:
  1374. return dict(self._portable_mcp_server_plugins)
  1375. def remove_plugin_skill(self, qualified_name: str) -> None:
  1376. """Remove a stale registry entry (silently ignores missing keys)."""
  1377. self._plugin_skills.pop(qualified_name, None)
  1378. # Module-level singleton & convenience functions.
  1379. # Legacy single-slot "current" manager, kept so tests that monkeypatch ``_plugin_manager`` keep
  1380. # working — ``get_plugin_manager()`` still reads/writes this name.
  1381. _plugin_manager: Optional[PluginManager] = None
  1382. # Resolved Hermes home -> PluginManager. A process can switch profiles via
  1383. # ``set_hermes_home_override()``; a single slot would leak one profile's plugin/context-engine state
  1384. # into another, and keying by resolved home lets a re-entered profile reuse its imported modules.
  1385. _plugin_managers_by_home: dict[Path, PluginManager] = {}
  1386. _plugin_managers_lock = threading.RLock()
  1387. # Process-wide messaging-gateway host. A multiplexed gateway owns one scheduler while plugins are
  1388. # isolated in per-profile managers, so every manager in this process must see the same live host.
  1389. _published_gateway_message_injector: tuple[object, Callable] | None = None
  1390. _published_gateway_host_lock = threading.Lock()
  1391. # Process-wide Ink TUI / desktop host. Not the messaging-gateway slot. Stamped onto
  1392. # each profile's manager so a multiplexed desktop process does not drop injects
  1393. # aimed at a non-launch profile. ``None`` until the TUI/desktop process installs it.
  1394. _published_tui_message_injector: tuple[object, Callable] | None = None
  1395. _published_tui_host_lock = threading.Lock()
  1396. def _plugin_home_key() -> Path:
  1397. """Resolved active Hermes home — the key for per-profile plugin managers (plugins capture the
  1398. home at registration, so a process serving several profiles cannot share one manager)."""
  1399. try:
  1400. return get_hermes_home().expanduser().resolve()
  1401. except Exception:
  1402. return get_hermes_home().expanduser()
  1403. def _clear_plugin_submodules(manager: Optional[PluginManager]) -> None:
  1404. """Purge ``sys.modules`` entries for this manager's directory plugins (package AND submodules —
  1405. otherwise a same-slug plugin in another profile reuses the previous profile's submodule state).
  1406. """
  1407. if manager is None:
  1408. return
  1409. for loaded in getattr(manager, "_plugins", {}).values(): # tolerates test-double managers
  1410. module_name = getattr(getattr(loaded, "module", None), "__name__", None)
  1411. if not module_name or not module_name.startswith(f"{_NS_PARENT}."):
  1412. continue
  1413. _evict_modules(module_name)
  1414. with _MODULE_NAMESPACE_LOCK:
  1415. if _BARE_MODULE_SCOPE.get(module_name) == manager.scope_key:
  1416. _BARE_MODULE_SCOPE.pop(module_name, None)
  1417. def _known_plugin_managers() -> list[PluginManager]:
  1418. with _plugin_managers_lock:
  1419. managers = list(dict.fromkeys(_plugin_managers_by_home.values()))
  1420. if _plugin_manager is not None and _plugin_manager not in managers:
  1421. managers.append(_plugin_manager)
  1422. return managers
  1423. def publish_gateway_message_host(owner: object, injector: Callable[..., bool]) -> None:
  1424. """Remember the process gateway host and stamp managers that already exist."""
  1425. global _published_gateway_message_injector
  1426. # Keep publication + stamping atomic with owner-safe clear. Managers created concurrently are
  1427. # registered before _attach_published_gateway_host(), which takes this same lock.
  1428. with _published_gateway_host_lock:
  1429. _published_gateway_message_injector = (owner, injector)
  1430. for manager in _known_plugin_managers():
  1431. manager.set_gateway_message_injector(owner, injector)
  1432. def clear_published_gateway_message_host(owner: object) -> None:
  1433. """Forget this owner's process gateway host without clobbering a newer runner."""
  1434. global _published_gateway_message_injector
  1435. with _published_gateway_host_lock:
  1436. if (_published_gateway_message_injector is not None
  1437. and _published_gateway_message_injector[0] is owner):
  1438. _published_gateway_message_injector = None
  1439. for manager in _known_plugin_managers():
  1440. manager.clear_gateway_message_injector(owner)
  1441. def _attach_published_gateway_host(manager: PluginManager) -> None:
  1442. """Give a newly resolved profile manager the live process gateway host, if any."""
  1443. with _published_gateway_host_lock:
  1444. host = _published_gateway_message_injector
  1445. if host is not None and manager._gateway_message_injector is None:
  1446. manager.set_gateway_message_injector(*host)
  1447. def publish_tui_message_host(owner: object, injector: Callable[..., bool]) -> None:
  1448. """Remember the process TUI/desktop host and stamp managers that already exist.
  1449. Does not call ``set_gateway_message_injector``.
  1450. """
  1451. global _published_tui_message_injector
  1452. with _published_tui_host_lock:
  1453. _published_tui_message_injector = (owner, injector)
  1454. for manager in _known_plugin_managers():
  1455. manager.set_tui_message_injector(owner, injector)
  1456. def clear_published_tui_message_host(owner: object) -> None:
  1457. """Forget the process TUI host and clear it where this owner still holds the slot."""
  1458. global _published_tui_message_injector
  1459. with _published_tui_host_lock:
  1460. if (_published_tui_message_injector is not None
  1461. and _published_tui_message_injector[0] is owner):
  1462. _published_tui_message_injector = None
  1463. for manager in _known_plugin_managers():
  1464. manager.clear_tui_message_injector(owner)
  1465. def _attach_published_tui_host(manager: PluginManager) -> None:
  1466. """Give a newly resolved manager the process TUI host, if one is installed and the slot is empty."""
  1467. with _published_tui_host_lock:
  1468. host = _published_tui_message_injector
  1469. if host is not None and manager._tui_message_injector is None:
  1470. manager._tui_message_injector = host
  1471. def get_plugin_manager() -> PluginManager:
  1472. """Return the plugin manager for the active Hermes profile/home (cached per resolved home; a
  1473. profile switch gets its own manager and plugin submodules)."""
  1474. global _plugin_manager
  1475. current_home = _plugin_home_key()
  1476. with _plugin_managers_lock:
  1477. # Tests/embedders monkeypatch ``_plugin_manager`` directly: adopt a single-slot manager the
  1478. # keyed cache doesn't know about at all.
  1479. if _plugin_manager is not None and _plugin_manager not in _plugin_managers_by_home.values():
  1480. _plugin_managers_by_home[current_home] = _plugin_manager
  1481. manager = _plugin_manager
  1482. else:
  1483. manager = _plugin_managers_by_home.get(current_home)
  1484. if manager is None:
  1485. manager = PluginManager(scope_key=hermes_home_key(current_home))
  1486. _plugin_managers_by_home[current_home] = manager
  1487. _plugin_manager = manager
  1488. _attach_published_gateway_host(manager)
  1489. _attach_published_tui_host(manager)
  1490. return manager
  1491. def _reset_plugin_managers_for_tests() -> None:
  1492. """Test-only: drop every cached manager and its submodules for a fully clean slate."""
  1493. global _plugin_manager, _published_gateway_message_injector, _published_tui_message_injector
  1494. with _plugin_managers_lock:
  1495. managers = list(dict.fromkeys(_plugin_managers_by_home.values()))
  1496. if _plugin_manager is not None and _plugin_manager not in managers:
  1497. managers.append(_plugin_manager)
  1498. for manager in managers:
  1499. _clear_plugin_submodules(manager)
  1500. try:
  1501. manager.unload()
  1502. except Exception:
  1503. logger.debug("test plugin-manager unload failed", exc_info=True)
  1504. _plugin_managers_by_home.clear()
  1505. _plugin_manager = None
  1506. with _published_gateway_host_lock:
  1507. _published_gateway_message_injector = None
  1508. with _published_tui_host_lock:
  1509. _published_tui_message_injector = None
  1510. # Dashboard-auth providers are persistent and survive a routine unload, so the clean-slate
  1511. # reset must clear that process-global registry explicitly or a test's provider leaks.
  1512. try:
  1513. from hermes_cli.dashboard_auth.registry import clear_providers
  1514. clear_providers()
  1515. except Exception:
  1516. logger.debug("dashboard-auth registry clear failed", exc_info=True)
  1517. def has_enabled_agent_plugin_mcp(raw_config: Mapping[str, Any]) -> bool:
  1518. """Whether config enables a portable package with MCP servers (manifest-only scan on a fresh
  1519. manager; imports nothing, mutates no registry)."""
  1520. return PluginManager().has_enabled_portable_mcp(raw_config)
  1521. def discover_plugins(force: bool = False) -> None:
  1522. """Discover and load all plugins (idempotent; ``force=True`` rescans). Joins an in-flight
  1523. background discovery instead of racing a second scan."""
  1524. from agent.safe_worker_policy import safe_worker_enabled
  1525. if safe_worker_enabled():
  1526. return
  1527. _join_background_discovery()
  1528. get_plugin_manager().discover_and_load(force=force)
  1529. _background_discovery_thread: Optional[threading.Thread] = None
  1530. _background_discovery_lock = threading.Lock()
  1531. def start_background_plugin_discovery() -> None:
  1532. """Run discovery in a daemon thread to overlap the rest of CLI startup (~150ms). Every
  1533. synchronous consumer joins it via :func:`discover_plugins`, so no one sees a half-loaded
  1534. registry. No-op when already done or in flight."""
  1535. from agent.safe_worker_policy import safe_worker_enabled
  1536. if safe_worker_enabled():
  1537. return
  1538. global _background_discovery_thread
  1539. manager = get_plugin_manager()
  1540. if manager._discovered:
  1541. return
  1542. with _background_discovery_lock:
  1543. if _background_discovery_thread is not None and _background_discovery_thread.is_alive():
  1544. return
  1545. def _run() -> None:
  1546. try:
  1547. manager.discover_and_load()
  1548. _persist_plugin_toolset_keys()
  1549. except Exception:
  1550. logger.warning("background plugin discovery failed", exc_info=True)
  1551. _background_discovery_thread = threading.Thread(target=_run, name="plugin-discovery", daemon=True)
  1552. _background_discovery_thread.start()
  1553. def _join_background_discovery(timeout: float = 30.0) -> None:
  1554. """Wait for an in-flight background discovery (no-op from its own thread or a plugin-load worker it
  1555. spawned — that worker's parent is blocked waiting on it)."""
  1556. t = _background_discovery_thread
  1557. if t is None or not t.is_alive() or t is threading.current_thread() or in_plugin_load_worker():
  1558. return
  1559. t.join(timeout=timeout)
  1560. def _plugin_toolset_keys_cache_path() -> Path:
  1561. return get_hermes_home() / "cache" / "plugin_toolset_keys.json"
  1562. def _persist_plugin_toolset_keys() -> None:
  1563. """Persist discovered plugin toolset keys + portable MCP names (best-effort)."""
  1564. try:
  1565. from utils import atomic_json_write
  1566. keys = sorted({ts_key for ts_key, _, _ in get_plugin_toolsets()})
  1567. try:
  1568. portable = sorted(get_plugin_manager().get_portable_mcp_servers())
  1569. except Exception:
  1570. portable = []
  1571. atomic_json_write(_plugin_toolset_keys_cache_path(), {"toolset_keys": keys, "portable_mcp": portable}, indent=None, mode=0o600)
  1572. except Exception:
  1573. logger.debug("plugin toolset key persist failed", exc_info=True)
  1574. def _nowait_plugin_set(cache_field: str, live: Callable[[PluginManager], set[str]]) -> set[str]:
  1575. """Shared body of the ``*_nowait`` probes: live registry, else last launch's cache, else block."""
  1576. manager = get_plugin_manager()
  1577. t = _background_discovery_thread
  1578. in_flight = t is not None and t.is_alive()
  1579. if manager._discovered and not in_flight:
  1580. return live(manager)
  1581. if in_flight:
  1582. with suppress(Exception):
  1583. blob = json.loads(_plugin_toolset_keys_cache_path().read_text(encoding="utf-8-sig"))
  1584. values = blob.get(cache_field) if isinstance(blob, dict) else None
  1585. if isinstance(values, list) and all(isinstance(v, str) for v in values):
  1586. return set(values)
  1587. discover_plugins()
  1588. return live(manager)
  1589. def get_plugin_toolset_keys_nowait() -> set[str]:
  1590. """Plugin toolset keys without blocking on in-flight discovery: live registry when done, last
  1591. launch's persisted set while a background scan runs (callers only EXCLUDE these keys, so a stale
  1592. set is harmless and self-heals), else block via discover_plugins()."""
  1593. return _nowait_plugin_set("toolset_keys", lambda _m: {ts_key for ts_key, _, _ in get_plugin_toolsets()})
  1594. def get_portable_mcp_server_names_nowait() -> set[str]:
  1595. """Portable MCP server names; same contract as :func:`get_plugin_toolset_keys_nowait`."""
  1596. return _nowait_plugin_set("portable_mcp", lambda m: set(m.get_portable_mcp_servers()))
  1597. def _delivery_manager() -> PluginManager:
  1598. """Active manager, lazily discovering if it never ran — delivery must not depend on WHICH
  1599. surface imported us (dashboards/TUI/cron never import model_tools). ``getattr`` default
  1600. ``True`` leaves test doubles untouched.
  1601. Hook/middleware delivery must not depend on WHICH surface imported us: dashboards, TUI slash workers,
  1602. query mode, and cron delivery paths never import ``model_tools`` (whose import side-effect is the
  1603. discovery trigger on the interactive CLI path), so hooks registered by user plugins were silently dead
  1604. on those surfaces (#50776, #67597, #67890, #50937; tracking #64178 — salvaged from PR #64188).
  1605. """
  1606. manager = get_plugin_manager()
  1607. if not getattr(manager, "_discovered", True):
  1608. _join_background_discovery()
  1609. manager.discover_and_load()
  1610. return manager
  1611. def invoke_hook(hook_name: str, **kwargs: Any) -> list[Any]:
  1612. """Invoke a lifecycle hook (lazy-discovers first); return non-``None`` callback results.
  1613. Hot-path / observer hooks in ``_HOOK_TIMEOUT_BOUNDED_HOOKS`` and the policy hook ``pre_tool_call`` are
  1614. bounded by ``plugins.hook_callback_timeout`` (default 30s). On timeout the worker is abandoned (not
  1615. joined) so we do not reintroduce the #6622 hang. Timed-out or still-running ``pre_tool_call`` callbacks
  1616. fail closed with a block directive; other bounded hooks fail open (skip).
  1617. Ensures plugins are discovered on first invocation so callers in processes that never explicitly call
  1618. ``discover_plugins()`` (gateway platform events, TUI slash workers, query mode, cron) still fire
  1619. callbacks registered by user plugins (tracking #64178).
  1620. """
  1621. return _delivery_manager().invoke_hook(hook_name, **kwargs)
  1622. async def ainvoke_hook(hook_name: str, **kwargs: Any) -> list[Any]:
  1623. """:func:`invoke_hook` for callers on an event loop: ``async def`` callbacks are awaited
  1624. there instead of bridged through a helper thread (see ``PluginManager.ainvoke_hook``)."""
  1625. return await _delivery_manager().ainvoke_hook(hook_name, **kwargs)
  1626. def render_system_prompt_sections(session_info: Mapping[str, Any]) -> list[RenderedPluginSystemPromptSection]:
  1627. """Render plugin prompt sections after idempotent plugin discovery."""
  1628. return _ensure_plugins_discovered().render_system_prompt_sections(session_info)
  1629. def invoke_middleware(kind: str, **kwargs: Any) -> list[Any]:
  1630. """Invoke registered middleware callbacks (lazy-discovers like :func:`invoke_hook`).
  1631. Lazy-discovers plugins on first use — same delivery-parity guarantee as :func:`invoke_hook` (tracking
  1632. #64178).
  1633. """
  1634. return _delivery_manager().invoke_middleware(kind, **kwargs)
  1635. def has_middleware(kind: str) -> bool:
  1636. """True when middleware is registered for ``kind``; lazy-discovers first since callers gate
  1637. :func:`invoke_middleware` on it.
  1638. Lazy-discovers first: callers use this as a gate before :func:`invoke_middleware`, so a pre-discovery
  1639. ``False`` here would silently skip delivery on surfaces that never ran discovery (#64178).
  1640. """
  1641. manager = _delivery_manager()
  1642. method = getattr(manager, "has_middleware", None)
  1643. if callable(method):
  1644. return bool(method(kind))
  1645. return bool(getattr(manager, "_middleware", {}).get(kind))
  1646. def has_hook(hook_name: str) -> bool:
  1647. """True when a loaded plugin handles a hook (lazy-discovers first, like :func:`has_middleware`).
  1648. Lazy-discovers first — same gate-before-invoke rationale as :func:`has_middleware` (tracking #64178).
  1649. """
  1650. return _delivery_manager().has_hook(hook_name)
  1651. def iter_hook_callbacks(hook_name: str) -> tuple[Callable, ...]:
  1652. """Return a stable snapshot of callbacks registered for a hook."""
  1653. return get_plugin_manager().iter_hook_callbacks(hook_name)
  1654. def fire_pre_command_hook(
  1655. *, surface: str, command: str, alias_used: str, args_raw: str,
  1656. session_key: Optional[str] = None, platform: Optional[str] = None,
  1657. ) -> None:
  1658. """Fire the observer-only ``pre_command`` hook; never raises. Directive-shaped returns are
  1659. logged at debug so future block/rewrite adopters are discoverable."""
  1660. try:
  1661. manager = get_plugin_manager()
  1662. if not manager.has_hook("pre_command"):
  1663. return
  1664. results = manager.invoke_hook(
  1665. "pre_command", surface=surface, command=command, alias_used=alias_used,
  1666. args_raw=args_raw, session_key=session_key, platform=platform,
  1667. )
  1668. for result in results:
  1669. if isinstance(result, dict) and ("action" in result or "decision" in result):
  1670. logger.debug("pre_command is observer-only in v1: ignoring directive %r for /%s (surface=%s). "
  1671. "Block/rewrite will arrive with the command middleware variant (#64204/#64231).",
  1672. result, command, surface)
  1673. except Exception as exc: # pragma: no cover - defensive
  1674. logger.debug("pre_command hook dispatch failed (non-fatal): %s", exc)
  1675. _thread_tool_whitelist = threading.local()
  1676. @dataclass(frozen=True)
  1677. class _PreToolCallDirective:
  1678. action: Optional[str] = None
  1679. message: Optional[str] = None
  1680. rule_key: Optional[str] = None
  1681. modified_args: Optional[dict[str, Any]] = None
  1682. def set_thread_tool_whitelist(
  1683. allowed: Optional[set[str]],
  1684. deny_msg_fmt: str = "Tool '{tool_name}' denied: not in this thread's tool whitelist",
  1685. ) -> None:
  1686. _thread_tool_whitelist.allowed = allowed
  1687. _thread_tool_whitelist.fmt = deny_msg_fmt
  1688. def clear_thread_tool_whitelist() -> None:
  1689. _thread_tool_whitelist.allowed = None
  1690. def _get_pre_tool_call_directive_details(
  1691. tool_name: str, args: Optional[dict[str, Any]], task_id: str = "", session_id: str = "",
  1692. tool_call_id: str = "", turn_id: str = "", api_request_id: str = "",
  1693. middleware_trace: Optional[list[dict[str, Any]]] = None,
  1694. ) -> _PreToolCallDirective:
  1695. """Check ``pre_tool_call`` hooks for ``{"action": "block", "message"}`` (veto; message becomes
  1696. the tool result) or ``{"action": "approve", "message", "rule_key"?}`` (escalate ANY tool to the
  1697. human-approval gate; ``rule_key`` picks the ``[a]lways`` allowlist grain). Precedence is
  1698. ``block`` > ``approve`` > none, not registration order: any plugin's valid veto wins over an
  1699. earlier plugin's request for human confirmation (#87420); among approves the first valid one
  1700. wins. Irrelevant returns are ignored."""
  1701. allowed = getattr(_thread_tool_whitelist, "allowed", None)
  1702. if allowed is not None and tool_name not in allowed:
  1703. fmt = getattr(_thread_tool_whitelist, "fmt", "Tool '{tool_name}' denied")
  1704. return _PreToolCallDirective(action="block", message=fmt.format(tool_name=tool_name))
  1705. from hermes_cli.lifecycle import invoke_hook as invoke_lifecycle_hook
  1706. hook_results = invoke_lifecycle_hook(
  1707. "pre_tool_call", tool_name=tool_name, args=args if isinstance(args, dict) else {},
  1708. task_id=task_id, session_id=session_id, tool_call_id=tool_call_id, turn_id=turn_id,
  1709. api_request_id=api_request_id, middleware_trace=list(middleware_trace or []),
  1710. )
  1711. modified_args: Optional[dict[str, Any]] = None
  1712. first_approve: Optional[tuple[Optional[str], Optional[str]]] = None # (message, rule_key)
  1713. for result in hook_results:
  1714. if not isinstance(result, dict):
  1715. continue
  1716. action = result.get("action")
  1717. # "modify" — transform tool_input before dispatch. Processed before the block/approve gate
  1718. # so modify directives are visible even when a later hook blocks. Each modify directive
  1719. # shallow-merges its keys into one accumulated dict built from the original args.
  1720. if action == "modify":
  1721. partial = result.get("args")
  1722. if isinstance(partial, dict) and partial:
  1723. modified_args = {**(modified_args if modified_args is not None else
  1724. (args if isinstance(args, dict) else {})), **partial}
  1725. continue
  1726. if action not in ("block", "approve"):
  1727. continue
  1728. message = result.get("message")
  1729. message = message if isinstance(message, str) and message else None
  1730. # A block directive requires a message (it becomes the tool result); approve's is optional.
  1731. if action == "block" and not message:
  1732. continue
  1733. if action == "block":
  1734. return _PreToolCallDirective(action="block", message=message, modified_args=modified_args)
  1735. # approve is held back until the whole list has been scanned for a veto.
  1736. if first_approve is None:
  1737. rule_key = result.get("rule_key")
  1738. first_approve = (message, (rule_key.strip() or None) if isinstance(rule_key, str) else None)
  1739. if first_approve is not None:
  1740. return _PreToolCallDirective(action="approve", message=first_approve[0], rule_key=first_approve[1],
  1741. modified_args=modified_args)
  1742. return _PreToolCallDirective(modified_args=modified_args)
  1743. def get_pre_tool_call_directive(
  1744. tool_name: str, args: Optional[dict[str, Any]], **hook_kwargs: Any
  1745. ) -> tuple[Optional[str], Optional[str]]:
  1746. """Back-compat: ``(directive, message)`` with directive ``"block"`` / ``"approve"`` / ``None``.
  1747. ``hook_kwargs`` are the observability ids of :func:`_get_pre_tool_call_directive_details`."""
  1748. details = _get_pre_tool_call_directive_details(tool_name, args, **hook_kwargs)
  1749. return (details.action, details.message)
  1750. def get_pre_tool_call_block_message(
  1751. tool_name: str, args: Optional[dict[str, Any]], **hook_kwargs: Any
  1752. ) -> Optional[str]:
  1753. """Deprecated shim: only the ``block`` message (or ``None``); ``approve`` is invisible here."""
  1754. directive, message = get_pre_tool_call_directive(tool_name, args, **hook_kwargs)
  1755. return message if directive == "block" else None
  1756. def resolve_pre_tool_block(
  1757. tool_name: str, args: Optional[dict[str, Any]], **hook_kwargs: Any
  1758. ) -> Optional[str]:
  1759. """Resolve the pre_tool_call directive to a final block message (or ``None`` to proceed),
  1760. running the human-approval gate for ``approve``. See :func:`_resolve_block_from_details`."""
  1761. return _dispatch_pre_tool_call_hooks(tool_name, args, **hook_kwargs)[0]
  1762. def _resolve_block_from_details(
  1763. details: _PreToolCallDirective, tool_name: str, *, turn_id: str = "", tool_call_id: str = "",
  1764. session_id: str = "",
  1765. ) -> Optional[str]:
  1766. """The ONE place for the fail-closed approval logic: ``block`` blocks with its message; an
  1767. ``approve`` whose gate errors, denies, or times out is blocked; anything else proceeds."""
  1768. if details.action == "block":
  1769. return details.message
  1770. if details.action != "approve":
  1771. return None
  1772. try:
  1773. from tools.approval import request_tool_approval
  1774. from tools.approval_context import reset_current_observability_context, set_current_observability_context
  1775. approval_tokens = None
  1776. with suppress(Exception):
  1777. approval_tokens = set_current_observability_context(
  1778. turn_id=turn_id, tool_call_id=tool_call_id, session_id=session_id)
  1779. try:
  1780. result = request_tool_approval(tool_name, details.message or "", rule_key=details.rule_key or tool_name)
  1781. finally:
  1782. if approval_tokens is not None:
  1783. with suppress(Exception):
  1784. reset_current_observability_context(approval_tokens)
  1785. except Exception:
  1786. # Fail-closed: if the gate itself errors, block rather than silently execute an action a
  1787. # plugin flagged for approval.
  1788. return f"BLOCKED: plugin approval gate failed for {tool_name}"
  1789. if not result.get("approved"):
  1790. return str(result.get("message") or f"BLOCKED: plugin approval required for {tool_name}")
  1791. return None
  1792. def _dispatch_pre_tool_call_hooks(
  1793. tool_name: str, args: Optional[dict[str, Any]], **hook_kwargs: Any
  1794. ) -> tuple[Optional[str], Optional[dict[str, Any]]]:
  1795. """Invoke ``pre_tool_call`` hooks once; return ``(block_message, modified_args)`` — the resolved
  1796. block/approve message (``None`` to proceed) and merged ``modify`` args (``None`` if none)."""
  1797. details = _get_pre_tool_call_directive_details(tool_name, args, **hook_kwargs)
  1798. block_msg = _resolve_block_from_details(
  1799. details, tool_name, **{k: hook_kwargs.get(k, "") for k in ("turn_id", "tool_call_id", "session_id")})
  1800. return (block_msg, details.modified_args)
  1801. def get_pre_verify_continue_message(
  1802. *, session_id: str = "", platform: str = "", model: str = "", coding: bool = False,
  1803. attempt: int = 0, final_response: str = "", changed_paths: Optional[list[str]] = None,
  1804. ) -> Optional[str]:
  1805. """Check ``pre_verify`` hooks for ``{"action": "continue", "message"}`` (or Claude-Code Stop
  1806. ``{"decision": "block", "reason"}``) to keep the turn going; first non-empty message wins, any
  1807. other return lets the turn finish. ``coding``/``attempt`` let hooks scope and self-throttle."""
  1808. hook_results = invoke_hook(
  1809. "pre_verify", session_id=session_id, platform=platform, model=model, coding=coding,
  1810. attempt=attempt, final_response=final_response, changed_paths=list(changed_paths or []),
  1811. )
  1812. for result in hook_results:
  1813. if not isinstance(result, dict):
  1814. continue
  1815. action = str(result.get("action") or result.get("decision") or "").strip().lower()
  1816. message = result.get("message") or result.get("reason")
  1817. if action in ("continue", "block") and isinstance(message, str) and message.strip():
  1818. return message.strip()
  1819. return None
  1820. def get_plugin_error_classification(
  1821. *, provider: str = "", model: str = "", status_code: Optional[int] = None, error_type: str = "",
  1822. error_code: str = "", error_message: str = "", error_body: Optional[dict[str, Any]] = None,
  1823. error: Optional[BaseException] = None, approx_tokens: int = 0, context_length: int = 0,
  1824. num_messages: int = 0,
  1825. ) -> Optional[dict[str, Any]]:
  1826. """Consult ``transform_api_error_classification`` hooks BEFORE the built-in classifier.
  1827. Run-all-then-pick-first: the first valid result in registration order wins, losing valid results
  1828. warn (conflicts visible, not shadowed). Returns a sanitized dict (``reason`` -> ``FailoverReason``,
  1829. hint flags -> bool, ``message`` capped at 500) or ``None``. Privacy: inputs may be unredacted.
  1830. A callback returns ``None`` to decline, or a dict with a required ``"reason"`` (a
  1831. :class:`agent.error_classifier.FailoverReason` member or its string name) plus optional recovery-hint
  1832. overrides. Dispatch is run-all-then-pick-first: ``invoke_hook`` runs every registered callback with
  1833. failures isolated, then the first result carrying a valid reason wins in registration order — mirroring
  1834. :func:`get_pre_tool_call_block_message`, invalid or irrelevant returns are silently ignored so a
  1835. misbehaving plugin degrades to a no-op. When more than one callback returns a valid classification, the
  1836. losing results are skipped with a runtime warning (the #64714 skipped-transform rule) so conflicting
  1837. provider plugins are visible in logs instead of silently shadowed.
  1838. """
  1839. from agent.error_classifier import FailoverReason
  1840. hook_results = invoke_hook(
  1841. "transform_api_error_classification", provider=provider, model=model,
  1842. status_code=status_code, error_type=error_type, error_code=error_code,
  1843. error_message=error_message, error_body=error_body if isinstance(error_body, dict) else {},
  1844. error=error, approx_tokens=approx_tokens, context_length=context_length,
  1845. num_messages=num_messages,
  1846. )
  1847. def _reason(result: Any) -> Any:
  1848. reason = result.get("reason") if isinstance(result, dict) else None
  1849. if isinstance(reason, str):
  1850. with suppress(ValueError):
  1851. return FailoverReason(reason.strip().lower())
  1852. return None
  1853. return reason if isinstance(reason, FailoverReason) else None
  1854. valid = [(result, reason) for result in hook_results if (reason := _reason(result)) is not None]
  1855. if not valid:
  1856. return None
  1857. result, reason = valid[0]
  1858. winner: dict[str, Any] = {"reason": reason}
  1859. for key in ("retryable", "should_compress", "should_rotate_credential", "should_fallback"):
  1860. if key in result:
  1861. winner[key] = bool(result[key])
  1862. message = result.get("message")
  1863. if isinstance(message, str) and message.strip():
  1864. winner["message"] = message.strip()[:500]
  1865. if isinstance(result.get("error_context"), dict):
  1866. winner["error_context"] = result["error_context"]
  1867. if len(valid) > 1:
  1868. logger.warning("transform_api_error_classification: skipped %d valid classification(s) after the "
  1869. "first result in registration order won (run-all-then-pick-first)", len(valid) - 1)
  1870. return winner
  1871. def _ensure_plugins_discovered(force: bool = False) -> PluginManager:
  1872. """Return the global manager after idempotent (or ``force``d) discovery."""
  1873. manager = get_plugin_manager()
  1874. manager.discover_and_load(force=force)
  1875. return manager
  1876. def get_plugin_context_engine():
  1877. """Return the plugin-registered context engine, or None."""
  1878. return _ensure_plugins_discovered()._context_engine
  1879. def get_plugin_command_handler(name: str) -> Optional[Callable]:
  1880. """Return the handler for a plugin-registered slash command, or ``None``."""
  1881. entry = _ensure_plugins_discovered()._plugin_commands.get(name)
  1882. return entry["handler"] if entry else None
  1883. def get_plugin_commands() -> dict[str, dict]:
  1884. """Plugin commands dict (name -> {handler, description, plugin}) after idempotent discovery."""
  1885. return _ensure_plugins_discovered()._plugin_commands
  1886. def get_plugin_auxiliary_tasks() -> list[dict[str, Any]]:
  1887. """Plugin auxiliary-task registration dicts sorted by ``key`` (after idempotent discovery)."""
  1888. manager = _ensure_plugins_discovered()
  1889. return [manager._aux_tasks[k] for k in sorted(manager._aux_tasks)]
  1890. def get_plugin_toolsets() -> list[tuple]:
  1891. """Plugin toolsets as ``(key, label, description)`` tuples for the ``hermes tools`` TUI."""
  1892. manager = get_plugin_manager()
  1893. if not manager._plugin_tool_names:
  1894. return []
  1895. try:
  1896. from tools.registry import registry
  1897. except Exception:
  1898. return []
  1899. # Group plugin tool names by their toolset, then map each toolset back to the plugin that
  1900. # registered it (first owner wins) for the description.
  1901. toolset_tools: dict[str, list[str]] = {}
  1902. for tool_name in manager._plugin_tool_names:
  1903. entry = registry.get_entry(tool_name)
  1904. if entry:
  1905. toolset_tools.setdefault(entry.toolset, []).append(entry.name)
  1906. toolset_plugin: dict[str, LoadedPlugin] = {}
  1907. for loaded in manager._plugins.values():
  1908. for tool_name in loaded.tools_registered:
  1909. entry = registry.get_entry(tool_name)
  1910. if entry and entry.toolset in toolset_tools:
  1911. toolset_plugin.setdefault(entry.toolset, loaded)
  1912. result = []
  1913. for ts_key in sorted(toolset_tools):
  1914. plugin = toolset_plugin.get(ts_key)
  1915. desc = (plugin.manifest.description if plugin else "") or ", ".join(sorted(toolset_tools[ts_key]))
  1916. result.append((ts_key, f"🔌 {ts_key.replace('_', ' ').title()}", desc))
  1917. return result