The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): validate accepts model-provider plugins and mirrors the real PluginContext surface
teknium15f9042bec696
diff --git a/hermes_cli/plugin_validate.py b/hermes_cli/plugin_validate.pyindex bcc7cb9943f..02a983025ad 100644--- a/hermes_cli/plugin_validate.py+++ b/hermes_cli/plugin_validate.py@@ -184,7 +184,9 @@ def _check_requires_env(report: ValidationReport, manifest: dict) -> None:# module using the same file-location mechanics PluginManager uses, calls# register() against a recording stub ctx, and prints a sentinel-prefixed# JSON line of what was actually registered. Deliberately imports NOTHING-# from hermes so a hostile plugin only sees a bare interpreter.+# from hermes so a hostile plugin only sees a bare interpreter — the one+# exception is `providers` for `kind: model-provider`, whose contract IS+# calling providers.register_provider at import._PROBE_SCRIPT = r"""import importlib.utilimport json@@ -192,13 +194,19 @@ import sysplugin_dir = sys.argv[1]sentinel = sys.argv[2]+options = json.loads(sys.argv[3])+# Public method names of the real PluginContext, computed by the parent so the+# stub's attribute surface cannot drift from the class plugins run against.+context_methods = set(options["context_methods"])+provider_kind = options["kind"] == "model-provider"-recorded = {"tools": [], "hooks": [], "middleware": [], "commands": []}+recorded = {"tools": [], "hooks": [], "middleware": [], "commands": [], "providers": []}class RecordingContext:plugin_config = {}profile_name = "default"+ plugin_id = "hermes_validate_probe_plugin"def register_tool(self, name, *args, **kwargs):recorded["tools"].append(str(name))@@ -220,20 +228,44 @@ class RecordingContext:# plugins do `int(ctx.get_config("timeout", 180))` in register().return default- def __getattr__(self, _name):- # Any other registration surface (platforms, providers, skills,- # context engines, ...) is accepted as a no-op — the probe only- # audits the declared-capability categories.- def _noop(*args, **kwargs):- return None+ def __getattr__(self, name):+ # Any other REAL registration surface (platforms, providers, skills,+ # context engines, ...) is accepted as a no-op — the probe only audits+ # the declared-capability categories. Names the real PluginContext does+ # not have raise AttributeError exactly like it would; handing back a+ # callable made `getattr(ctx, "profile_path", None)` truthy and crashed+ # register() in the probe alone.+ if name in context_methods:+ def _noop(*args, **kwargs):+ return None- return _noop+ return _noop+ raise AttributeError(name)def emit(payload):print(sentinel + json.dumps(payload))+if provider_kind:+ # `kind: model-provider` plugins register at import via+ # providers.register_provider(ProviderProfile) — the PluginManager never+ # calls a register(ctx) on them (plugins_discovery skips the kind), so the+ # probe records that call instead of demanding an entry point that would+ # be dead code.+ try:+ import providers as _providers+ except Exception as exc:+ emit({"error": "model-provider probe could not import providers: %s" % exc})+ sys.exit(0)+ _real_register_provider = _providers.register_provider++ def _recording_register_provider(profile):+ recorded["providers"].append(str(getattr(profile, "name", profile)))+ return _real_register_provider(profile)++ _providers.register_provider = _recording_register_provider+try:spec = importlib.util.spec_from_file_location("hermes_validate_probe_plugin",@@ -248,6 +280,13 @@ except Exception as exc:emit({"error": "import failed: %s" % exc})sys.exit(0)+if provider_kind:+ if not recorded["providers"]:+ emit({"error": "model-provider plugin registered no ProviderProfile at import"})+ else:+ emit(recorded)+ sys.exit(0)+register = getattr(module, "register", None)if register is None:emit({"error": "no register() function"})@@ -263,12 +302,24 @@ emit(recorded)"""-def _run_capability_probe(plugin_dir: Path) -> Tuple[Optional[dict], str]:+def _probe_options(manifest: dict) -> dict:+ from hermes_cli.plugins import PluginContext++ return {+ "kind": str(manifest.get("kind") or ""),+ "context_methods": sorted(+ n for n in dir(PluginContext)+ if not n.startswith("_") and callable(getattr(PluginContext, n))+ ),+ }+++def _run_capability_probe(plugin_dir: Path, manifest: dict) -> Tuple[Optional[dict], str]:"""Run the recording probe in a scratch subprocess.Returns ``(recorded, error)`` — exactly one is meaningful: *recorded*- is the ``{tools, hooks, middleware, commands}`` dict on success, and- *error* is a human-readable failure description otherwise.+ is the ``{tools, hooks, middleware, commands, providers}`` dict on+ success, and *error* is a human-readable failure description otherwise."""with tempfile.TemporaryDirectory(prefix="hermes-validate-") as scratch:env = dict(os.environ)@@ -281,6 +332,7 @@ def _run_capability_probe(plugin_dir: Path) -> Tuple[Optional[dict], str]:_PROBE_SCRIPT,str(plugin_dir),_PROBE_SENTINEL,+ json.dumps(_probe_options(manifest)),],capture_output=True,text=True,@@ -331,11 +383,17 @@ def _check_capabilities(report.add("capability probe", True, "skipped (no __init__.py)")return None- recorded, error = _run_capability_probe(plugin_dir)+ recorded, error = _run_capability_probe(plugin_dir, manifest)if recorded is None:report.add("capability probe", False, error)return None- report.add("capability probe", True, "register() ran in isolation")+ if recorded.get("providers"):+ report.add(+ "capability probe", True,+ "import registered provider(s): " + ", ".join(recorded["providers"]),+ )+ else:+ report.add("capability probe", True, "register() ran in isolation")for kind, manifest_key in (("tools", "provides_tools"),diff --git a/tests/hermes_cli/test_plugin_validate.py b/tests/hermes_cli/test_plugin_validate.pyindex 335ee750de1..895a3ad3995 100644--- a/tests/hermes_cli/test_plugin_validate.py+++ b/tests/hermes_cli/test_plugin_validate.py@@ -124,6 +124,53 @@ class TestCapabilityProbe:assert report.ok, report.failures+ def test_probe_context_has_real_context_attribute_surface(self, tmp_path):+ """An attribute the real PluginContext lacks must raise AttributeError in the probe too:+ handing back a callable made ``getattr(ctx, "profile_path", None)`` truthy and crashed+ register() only under validation."""+ d = _make_plugin(+ tmp_path,+ manifest={**BASE_MANIFEST, "provides_tools": ["t"]},+ init_py=(+ "def register(ctx):\n"+ " assert getattr(ctx, 'profile_path', None) is None\n"+ " ctx.register_platform('probe', object)\n"+ " ctx.register_tool('t', schema={}, handler=lambda **kw: None)\n"),+ )+ report = validate_plugin_dir(d)+ assert report.ok, report.failures+++class TestModelProviderKind:+ def test_import_time_register_provider_is_the_entry_point(self, tmp_path):+ """``kind: model-provider`` plugins register at import via providers.register_provider and+ are never handed a register(ctx); validate must accept that contract, not demand register()."""+ d = _make_plugin(+ tmp_path,+ manifest={**BASE_MANIFEST, "name": "probe-provider", "kind": "model-provider"},+ init_py=(+ "from providers import register_provider\n"+ "from providers.base import ProviderProfile\n"+ "register_provider(ProviderProfile(name='probe_provider_fixture'))\n"),+ )+ report = validate_plugin_dir(d)+ assert report.ok, report.failures+ assert any(+ name == "capability probe" and "probe_provider_fixture" in detail+ for name, _ok, detail in report.checks+ ), report.checks++ def test_provider_plugin_that_registers_nothing_fails(self, tmp_path):+ d = _make_plugin(+ tmp_path,+ manifest={**BASE_MANIFEST, "name": "empty-provider", "kind": "model-provider"},+ init_py="import providers\n",+ )+ report = validate_plugin_dir(d)+ assert not report.ok+ assert any("registered no ProviderProfile" in f for f in report.failures), report.failures++class TestRequiresHermesSpec:"""A typo'd ``requires_hermes`` clause must fail admission, not silently gate nothing."""