Files
hermes-agent/hermes_cli/plugins_loader.py
Teknium 9bcbe7b5df feat(i18n): pluggable, layered language packs across core, Desktop and TUI (#126296)
* feat(i18n): layered catalogs — plugin packs and user overlay over bundled locales

* feat(tui): i18n layer — en catalog, nanostore runtime, RPC pack loader, _keys.tui.json emitter

ui-tui/src/i18n/: en.ts (facade over topical siblings under en/), types.ts
(Translations + dotted TranslationKey derived from en), runtime.ts ($locale/
$catalog atoms, translateFrom active→en→key, pack merge with string→fn
wrapping for {0}/{1} placeholders), loader.ts (display.language →
i18n.catalog {lang, surface:'tui'}, English when the method is missing),
useT()/useLocale() hooks, t() for non-React code. useConfigSync feeds the
loader from the existing config.get full hydration. `npm run i18n:keys`
writes locales/_keys.tui.json (sorted flat key list) and runs before build.

* feat(plugins): provides_locales manifest field, ctx.register_locale/register_locale_dir, manifest-only language packs

* chore(tui): split en catalog siblings by lane (slash sibling)

* feat(plugins): validate language packs — parse, text-only, key-subset WARN against en / _keys exports

* feat(tui_gateway): i18n.languages / i18n.catalog RPC + regenerated contracts

* feat(config): display.language accepts any supported_languages() id, refuses unknown ids with the list

* docs(i18n): language packs user guide, pluggable display.language, plugin developer section, AGENTS notes

* feat(plugins): report language-pack layers in the mid-run activation summary

* feat(tui): wire status bar, composer placeholders, hotkey help and approval/clarify/confirm prompts through i18n

StatusRule maps compared state values (ready/running…/summoning) to catalog
text at render via displayStatus(); hotkeys()/placeholder() resolve lazily so
a pack that arrives after boot applies. Catalog grows to 81 keys.

* feat(desktop): pluggable app locales — registry, host.i18n.registerAppLocale, backend packs, keys emitter

- Locale widens to string (BundledLocale keeps the union); TRANSLATIONS stays
  the bundled record and every consumer resolves through the registry.
- src/i18n/registry.ts: registerAppLocale(id, {endonym, rtl, translations})
  layers partial packs (nested or flat dotted) over bundled/en via
  mergeTranslations; a string over a function-valued en entry becomes a
  positional {0}/{1} formatter; $appLocaleVersion bumps so translators
  re-render; per-source disposers + replaceAppLocaleSource for atomic swaps.
- Backend packs: i18n.languages + i18n.catalog {surface:'desktop'} feed the
  registry as source 'backend' (method-not-found is silent); re-synced on
  socket open, display.language change and profile switch. A saved pack-only
  language is promoted once its pack registers.
- SDK: host.i18n.registerAppLocale / languageOptions; ctx.i18n.registerAppLocale
  tracked for unload. Docs in the desktop plugin SDK guide + skill reference.
- Language switcher lists bundled ∪ registered ∪ backend, endonym-only; RTL
  from the registry (applyDocumentLocale takes rtl).
- npm run i18n:keys emits locales/_keys.desktop.json (wired into build).

* i18n(cli): route /topup + /subscription copy through t() (cli.billing.*, cli.subscription.*)

Module-level copy tables and modal choice tuples in cli_billing_mixin.py froze
English at import, before display.language was known. They are now key tables /
builder functions evaluated at call time; every user-facing line in the /usage
balance block, /subscription and the five /topup screens reads the catalog.
Choice VALUES stay English identifiers. Fragment-assembled status lines
(Plan: … → cancels · $x left · renews …) become full templates.

* i18n(gateway): exec-approval card contract + base/run/run_busy/run_inbound replies through t()

- base_exec_approval: EA_* English constants stay; add ea_header_text()/ea_reason_label_text()/
  ea_smart_deny_line_text()/ea_default_reason_text()/ea_action_labels()/approval_timed_out_notice()
  accessors; deadline + timed-out notice resolve via gateway.exec_approval.*
- BasePlatformAdapter._EA_HEADER/_EA_REASON_LABEL/_EA_SMART_DENY_LINE/_EA_ACTION_LABELS become
  properties (adapters still shadow them with markup class attrs)
- run.py: provider error replies table holds catalog keys; _CONTEXT_OVERFLOW_REPLY -> _context_overflow_reply()
- run_busy/run_inbound: typed approval + slash-confirm matchers accept English ∪ approval.inputs.* (t())
- locales/en.yaml: gateway.exec_approval/busy/errors/... namespaces

* i18n(cli): wire modal, loops, agent-setup mixins through t() (cli.* keys)

* i18n(platforms): route Slack, Matrix and Feishu user-facing text through t()

Exec-approval markup overrides (_EA_HEADER/_EA_REASON_LABEL/_EA_SMART_DENY_LINE/
_EA_ACTION_LABELS) become per-call properties over the shared
gateway.exec_approval.* contract keys, so Slack's 3000-char section budget
measures the resolved template. Slack _APPROVAL_DECISIONS/_CONFIRM_DECISIONS,
Feishu _APPROVAL_LABEL_MAP and Matrix _EA_LEGEND/_EA_TYPED_HINT turn into
key tables resolved at click time; the Matrix typed hints become whole
sentences per offered tier instead of spliced fragments. Slack button labels
are cut to 75 chars and select placeholders to 150 after translation; the
model-facing clarify fallback answer ('choice N') stays English while the
card copy localizes.

locales/en.yaml gains the gateway.exec_approval.* contract keys plus the
platform.shared.* / platform.slack.* / platform.matrix.* / platform.feishu.*
namespaces (and the keys for the other adapters wired in follow-up commits).

* i18n(gateway): run_turn / run_turn_runner / approval-settle copy through t()

- status hints, proxy errors, background task notices, progress heartbeats, session info lines
- tool progress chrome (tool_head/tool_pending/tool_preview/tool_verbose) shared by base.format_tool_event
- run_turn_runner:1406 Chinese clarify placeholder -> gateway.clarify.native_stream_placeholder (zh text kept in zh.yaml)
- _UNEXPECTED_SILENCE_REPLY/_CLARIFY_EXPIRED_NOTICE -> accessor functions

* i18n(platforms): route Google Chat and Teams user-facing text through t()

Google Chat clarify card, typing placeholder, orphan-card labels and the whole
/setup-files reply set (module constants become platform.google_chat.setup_files.*
keys resolved at reply time). The attachment-fallback notice that shipped
hardcoded in Spanish is keyed with an English en value; es.yaml carries the
original Spanish text for those four keys.

Teams approval card header/reason use the gateway.exec_approval.* contract,
_APPROVAL_LABELS becomes a key table resolved at click time, and the meeting
summary writer resolves its section headings/fallbacks per render.

* i18n(platforms): route LINE, WeCom, email, DingTalk, IRC and Home Assistant text through t()

LINE default copy constants become catalog keys resolved in __init__ (the
LINE_*_TEXT / extra.* operator overrides still win); the busy-ack bypass
matcher keys on the leading emoji marker only, so it keeps firing once the
gateway busy heads are localized. WeCom media size/format notices that shipped
hardcoded in Chinese are keyed with English en values and zh.yaml carries the
original Chinese text. DingTalk emotion bubbles resolve per send.

* i18n(cli): route /model switch output and -q status lines through t() (cli.model.*, cli.single_query.*)

Switch-summary labels shared with the gateway reuse gateway.model.* keys
(provider/context/max-output/capabilities/prompt-caching); CLI-only variants
(glyph or no-backtick forms) live under cli.model.*. The hand-padded /model usage
block becomes a (form, description-key) table padded at render time so the
command syntax stays fixed while descriptions translate. -q 'Error:' reuses
gateway.model.error_prefix.

* i18n(cli): route TUI panel/hint/placeholder copy through t() (cli.tui.*)

_APPROVAL_CHOICE_LABELS and _TUI_MODAL_HINTS become key tables resolved at
render time; vault/sudo panel bodies are one catalog value per panel split on
newline; inline plurals use <key>_one/<key>_other. Adds the cli.* namespace
(shared/tui/voice/render/subagents/dock) to locales/en.yaml.

* i18n(cli): voice/wake-word CLI copy through t() (cli.voice.*)

RuntimeError texts raised in _voice_start_recording are human copy (callers
print {e}) and are keyed; the Termux requirement-check match stays English.
Wake state ids stay internal, only their labels localize.

* i18n(cli): live-work dock, subagent monitor and render copy through t()

cli.subagents.* / cli.dock.* / cli.render.*; count fragments pluralize via
_one/_other keys, verdict table holds keys resolved at paint time so width
clipping measures the translated text.

* i18n(gateway): unauthorized/pairing, voice, topics, shutdown, startup, notifications, kanban pings through t()

* i18n(cli): move tips + composer placeholders into the catalog (tips.tNNN / tips.placeholder.pNN)

get_random_tip()/get_random_composer_placeholder() pick a key from the English catalog
(the parity baseline, probed once per process) and resolve it through t() for the active
language, so language packs translate tips like any other string. Also lands the cli.*
en.yaml namespace consumed by the CLI info/help/error-copy wiring in the next commit.

* i18n(cli): wire chat-turn + session mixins through t(); kanban log trimmer matches t() output

* test(cli): assert TUI/dock/voice copy via t(key); prove labels resolve at render time

Pinned-English assertions in the approval-UI, live-work dock and voice tests now
go through the catalog. New test swaps the catalog after import and checks the
approval panel + hint row follow it (the reason _APPROVAL_CHOICE_LABELS and
_TUI_MODAL_HINTS became key tables).

* i18n(cli): route CLI info/help/error copy through t() (cli.* namespace)

cli_info_mixin: /help consumes CommandDef.describe() (added to commands.py: slash.<name>.description
with fallback to .description), section titles/skill/quick-command headers, /tools, /toolsets,
/usage labels, /context, /whoami, /insights, /gateway status, tool-progress labels, bang-shell
denials, MCP config-watch + /reload-mcp confirm/reload lines, /reload-skills, and the session-store
warning all read the catalog at call time (module-level label tables became functions so the
active language is honoured after startup). cli.py: worktree cleanup, tirith warning, show_config
(labels re-padded at print time), quick/plugin/skill slash-command errors, ambiguous-command hint,
stdin error, gateway start, profile warning. cli_chat_error_copy / cli_unknown_command /
cli_output / cli_init_mixin: chat error panel copy, did-you-mean lines, n-more / yes-no prompt
(localized affirmative initial alongside 'y'), unknown-toolsets warning.

* i18n(w1a): wire agent display/explainers/approval + slash registry/help through t()

- hermes_cli/commands.py: CommandDef.describe() resolves slash.<name>.description
  at call time; category labels via slash.category.*; help/alias/usage suffixes
  via slash.shared.*; gateway_help_lines and commands_platforms/slash_exec use them.
- agent/display.py: display.verb.* resolved at call time via get_tool_verb();
  bridge/spinner/thinking-verb/cute-row/failure/preview/diff text via display.*.
- agent/turn_explainers.py: exit-reason / persistence-cause tables become call-time
  lookups (explainer.exit.*, explainer.persistence.*, explainer.file_mutation.*).
- agent/background_review.py, session_activity.py, context_breakdown.py,
  status_output.py: review summaries, iteration progress, context notices.
- tools/approval.py, approval_context.py: approval.summary.*, approval.noun.*,
  approval.window.* pluralized keys.
- gateway/slash_commands*.py: remaining raw strings (busy, whoami, platform,
  bundles, memory, skills, approvals, set_home, diff, update, debug, profile,
  heartbeat, refine, review, subgoal, loop, retry, compress codex path, save,
  sessions, model guard/errors, agents rows, topup, login). HISTORY_UNREADABLE
  keeps its English constant; callers use history_unreadable() ->
  gateway.shared.history_unreadable.
- locales/en.yaml: new approval/display/explainer/slash blocks + gateway leftovers.

* i18n(telegram): route adapter chat copy through t()

Approval card (header/reason/smart-deny as HTML-escaped properties), inline
button labels, callback toasts (cut at Telegram's 200-char cap), model/choice
pickers, clarify/update/slash-confirm prompts, gmail-triage labels and the
inbound-media failure notice now come from the catalog. _UNAUTHORIZED is a
lazy _unauthorized() so the import no longer binds a language. The command
menu carries a language+payload fingerprint (forum scopes re-register on
change) and BotCommand descriptions are cut at 256.

Adds gateway.exec_approval.* (WAVE2 contract), platform.telegram.*,
platform.discord.* and the slash.*.description keys the Discord table shares
with the CLI registry to locales/en.yaml.

* i18n(gateway/platforms): whatsapp_cloud, yuanbao, weixin, signal, api_server copy through t()

- whatsapp_cloud: clarify list/buttons, approve/deny + slash-confirm labels via platform.whatsapp.* (t()-then-truncate at 20/24/72 caps); _EA_HEADER becomes a property wrapping ea_header_text()
- yuanbao: SLOW_RESPONSE_MESSAGE -> slow_response_message() (platform.yuanbao.slow_response_notice; zh keeps the original text); cron-wrapper markers centralized as module constants for strip_cron_wrapper
- api_server: PROVIDER_AUTH_FAILED_LABEL/PROVIDER_RATE_LIMITED_LABEL stay English for run.py matchers; user_text() renders via t()
- signal/_format_wait, weixin voice caption, openai_routes transformed notice
- run_turn: second _UNEXPECTED_SILENCE_REPLY consumer -> accessor

* i18n(discord): route adapter chat copy through t()

Native slash-command table becomes _NATIVE_SLASH_COMMAND_SPECS holding catalog
keys; _native_slash_commands() resolves descriptions, parameter descriptions
and Choice names for the active language, each cut at Discord's 100-char cap,
and the app-command sync fingerprint now includes get_language() so a
display.language change re-syncs. Exec-approval card (gateway.exec_approval.*
contract), slash-confirm / clarify / update views, model+choice pickers,
thread creation, forum titles, voice acks, the response-truncation notice,
the unauthorized-slash security alert and the media upload-size notices all
read from platform.discord.*. Decorator-declared button labels are relabelled
in __init__ (80-char cap); embed titles cut at 256, select placeholders at
150, option label/description at 100. _UNAUTHORIZED is a lazy _unauthorized().

* i18n(cli): wire status-bar, stream, terminal mixins + terminal_input through t(); rename kwargs that shadow t(key)

* i18n: wire hermes_cli/cli_commands_mixin.py slash-command copy through t()

- 431 new leaves under cli.commands.<cmd>.* in locales/en.yaml; 12 rows reuse
  existing gateway.* keys (rollback, diff, resume, branch, btw, model, reasoning)
  via a _gt() helper so CLI and gateway replies stay identical.
- Module-level English tables (_BUSY_MODE_*, _REASONING_TOGGLES, _HATCH_PROGRESS,
  _DIFF_LABELS, _LOCAL_ENGINE_LINES) become call-time catalog lookups keyed by id.
- Verb tables (Enabling/Disabling, Paused/Resumed/Triggered, planned/done,
  Updating/Generating) are one full template per variant; plurals use
  <key>_one/<key>_other via _tn(); hand-padded column labels (/snapshot list)
  translate the value and re-pad at the call site.
- Multi-line usage blocks are single catalog values split with _lines().
- Model-facing system notes and DB-stored reasons stay English (EXCLUDED).

* tests: assert /handoff, /worktree, /login CLI copy via t(key) instead of pinned English

* test(i18n): pin Telegram/Discord adapter catalog wiring

Lazy unauthorized notice, exec-approval contract keys, HTML escaping before
Telegram <b> wrapping, 200-char toast / 256-char BotCommand caps, Discord
100-char app-command text and 80-char button caps, and language-bearing
command-menu fingerprints on both platforms.

* i18n: reconcile cli.shared on/off vs enabled/disabled after lane merge

* i18n: describe() in TUI-gateway slash listings; localize TUI exit resume hint

* i18n(tr): translate bundled catalog + tui pack

* i18n(ja): translate bundled catalog + tui pack

* i18n(ko): translate bundled catalog + tui pack

* i18n(zh): translate bundled catalog + tui pack

* i18n(fr): translate bundled catalog + tui pack

* i18n(af): translate bundled catalog + tui pack

* i18n(uk): translate bundled catalog + tui pack

* i18n(ar): translate bundled catalog + tui pack

* i18n(pt): translate bundled catalog + tui pack

* i18n(it): translate bundled catalog + tui pack

* i18n(es): translate bundled catalog + tui pack

* i18n(zh-hant): translate bundled catalog + tui pack

* i18n(ru): translate bundled catalog + tui pack

* i18n(hu): translate bundled catalog + tui pack

* i18n(hu): translate pre-existing English-valued leftovers (kanban wake, /context, /status, fast labels)

* i18n(de): translate bundled catalog + tui pack

* i18n(ga): translate bundled catalog + tui pack

* test(i18n): fixture matches _normalize_lang(lang, home) signature

* i18n(tui): scaffold userMessages/slashCmd en siblings

* i18n(tui): wire secure prompts + content tables

* feat(tui): i18n — wire billing, subscription, connection-setup and journey overlays

Adds en siblings billing.ts / subscription.ts / connection.ts (namespaces
billing, subscription, connection, journey) and routes every user-facing
literal in billingOverlay, subscriptionOverlay, connectionSetupOverlay and
journey through useT()/messages(). Module-level label tables became lazy
(scopeStillDeniedResult(), verbOf(T, action)); auto-reload rows dispatch on
stable ids instead of label text. Regenerates locales/_keys.tui.json.

* i18n(tui): wire slash ops/wake replies

* i18n(tui): wire pickers (modelPicker, activeSessionSwitcher, petPicker)

* i18n(tui): wire slash core/debug/setup replies

* i18n(tui): wire hubs (agents overlay/panel/controls, skills, plugins)

* i18n(tui): wire slash session/topup/subscription replies

* i18n(tui): wire chat bits (branding, thinking, messageLine, loaders, todo, queued, banner, entry)

* i18n(tui): register t3 siblings (pickers, hubs, secure, content, chatBits) and regenerate keys

* i18n(tui): wire userMessages copy through the userMessages namespace

* i18n(tui): lazy-copy test for userMessages, regenerate _keys.tui.json

* i18n(tui): wire session/gateway/lib text through the TUI catalog (lane t2)

Adds en siblings session.ts, gatewayMsg.ts, libText.ts (namespaces session,
gatewayMsg, libText) and routes user-facing literals in app/{useMainApp,
useSessionLifecycle,useInputHandlers,turnController,createServerRequestHandler,
setupHandoff,createGatewayEventHandler}.ts, gatewayClient displayed reasons,
lib/*, domain/*, hooks/* through t()/messages(). Status-bar state values that
code compares against, backend-matched strings, log lines, model-bound text,
and machine 'error:' prefixes stay literal. Regenerates locales/_keys.tui.json
(232 keys).

* i18n: serve bundled locales/<lang>.tui.yaml under overlay/packs; TUI pack parity test; regen _keys.tui.json (1250)

* i18n: translate pre-existing English stubs in bundled locales (424 leaves, 14 locales)

* tui: i18n-export-en script (English templates for pack translators)

* docs(i18n): bundled TUI packs are the bottom layer of the tui surface

* i18n(ru): translate TUI pack

* i18n(ar): translate TUI pack

* i18n(es): translate TUI pack

* i18n(pt): translate TUI pack

* i18n(ko): translate TUI pack

* i18n(de): translate TUI pack

* i18n(ja): translate TUI pack

* i18n(fr): translate TUI pack

* i18n(tr): translate TUI pack

* i18n(it): translate TUI pack

* i18n(zh): translate TUI pack

* i18n(zh-hant): translate TUI pack

* i18n(hu): translate TUI pack

* i18n(uk): translate TUI pack

1,169 missing keys translated; 81 pre-existing kept byte-identical. Parity OK missing=0 extra=0 placeholder_mismatch=0 empty=0.

Deliberately identical to en: chatBits.branding.mcpSummary ({0} MCP), chatBits.thinking.agentsHint ((/agents)), session.main.voiceStt (◉ STT), session.main.voiceTtsSuffix ( [tts]), slashCmd.core.help.tuiSection (TUI), slashCmd.core.history.hermesTag (Hermes #{0}), slashCmd.debug.heapdump.heapPath (heapdump: {0}), slashCmd.debug.mem.rss (rss), subscription.stepUp.title (Remote Spending — product feature name, as in core catalog), content.faces.* (glyph-only kaomoji).

* i18n(ga): translate TUI pack

* i18n(af): translate TUI pack

* plugin_guard: locale catalogs in language packs step down the agent-config family

A translated status line such as "Updating AGENTS.md" in locales/<lang>.yaml is UI text the loader
reads as a string leaf; it cannot edit a file. The bundled en.yaml itself tripped agent_config_mod
at critical, making any faithful language pack uninstallable. Injection shapes keep full severity.

* plugin_validate_locales: read key exports with utf-8-sig (Windows footgun lint)

* i18n(relay): route relay adapter prompt copy through t(); drop dead import-bound approval header

Adds platform.relay.* (5 keys) to en and all 16 bundled locales, reusing the sibling platform
translations for the confirm buttons and the Other option.

* ci: fix TUI import order, MDX table pipe, main's overflow-warning wording in all locales; fresh-install fixture carries the i18n kernel

- ui-tui/src/i18n/en.ts: perfectionist/sort-imports (slash before slashCmd)
- docs plugins/index.md: escape the | inside the provides_locales table cell (MDX parsed <id> as JSX)
- display.notice.uncompressed_context_overflow: adopt main's wording (names compression.enabled: false
  and /compact) in en + 16 locales; the guardrail test pins that phrase
- tests/scripts/test_fresh_source_install.py: the installer tail now resolves CLI text through
  agent.i18n, so the fixture tree carries the i18n kernel + en.yaml (not the agent runtime)

* docs(desktop-plugin-sdk): double-backtick the template-literal example (MDX evaluated ${n})

* test(e2e): display.language is validated against the live language set; exclude it from the arbitrary-string set property

* commands: keep the localized COMMANDS/COMMANDS_BY_CATEGORY module __getattr__ after the compat block removal

* build: never write locales/_keys.*.json from the desktop/TUI builds; regenerate the committed desktop key export

The desktop build regenerated locales/_keys.desktop.json in the checkout, so a
hermes update that rebuilt the app left the tree dirty (Desktop update E2E:
'M locales/_keys.desktop.json'). The key exports are committed artifacts pinned
to en.ts by apps/desktop/scripts/i18n-keys.test.mjs and ui-tui i18n:keys:check;
builds read them, never write them. Regenerated after main's new desktop strings.

* test: unbreak two main-red timing tests the PR merge-ref inherits

- test_local_runtime racing fake publishes the modern state record (legacy pid-only
  records are rejected since 65ff3ad353; main has been red on this test since)
- test_run_progress_topics ManyProgressLinesAgent waits for the first bubble instead of
  a fixed 0.35s, which a loaded CI runner does not always meet

* chore(i18n): regenerate desktop key catalog for main's new strings (model pricing, copy changelog)

* test(e2e): torture-chamber fd monitor confirms a deleted sidecar is still held before calling it a leak

SQLite's WAL last-close unlinks -shm before closing its descriptor (unixShmUnmap, then
unixShmPurge), so a healthy close shows a (deleted) -shm for microseconds; the 20ms poll
occasionally caught that window on the short-lived opener and failed the episode.

* chore(i18n): regenerate desktop key catalog for main's telemetry/consent strings

* chore(i18n): regenerate desktop key catalog after main sync

---------

Co-authored-by: Teknium <teknium@nousresearch.com>
2026-09-28 14:16:18 -07:00

684 lines
36 KiB
Python

"""Plugin loading: directory/entry-point module import, deferred bundled platforms, portable packages,
dependency/config-schema warnings. Mixed into :class:`hermes_cli.plugins.PluginManager`.
Origin-internal names (``PluginContext``, ``LoadedPlugin``, ``_PLUGINS_DEBUG`` …) are imported lazily
through ``hermes_cli.plugins`` so tests that patch them on the origin keep working.
"""
from __future__ import annotations
import contextvars
import hashlib
import importlib
import importlib.metadata
import importlib.util
import logging
import re
import sys
import threading
import types
from contextlib import contextmanager
from functools import wraps
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional, Union
from hermes_constants import get_hermes_home, reset_hermes_home_override, set_hermes_home_override
from registration_lifecycle import replacement_coordinator
from hermes_cli.plugins_discovery import ENTRY_POINTS_GROUP, _select_entry_point_group
from hermes_cli.plugins_manifest import PluginManifest, manifest_key, portable_mcp_server_name, validate_config_schema
from hermes_cli.plugins_state import _plugin_settings_entry
if TYPE_CHECKING: # pragma: no cover
from hermes_cli.plugins import LoadedPlugin, PluginContext
logger = logging.getLogger("hermes_cli.plugins")
_NS_PARENT = "hermes_plugins"
_MODULE_NAMESPACE_LOCK = threading.RLock()
_BARE_MODULE_SCOPE: Dict[str, str] = {} # bare module name -> owning scope_key
# Per-plugin deadline on import + register(): ``plugins.load_timeout_seconds`` (default 10s, 0 disables,
# clamped to the max). A plugin that never returns is skipped with a named reason and loading moves on
# (#108139). Python cannot kill a thread, so the worker is abandoned as a daemon; the cap bounds how many
# abandoned loaders one process may accumulate (#98382) — past it, further loads are refused, not run inline.
_LOAD_TIMEOUT_SECS = 10.0
_MAX_LOAD_TIMEOUT_SECS = 600.0
_MAX_ABANDONED_LOADERS = 8
_ABANDONED_LOADERS: List[threading.Thread] = []
_ABANDONED_LOADERS_LOCK = threading.Lock()
_IN_PLUGIN_LOAD = threading.local() # ``.active`` on a loader worker thread
class PluginLoadTimeout(Exception):
"""Raised on the loading thread when a plugin's import + ``register()`` overran its deadline."""
def in_plugin_load_worker() -> bool:
"""True on a deadline worker thread; re-entrant discovery from there must not block on its own parent."""
return bool(getattr(_IN_PLUGIN_LOAD, "active", False))
def _resolve_plugin_load_timeout() -> float:
"""Effective per-plugin load deadline from ``plugins.load_timeout_seconds`` (default 10s; ``0`` runs
loads inline with no deadline; clamped to ``_MAX_LOAD_TIMEOUT_SECS``)."""
default = _LOAD_TIMEOUT_SECS
try:
from hermes_cli.config import load_config_readonly
plugins_cfg = (load_config_readonly() or {}).get("plugins")
if not isinstance(plugins_cfg, dict) or plugins_cfg.get("load_timeout_seconds") is None:
return default
timeout = float(plugins_cfg["load_timeout_seconds"])
except (TypeError, ValueError):
logger.warning("plugins.load_timeout_seconds is not a number; using default %gs", default)
return default
except Exception:
return default
if timeout < 0:
logger.warning("plugins.load_timeout_seconds=%g is negative; using default %gs", timeout, default)
return default
if timeout > _MAX_LOAD_TIMEOUT_SECS:
logger.warning("plugins.load_timeout_seconds=%g exceeds max %gs; clamping", timeout,
_MAX_LOAD_TIMEOUT_SECS)
return _MAX_LOAD_TIMEOUT_SECS
return timeout
def _reserve_abandoned_loader_slot() -> None:
"""Drop finished abandoned loaders; refuse the load once the live cap is reached. Refusing beats
loading inline: at the cap the process already holds several hung loaders, so an inline load is the
exact startup hang this deadline exists to prevent."""
with _ABANDONED_LOADERS_LOCK:
_ABANDONED_LOADERS[:] = [t for t in _ABANDONED_LOADERS if t.is_alive()]
if len(_ABANDONED_LOADERS) < _MAX_ABANDONED_LOADERS:
return
raise PluginLoadTimeout(
f"not loaded: {_MAX_ABANDONED_LOADERS} abandoned plugin loader thread(s) are still running "
f"(plugins.load_timeout_seconds); restart Hermes to retry"
)
def run_with_load_deadline(plugin_key: str, ctx: "PluginContext", fn: Callable[[], Any]) -> Any:
"""Run ``fn`` (a plugin's import + ``register()``) under the per-plugin deadline.
The worker inherits the caller's context (the Hermes-home override is a ContextVar). On timeout the
worker is abandoned as a daemon, ``ctx`` is marked so any registration it still attempts is ignored,
and :class:`PluginLoadTimeout` is raised on the calling thread so the usual failure path records the
reason and disposes whatever was registered before the hang.
"""
timeout = _resolve_plugin_load_timeout()
if timeout <= 0:
return fn()
_reserve_abandoned_loader_slot()
outcome: List[Any] = []
failure: List[BaseException] = []
def _worker() -> None:
_IN_PLUGIN_LOAD.active = True
try:
outcome.append(fn())
except BaseException as exc: # re-raised on the loading thread, KeyboardInterrupt included
failure.append(exc)
worker = threading.Thread(
target=contextvars.copy_context().run, args=(_worker,), name=f"plugin-load:{plugin_key}", daemon=True,
)
worker.start()
worker.join(timeout)
if worker.is_alive():
ctx._abandon_load()
with _ABANDONED_LOADERS_LOCK:
_ABANDONED_LOADERS.append(worker)
raise PluginLoadTimeout(f"load timed out after {timeout:g}s (import + register() never returned)")
if failure:
raise failure[0]
return outcome[0]
def _evict_modules(module_name: str) -> None:
"""Drop ``module_name`` and every ``module_name.*`` submodule from ``sys.modules``."""
prefix = f"{module_name}."
for name in [n for n in sys.modules if n == module_name or n.startswith(prefix)]:
del sys.modules[name]
def _serialized_replacement(method):
"""Make snapshot → write → lease attachment one atomic transaction."""
@wraps(method)
def wrapped(*args, **kwargs):
with replacement_coordinator.transaction():
return method(*args, **kwargs)
return wrapped
@contextmanager
def _plugin_home_scope(home: Path):
"""Bind discovery and loading to the manager's immutable Hermes home."""
token = set_hermes_home_override(home)
try:
yield
finally:
reset_hermes_home_override(token)
def _load_error_text(exc: BaseException) -> str:
"""Human-readable load failure; ``sys.exit(0)`` has an empty ``str()`` so name the class and code."""
if isinstance(exc, SystemExit):
return f"SystemExit({exc.code!r}) raised during import/register()"
return str(exc)
def _dist_installed(req: str) -> Optional[bool]:
"""Best-effort presence probe on a requirement's distribution name; ``None`` when unprobeable."""
dist = re.split(r"[<>=!~\[;\s]", req, maxsplit=1)[0].strip()
if not dist:
return None
try:
importlib.metadata.version(dist)
return True
except importlib.metadata.PackageNotFoundError:
return False
except Exception:
return None
class PluginLoaderMixin:
def on_plugin_loaded(self, callback: Callable[[List[Dict[str, Any]]], Any]) -> Callable[[], None]:
"""Subscribe to "a discovery sweep loaded plugins this process did not have": fires from INSIDE
:meth:`discover_and_load` (never emitted by an install RPC) with one
``{name, key, activated_now, deferred}`` summary per NEWLY loaded plugin — every plugin at boot,
just the newcomer after a mid-run ``hermes plugins install/enable``, Desktop / dashboard /
``plugins.manage`` install-enable-update, a tool-triggered force re-discovery or the gateway's
``reload-plugins`` verb (all of which run ``discover_plugins(force=True)``; a non-forced call
short-circuits on ``_discovered`` and never fires). See
:func:`hermes_cli.plugins_activation.plugin_activation_summary` for the payload: ``activated_now``
(gateway commands/transforms/hooks/callbacks, live at once) vs ``deferred`` (``tools``/``prompt``
until the next session, ``mcp_servers`` — the plugin's mcp.json server names — until ``mcp.reload``).
Listeners belong to the process (gateway runner, TUI server), not to a plugin, so ``unload()``
never clears them. Returns an unsubscribe callable. Fires on the discovering thread with the
discovery lock released; marshal onto your own loop."""
if not callable(callback):
raise ValueError("on_plugin_loaded requires a callable")
listeners = self._plugin_loaded_listeners
listeners.append(callback)
def _unsubscribe() -> None:
try:
listeners.remove(callback)
except ValueError:
pass
return _unsubscribe
def _notify_plugin_loaded(self, loaded_before: frozenset) -> None:
"""Fire every :meth:`on_plugin_loaded` listener for the plugins this sweep added over
``loaded_before``; nothing new = no event. One raising listener never starves the rest."""
if not self._plugin_loaded_listeners:
return
from hermes_cli.plugins_activation import activation_summaries
summaries = [s for s in activation_summaries(self) if s["key"] not in loaded_before]
if not summaries:
return
for callback in list(self._plugin_loaded_listeners):
try:
callback(summaries)
except Exception:
logger.warning("plugin-loaded listener %r raised", callback, exc_info=True)
@staticmethod
def _platform_name_from_manifest(manifest: PluginManifest) -> str:
"""Derive the platform name without importing the adapter: strip a trailing ``-platform`` from the
manifest name, else the directory basename (the bundled convention)."""
name = manifest.name or ""
if name.endswith("-platform"):
return name[: -len("-platform")]
return Path(manifest.path).name if manifest.path else name
def _register_deferred_platform(self, manifest: PluginManifest) -> None:
"""Register a lazy loader for a bundled platform: the adapter imports only when the
``platform_registry`` is first asked for it; a placeholder ``LoadedPlugin`` keeps it visible in
``hermes plugins list`` until then."""
from hermes_cli.plugins import LoadedPlugin
lookup_key = manifest_key(manifest)
loaded = LoadedPlugin(manifest=manifest, enabled=True, deferred=True)
self._plugins[lookup_key] = loaded
if not self._lease_deferred_platform(manifest, lookup_key):
# Fall back to eager loading so the platform is never silently lost. Runs outside the
# replacement transaction: the eager load's register() executes on a deadline worker, whose
# registrations need the coordinator lock this thread would otherwise still hold.
self._load_plugin(manifest)
return
self._register_deferred_platform_tools(manifest, loaded)
@_serialized_replacement
def _lease_deferred_platform(self, manifest: PluginManifest, lookup_key: str) -> bool:
"""Publish the deferred loader as a ledger-owned lease; False when the registry refused it."""
platform_name = self._platform_name_from_manifest(manifest)
try:
from gateway.platform_registry import platform_registry
scope = self.scope_key
def _loader(_manifest: PluginManifest = manifest) -> None:
# Lock before checking cancellation: if an unload won the race it restored the predecessor
# and this loader must publish nothing; if loading won, unload waits and disposes the set.
with self._discovery_lock, _plugin_home_scope(self.home_path):
if platform_registry.is_deferred_load_cancelled(platform_name, scope=scope):
return
self._load_plugin_scoped(_manifest)
previous = platform_registry.snapshot_registration(platform_name, scope=scope)
platform_registry.register_deferred(platform_name, _loader, scope=scope)
current = platform_registry.snapshot_registration(platform_name, scope=scope)
if current[0] is None and current[1] is _loader:
self._plugin_platform_names.add(platform_name)
self._track_scoped_registration(
manifest, "platform", platform_name, platform_registry, current, previous,
finalize=lambda: self._remove_platform_name_if_unowned(platform_name),
)
logger.debug("Registered deferred platform loader: %s (plugin=%s)", platform_name, lookup_key)
except Exception:
logger.debug(
"Deferred platform registration failed for '%s'; eager-loading", lookup_key, exc_info=True)
return False
return True
def _register_deferred_platform_tools(self, manifest: PluginManifest, loaded: LoadedPlugin) -> None:
"""Register a deferred platform's *client* tools without its adapter. Deferring the plugin would
otherwise defer its outbound tools too, so CLI/TUI processes (which never materialize platforms)
would miss them in ``hermes tools`` / ``platform_toolsets``. Opt-in is explicit via ``provides_tools``;
tools live in a ``tools`` submodule so ``__init__`` stays import-light.
A platform plugin can ship two independent things: an inbound adapter (heavy — it imports the
platform SDK) and outbound client tools the agent calls like any other tool. Deferring the plugin
defers both, so in a CLI/TUI process the client tools never register at all: ``resolve_toolset()``
returns ``[]``, the toolset is missing from the ``hermes tools`` checklist, and even an explicit
``platform_toolsets`` entry is dropped because the key is unknown. The same tools work in
gateway/web processes only because those materialize every platform at startup (issue #78050).
Opting in is explicit: the manifest must declare ``provides_tools`` (the field the plugin list and
web server already read to name a plugin's tools, per #78538). Keying off the mere presence of a
``tools.py`` would opt a plugin in by accident — a platform is free to put internal helpers there —
and would leave the contract invisible to anyone reading the manifest. ``tools.py`` remains where
the code is imported from; ``provides_tools`` is what asks for it. A platform that does not declare
the field is untouched and stays fully deferred.
"""
from hermes_cli.plugins import PluginContext, _PLUGINS_DEBUG
if not manifest.provides_tools:
return
lookup_key = manifest_key(manifest)
# Never let a client-tool import break discovery — the platform stays deferred and behaves exactly
# as it did before. But a broken tools.py produces the #78050 symptom itself (declared tools missing
# from the session), so this has to be visible without turning on debug logging to find it. Where it
# failed is the first thing an operator needs: nothing registered points at the import or the module
# body, a partial run points at one tool's definition, and a full run that still raised points past
# the registrations entirely.
declared = list(manifest.provides_tools)
plugin_dir = Path(manifest.path) if manifest.path else None
if plugin_dir is None or not (plugin_dir / "tools.py").is_file():
# Declared but undeliverable — staying quiet reproduces the very symptom this fixes.
logger.warning(
# Staying quiet here reproduces the exact symptom this path exists to fix — tools the
# manifest promises, silently absent from the session (#78050) — so say so.
"Plugin '%s' declares provides_tools %s but has no tools.py; "
"those tools will not be available in CLI/TUI sessions.", lookup_key, declared,
)
return
before = set(self._plugin_tool_names) # lets the failure path credit partial registrations
def _credit() -> List[str]:
"""Attribute every tool registered since ``before`` to this plugin."""
registered = [t for t in self._plugin_tool_names if t not in before]
if registered:
loaded.tools_registered = registered
self._predeclared_tools[lookup_key] = registered
return registered
try:
module = self._load_directory_module(manifest)
# Record the module even if nothing registers: the package body has run, so materializing the
# adapter later must reuse it rather than execute it twice.
loaded.module = module
self._predeclared_modules[lookup_key] = module
tools_module = importlib.import_module(f"{module.__name__}.tools")
register_tools = getattr(tools_module, "register_tools", None)
if register_tools is None:
logger.warning(
"Plugin '%s' declares provides_tools %s but its tools.py "
"has no register_tools(ctx); those tools will not be "
"available in CLI/TUI sessions.", lookup_key, declared,
)
return
register_tools(PluginContext(manifest, self))
registered = _credit()
logger.debug(
"Deferred platform '%s': pre-registered %d client tool(s) %s", lookup_key, len(registered),
registered,
)
except (Exception, SystemExit) as exc:
# Tools registered before the raise are live: credit them or `hermes plugins list` under-reports
# (and _load_plugin's later diff would miss them too). Never break discovery (the platform stays
# deferred), but a broken tools.py IS the symptom, so warn — and say where it failed first.
partial, total = _credit(), len(declared)
complete = len(partial) >= total
scope = (
f"before registering any of its {total} declared tool(s)" if not partial
else f"after registering all {total} declared tool(s)" if complete
else f"after registering {len(partial)} of {total} declared tool(s)"
)
logger.warning(
"Plugin '%s': client-tool pre-registration failed %s (%s).%s", lookup_key, scope, exc,
"" if complete else " The remainder will be missing from CLI/TUI sessions.",
exc_info=_PLUGINS_DEBUG,
)
def _warn_python_dependencies(self, manifest: PluginManifest) -> None:
"""Report missing dependencies without installing during discovery.
Plugin admission and PM repair own dependency changes.
"""
deps = manifest.python_dependencies
if not deps:
return
key = manifest_key(manifest)
missing = [req for req in deps if _dist_installed(req) is False]
if missing:
logger.warning(
"Plugin %s declares Python dependencies that are not "
"installed: %s. For an enabled plugin, run hermes pm repair, "
"then restart Hermes. Discovery does not install dependencies.",
key, ", ".join(missing),
)
else:
logger.debug("Plugin %s python_dependencies satisfied: %s", key, ", ".join(deps))
def _validate_plugin_config_schema(self, manifest: PluginManifest) -> None:
"""Warn (never block) on plugins.entries.<id> settings that violate config_schema.
See #64165.
"""
if not manifest.config_schema:
return
plugin_id = manifest_key(manifest)
settings: Mapping[str, Any] = {}
try:
from hermes_cli.config import load_config
entry = _plugin_settings_entry(load_config() or {}, plugin_id) or {}
raw = entry.get("settings")
if not isinstance(raw, Mapping):
raw = entry.get("config") # migration fallback mirroring ctx.get_config
settings = raw if isinstance(raw, Mapping) else {}
except Exception:
settings = {}
for warning in validate_config_schema(plugin_id, manifest.config_schema, settings):
logger.warning("Plugin %s config: %s", plugin_id, warning)
def _load_plugin(self, manifest: PluginManifest) -> None:
"""Import a plugin module and call its ``register(ctx)`` function."""
with self._discovery_lock, _plugin_home_scope(self.home_path):
self._load_plugin_scoped(manifest)
def _load_plugin_scoped(self, manifest: PluginManifest) -> None:
"""Load one plugin with the manager's home bound as current."""
from hermes_cli.plugins import LoadedPlugin, PluginContext, _PLUGINS_DEBUG
loaded = LoadedPlugin(manifest=manifest)
plugin_key = manifest_key(manifest)
logger.debug(
"Loading plugin '%s' (source=%s, kind=%s, path=%s)",
plugin_key, manifest.source, manifest.kind, manifest.path,
)
if manifest.portable:
self._load_portable_plugin(manifest, loaded)
return
# requires_hermes gate: skip cleanly (no import, no traceback) on a version mismatch.
from hermes_cli.plugins_manifest import requires_hermes_error
reason = requires_hermes_error(manifest)
if reason:
loaded.error = reason
logger.warning("Plugin '%s' skipped: %s", plugin_key, reason)
self._plugins[plugin_key] = loaded
return
registration_start = len(self._registration_order)
module_name = self._policy_module_name(manifest)
self._track_tool_override_policy(manifest, module_name)
ctx = PluginContext(manifest, self)
def _import_and_register() -> bool:
"""Import + register() — the part a plugin controls, so the part the deadline covers."""
# Declared language packs register before any plugin code runs, inside the same ledger slice
# so a failing register() unwinds them too.
self._register_declared_locales(manifest, ctx)
# Reuse a deferred platform's already-imported package so its body doesn't run twice.
# See #78050.
module = self._predeclared_modules.pop(plugin_key, None)
if module is None and manifest.source in {"user", "project", "bundled"}:
if self._is_manifest_only_language_pack(manifest):
return True # pure pack: locales/ is the whole plugin, no register() to run
module = self._load_directory_module(manifest, module_name=module_name)
elif module is None:
module = self._load_entrypoint_module(manifest)
register_fn = None
if module is not None and not isinstance(module, types.ModuleType) and callable(module):
# An entry point declared as ``module:function`` resolves to the function object itself via
# ``ep.load()``, not its module (#72052).
register_fn = module
module = sys.modules.get(getattr(register_fn, "__module__", ""))
loaded.module = module
if register_fn is None:
register_fn = getattr(module, "register", None)
if register_fn is None:
loaded.error = "no register() function"
logger.warning("Plugin '%s' has no register() function", manifest.name)
return False
register_fn(ctx)
return True
try:
if run_with_load_deadline(plugin_key, ctx, _import_and_register):
self._attribute_registrations(loaded, plugin_key, registration_start)
loaded.enabled = True
from hermes_cli.plugins_ledger import _hook_source_of
self._drop_fallback_hooks(_hook_source_of(manifest.name, loaded.module))
except (Exception, SystemExit) as exc:
# SystemExit too: a plugin module with an unguarded ``main()``/``sys.exit()`` must not take the
# whole process (and every other plugin's registry) down with it; KeyboardInterrupt still propagates.
# PluginLoadTimeout lands here as well: the abandoned worker's later registrations are refused
# by ``ctx``, and whatever it registered before hanging is disposed below.
owned = [r for r in self._registration_order if r.plugin_key == plugin_key]
self._dispose_registrations(owned)
self._forget_registrations(owned)
loaded.error = _load_error_text(exc)
# register() may have subscribed before raising; a failed plugin must leave no callable reachable
# from later event dispatch.
self._remove_plugin_subscriptions(plugin_key)
logger.warning("Failed to load plugin '%s': %s", manifest.name, _load_error_text(exc), exc_info=_PLUGINS_DEBUG)
# The failure path swept this plugin's whole ledger (not just the registration_start slice), so
# discovery-time pre-registrations are gone too.
# There is no live tool left to credit — attribution and the registry agree at zero. Only the
# success path pops _predeclared_tools, so drop the entry here rather than let the bookkeeping
# outlive the load attempt (#78050).
if not loaded.enabled:
self._predeclared_tools.pop(plugin_key, None)
self._plugins[plugin_key] = loaded
@staticmethod
def _is_manifest_only_language_pack(manifest: PluginManifest) -> bool:
"""A ``provides_locales`` plugin with no ``__init__.py`` is complete without Python — like a
manifest-only desktop plugin, it loads from its declared files alone."""
return bool(manifest.provides_locales and manifest.path
and not (Path(manifest.path) / "__init__.py").is_file())
def _register_declared_locales(self, manifest: PluginManifest, ctx) -> None:
"""``provides_locales`` -> ``ctx.register_locale_dir(<plugin>/locales)``; a declared id with no file
is a warning (the pack promised a language it does not ship), never a load failure."""
if not manifest.provides_locales or not manifest.path:
return
locales_dir = Path(manifest.path) / "locales"
handles = ctx.register_locale_dir(locales_dir, metadata=manifest.locale_metadata)
registered = {handle.key.split(".", 1)[0] for handle in handles}
for lang_id in manifest.provides_locales:
if lang_id not in registered:
logger.warning("Plugin '%s' declares provides_locales %r but %s has no %s.yaml",
manifest.name, lang_id, locales_dir, lang_id)
def _track_tool_override_policy(self, manifest: PluginManifest, module_name: str) -> None:
"""Install the plugin's tool-override policy in tools.registry as a ledger-owned lease."""
from hermes_cli.plugins import PluginContext
from tools.registry import registry as _registry
scope = self.scope_key
with replacement_coordinator.transaction():
previous_policy = _registry.snapshot_plugin_override_policy(module_name, scope=scope)
current_policy = _registry.register_plugin_override_policy(
module_name, PluginContext(manifest, self)._tool_override_allowed(""), scope=scope,
)
policy_lease = replacement_coordinator.acquire(
("tool_override_policy", scope, module_name), current=current_policy,
previous=previous_policy,
restore=lambda replacement: _registry.restore_plugin_override_policy(
module_name, current_policy, replacement, scope=scope,
),
)
self._track_registration(manifest, "tool_override_policy", module_name, policy_lease.dispose)
def _attribute_registrations(
self, loaded: LoadedPlugin, plugin_key: str, registration_start: int
) -> None:
"""Fill ``loaded.*_registered`` from the ledger slice this plugin's register() produced."""
registrations = [
r for r in self._registration_order[registration_start:]
if r.plugin_key == plugin_key and r.active
]
def _keys(kind: str) -> List[str]:
return [r.key for r in registrations if r.kind == kind]
# Discovery-time tools predate registration_start; credit them back or `hermes plugins list`
# under-reports once the deferred adapter materializes.
predeclared = [t for t in self._predeclared_tools.pop(plugin_key, []) if t in self._plugin_tool_names]
loaded.tools_registered = predeclared + [k for k in _keys("tool") if k not in predeclared]
loaded.hooks_registered = _keys("hook")
loaded.middleware_registered = _keys("middleware")
loaded.commands_registered = _keys("command")
logger.debug(
" registered: %d tool(s), %d hook(s), %d middleware, %d slash command(s), %d CLI command(s)",
len(loaded.tools_registered), len(loaded.hooks_registered),
len(loaded.middleware_registered), len(loaded.commands_registered),
sum(1 for c in self._cli_commands if c in _keys("cli_command")),
)
def _load_portable_plugin(self, manifest: PluginManifest, loaded: LoadedPlugin) -> None:
"""Load validated portable components without importing Python code."""
from hermes_cli.plugins import PluginContext
lookup_key = manifest_key(manifest)
try:
from hermes_cli.agent_plugins import load_agent_plugin
package = load_agent_plugin(
Path(manifest.path), get_hermes_home() / "plugin-data" / manifest.skill_namespace)
ctx = PluginContext(manifest, self)
for diagnostic in package.diagnostics:
logger.warning("Agent Plugin '%s' [%s]: %s", lookup_key, diagnostic.scope, diagnostic.message)
for skill in package.skills:
try:
ctx.register_skill(skill.name, skill.skill_md, skill.description, skill.frontmatter)
except Exception as exc:
logger.warning("Agent Plugin '%s' skill '%s' skipped: %s", lookup_key, skill.name, exc)
from hermes_cli.agent_plugins import _clear_liveness, _set_liveness
from hermes_platform import declaration
registered: list[str] = []
try:
for server_name, config in package.mcp_servers.items():
internal_name = portable_mcp_server_name(lookup_key, server_name)
if internal_name in self._portable_mcp_servers:
logger.warning("Agent Plugin '%s' MCP server '%s' skipped: name already taken by plugin '%s'; rename one server",
lookup_key, internal_name, self._portable_mcp_server_plugins.get(internal_name, "?"))
continue
self._portable_mcp_servers[internal_name] = dict(config)
self._portable_mcp_server_plugins[internal_name] = lookup_key
server_decl = package.server_declarations.get(server_name)
if server_decl is not None:
declaration.register(internal_name, server_decl.declaration)
_set_liveness(internal_name, server_decl.liveness)
registered.append(internal_name)
for internal_name in registered:
def release(name: str = internal_name) -> None:
self._portable_mcp_servers.pop(name, None)
self._portable_mcp_server_plugins.pop(name, None)
declaration.unregister(name)
_clear_liveness(name)
self._track_registration(manifest, "portable_mcp", internal_name, release)
loaded.enabled = True
except BaseException:
for internal_name in registered:
self._portable_mcp_servers.pop(internal_name, None)
self._portable_mcp_server_plugins.pop(internal_name, None)
declaration.unregister(internal_name)
_clear_liveness(internal_name)
raise
except (Exception, SystemExit) as exc:
loaded.error = _load_error_text(exc)
logger.warning("Agent Plugin '%s' disabled: %s", lookup_key, loaded.error)
self._plugins[lookup_key] = loaded
def _directory_module_name(self, manifest: PluginManifest) -> str:
"""Profile-safe import namespace for a directory plugin: the bare ``hermes_plugins.<slug>`` for the
first scope that claims it, a ``__home_<digest>`` suffix for any other scope."""
slug = manifest_key(manifest).replace("/", "__").replace("-", "_")
bare_name = f"{_NS_PARENT}.{slug}"
with _MODULE_NAMESPACE_LOCK:
if _BARE_MODULE_SCOPE.setdefault(bare_name, self.scope_key) == self.scope_key:
return bare_name
digest = hashlib.sha256(self.scope_key.encode("utf-8")).hexdigest()[:12]
return f"{bare_name}__home_{digest}"
def _policy_module_name(self, manifest: PluginManifest) -> str:
"""Return the module prefix whose callbacks inherit plugin policy."""
if manifest.source == "entrypoint" and manifest.path:
module_name = str(manifest.path).partition(":")[0].strip()
if module_name:
return module_name
return self._directory_module_name(manifest)
def _load_directory_module(
self, manifest: PluginManifest, *, module_name: Optional[str] = None,
) -> types.ModuleType:
"""Import a directory plugin as ``hermes_plugins.<slug>`` (slug from ``manifest.key`` so
``image_gen/openai`` cannot collide with ``tts/openai``)."""
plugin_dir = Path(manifest.path) # type: ignore[arg-type]
init_file = plugin_dir / "__init__.py"
if not init_file.exists():
raise FileNotFoundError(f"No __init__.py in {plugin_dir}")
if _NS_PARENT not in sys.modules:
ns_pkg = types.ModuleType(_NS_PARENT)
ns_pkg.__path__ = [] # type: ignore[attr-defined]
ns_pkg.__package__ = _NS_PARENT
sys.modules[_NS_PARENT] = ns_pkg
module_name = module_name or self._directory_module_name(manifest)
# Evict stale entries for this slug (same slug cached from another Hermes home, or an earlier force
# reload). Replacing only sys.modules[module_name] is not enough: the plugin's relative imports are
# cached as "module_name.sub" and resolve from sys.modules first, so a stale submodule would keep
# serving the previous load's code/state.
_evict_modules(module_name)
spec = importlib.util.spec_from_file_location(
module_name, init_file, submodule_search_locations=[str(plugin_dir)])
if spec is None or spec.loader is None:
raise ImportError(f"Cannot create module spec for {init_file}")
module = importlib.util.module_from_spec(spec)
module.__package__ = module_name
module.__path__ = [str(plugin_dir)] # type: ignore[attr-defined]
sys.modules[module_name] = module
try:
spec.loader.exec_module(module)
except BaseException:
# Don't leave a half-initialized module (or its partially imported relative submodules) cached — a
# retry or a same-slug plugin in another profile would inherit broken state.
_evict_modules(module_name)
raise
return module
def _load_entrypoint_module(self, manifest: PluginManifest) -> Union[types.ModuleType, Callable[..., Any]]:
"""Load a pip-installed plugin via its entry-point reference: the module for a bare ``module`` target,
the referenced attribute (normally ``register``) for the ``module:function`` form."""
for ep in _select_entry_point_group(importlib.metadata.entry_points(), ENTRY_POINTS_GROUP):
if ep.name == manifest.name:
return ep.load()
raise ImportError(f"Entry point '{manifest.name}' not found in group '{ENTRY_POINTS_GROUP}'")