Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(plugins): add the deeptutor.plugins entry-point loader (#908)

alanguan730c9093db90c8
diff --git a/deeptutor/plugins/__init__.py b/deeptutor/plugins/__init__.py
new file mode 100644
index 000000000..3ad788a9d
--- /dev/null
+++ b/deeptutor/plugins/__init__.py
@@ -0,0 +1,13 @@
+"""DeepTutor plugin package — entry-point discovery lives in ``loader``."""
+
+from deeptutor.plugins.loader import (
+ PluginManifest,
+ discover_plugins,
+ load_plugin_capability,
+)
+
+__all__ = [
+ "PluginManifest",
+ "discover_plugins",
+ "load_plugin_capability",
+]
diff --git a/deeptutor/plugins/loader.py b/deeptutor/plugins/loader.py
new file mode 100644
index 000000000..8cff43951
--- /dev/null
+++ b/deeptutor/plugins/loader.py
@@ -0,0 +1,184 @@
+"""Neutral plugin discovery for DeepTutor.
+
+External packages register under the ``deeptutor.plugins`` entry-point group.
+This module is intentionally domain-agnostic: it only discovers manifests and
+instantiates ``BaseCapability`` subclasses.
+
+Call sites already expect:
+
+* ``discover_plugins() -> list[PluginManifest]``
+* ``load_plugin_capability(manifest) -> BaseCapability | None``
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+import importlib
+from importlib.metadata import entry_points
+import inspect
+import logging
+from typing import Any
+
+from deeptutor.core.capability_protocol import BaseCapability
+
+logger = logging.getLogger(__name__)
+
+ENTRY_POINT_GROUP = "deeptutor.plugins"
+
+
+@dataclass
+class PluginManifest:
+ """Static metadata for a discovered plugin."""
+
+ name: str
+ type: str # "capability" | "tool" | …
+ description: str = ""
+ stages: list[str] = field(default_factory=list)
+ version: str = "0.0.0"
+ author: str = ""
+ entry: str = ""
+
+
+def discover_plugins() -> list[PluginManifest]:
+ """Discover plugins registered via ``deeptutor.plugins`` entry points."""
+ manifests: list[PluginManifest] = []
+ try:
+ eps = entry_points(group=ENTRY_POINT_GROUP)
+ except TypeError:
+ # Python <3.10 style Selection / dict API
+ all_eps = entry_points()
+ if isinstance(all_eps, dict):
+ eps = all_eps.get(ENTRY_POINT_GROUP, [])
+ else:
+ eps = all_eps.select(group=ENTRY_POINT_GROUP)
+
+ for ep in eps:
+ try:
+ loaded = ep.load()
+ manifest = _coerce_manifest(ep.name, loaded)
+ if manifest is not None:
+ manifests.append(manifest)
+ except Exception:
+ logger.warning(
+ "Failed to load plugin entry point %r; skipping.",
+ getattr(ep, "name", ep),
+ exc_info=True,
+ )
+ return manifests
+
+
+def load_plugin_capability(manifest: PluginManifest) -> BaseCapability | None:
+ """Instantiate a capability plugin from *manifest*, or return ``None``."""
+ if not manifest.entry:
+ return None
+ if manifest.entry.endswith("tool.py"):
+ return None
+ if manifest.type and manifest.type != "capability":
+ return None
+
+ obj = _resolve_entry(manifest.entry)
+ return _instantiate_capability(obj)
+
+
+def _coerce_manifest(ep_name: str, loaded: Any) -> PluginManifest | None:
+ if isinstance(loaded, PluginManifest):
+ if not loaded.name:
+ loaded.name = ep_name
+ return loaded
+
+ if callable(loaded) and not _is_capability_class(loaded):
+ # Manifest factory (not a BaseCapability subclass)
+ produced = loaded()
+ if isinstance(produced, PluginManifest):
+ if not produced.name:
+ produced.name = ep_name
+ return produced
+ if _is_capability_class(produced):
+ return _manifest_from_capability_class(ep_name, produced)
+ if isinstance(produced, BaseCapability):
+ return _manifest_from_capability_instance(ep_name, produced)
+ loaded = produced
+
+ if _is_capability_class(loaded):
+ return _manifest_from_capability_class(ep_name, loaded)
+
+ if isinstance(loaded, BaseCapability):
+ return _manifest_from_capability_instance(ep_name, loaded)
+
+ plugin_manifest = getattr(loaded, "PLUGIN_MANIFEST", None)
+ if isinstance(plugin_manifest, PluginManifest):
+ if not plugin_manifest.name:
+ plugin_manifest.name = ep_name
+ return plugin_manifest
+
+ create = getattr(loaded, "create_capability", None)
+ if callable(create):
+ cap = create()
+ if isinstance(cap, BaseCapability):
+ return _manifest_from_capability_instance(ep_name, cap)
+ if _is_capability_class(cap):
+ return _manifest_from_capability_class(ep_name, cap)
+
+ logger.warning(
+ "Plugin entry point %r did not yield a capability or PluginManifest.",
+ ep_name,
+ )
+ return None
+
+
+def _manifest_from_capability_class(ep_name: str, cls: type[BaseCapability]) -> PluginManifest:
+ m = cls.manifest
+ return PluginManifest(
+ name=m.name or ep_name,
+ type="capability",
+ description=m.description or "",
+ stages=list(m.stages or []),
+ entry=_qualname(cls),
+ )
+
+
+def _manifest_from_capability_instance(ep_name: str, cap: BaseCapability) -> PluginManifest:
+ return PluginManifest(
+ name=cap.manifest.name or ep_name,
+ type="capability",
+ description=cap.manifest.description or "",
+ stages=list(cap.manifest.stages or []),
+ entry=_qualname(type(cap)),
+ )
+
+
+def _is_capability_class(obj: Any) -> bool:
+ return isinstance(obj, type) and issubclass(obj, BaseCapability) and obj is not BaseCapability
+
+
+def _qualname(obj: Any) -> str:
+ module = getattr(obj, "__module__", "") or ""
+ name = getattr(obj, "__qualname__", None) or getattr(obj, "__name__", "")
+ if module and name:
+ return f"{module}:{name}"
+ return str(name or obj)
+
+
+def _resolve_entry(entry: str) -> Any:
+ if ":" not in entry:
+ return importlib.import_module(entry)
+ module_path, attr_path = entry.split(":", 1)
+ module = importlib.import_module(module_path)
+ obj: Any = module
+ for part in attr_path.split("."):
+ obj = getattr(obj, part)
+ return obj
+
+
+def _instantiate_capability(obj: Any) -> BaseCapability | None:
+ if isinstance(obj, BaseCapability):
+ return obj
+ if _is_capability_class(obj):
+ return obj()
+ if callable(obj) and not inspect.isclass(obj):
+ produced = obj()
+ if isinstance(produced, BaseCapability):
+ return produced
+ if _is_capability_class(produced):
+ return produced()
+ return None
diff --git a/tests/plugins/test_loader.py b/tests/plugins/test_loader.py
new file mode 100644
index 000000000..46b3fe947
--- /dev/null
+++ b/tests/plugins/test_loader.py
@@ -0,0 +1,128 @@
+"""Tests for the neutral deeptutor.plugins.loader entry-point discovery."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest
+from deeptutor.core.context import UnifiedContext
+from deeptutor.core.stream_bus import StreamBus
+
+
+class _DemoCapability(BaseCapability):
+ manifest = CapabilityManifest(
+ name="demo_cap",
+ description="Demo capability from a plugin EP.",
+ stages=["responding"],
+ )
+
+ async def run(self, context: UnifiedContext, stream: StreamBus) -> None:
+ return None
+
+
+def _ep(name: str, load):
+ return SimpleNamespace(name=name, load=load)
+
+
+def test_discover_plugins_from_capability_class(monkeypatch):
+ from deeptutor.plugins import loader
+
+ def fake_entry_points(*, group: str):
+ assert group == "deeptutor.plugins"
+ return [_ep("demo_cap", lambda: _DemoCapability)]
+
+ monkeypatch.setattr(loader, "entry_points", fake_entry_points)
+
+ manifests = loader.discover_plugins()
+ assert len(manifests) == 1
+ m = manifests[0]
+ assert m.name == "demo_cap"
+ assert m.type == "capability"
+ assert m.description.startswith("Demo")
+ assert m.stages == ["responding"]
+ assert ":_DemoCapability" in m.entry or m.entry.endswith("_DemoCapability")
+
+
+def test_discover_skips_broken_entry_points(monkeypatch):
+ from deeptutor.plugins import loader
+
+ def boom():
+ raise RuntimeError("boom")
+
+ def fake_entry_points(*, group: str):
+ return [
+ _ep("bad", boom),
+ _ep("demo_cap", lambda: _DemoCapability),
+ ]
+
+ monkeypatch.setattr(loader, "entry_points", fake_entry_points)
+ manifests = loader.discover_plugins()
+ assert [m.name for m in manifests] == ["demo_cap"]
+
+
+def test_load_plugin_capability_instantiates(monkeypatch):
+ from deeptutor.plugins import loader
+
+ monkeypatch.setattr(
+ loader,
+ "entry_points",
+ lambda *, group: [_ep("demo_cap", lambda: _DemoCapability)],
+ )
+ manifests = loader.discover_plugins()
+ cap = loader.load_plugin_capability(manifests[0])
+ assert isinstance(cap, _DemoCapability)
+ assert cap.name == "demo_cap"
+
+
+def test_load_plugin_capability_skips_tool_entry():
+ from deeptutor.plugins.loader import PluginManifest, load_plugin_capability
+
+ manifest = PluginManifest(
+ name="some_tool",
+ type="tool",
+ description="",
+ entry="path/to/tool.py",
+ )
+ assert load_plugin_capability(manifest) is None
+
+
+def test_discover_from_manifest_factory(monkeypatch):
+ from deeptutor.plugins import loader
+ from deeptutor.plugins.loader import PluginManifest
+
+ def factory():
+ return PluginManifest(
+ name="from_factory",
+ type="capability",
+ description="via factory",
+ stages=["a"],
+ entry="tests.plugins.test_loader:_DemoCapability",
+ )
+
+ monkeypatch.setattr(
+ loader,
+ "entry_points",
+ lambda *, group: [_ep("from_factory", factory)],
+ )
+ manifests = loader.discover_plugins()
+ assert manifests[0].name == "from_factory"
+ cap = loader.load_plugin_capability(manifests[0])
+ assert isinstance(cap, _DemoCapability)
+
+
+def test_capability_registry_loads_plugins(monkeypatch):
+ from deeptutor.plugins import loader
+ from deeptutor.runtime.registry import capability_registry as cr
+
+ monkeypatch.setattr(
+ loader,
+ "entry_points",
+ lambda *, group: [_ep("demo_cap", lambda: _DemoCapability)],
+ )
+ # Fresh registry instance (avoid process-global singleton pollution)
+ reg = cr.CapabilityRegistry()
+ reg.load_plugins()
+ assert reg.get("demo_cap") is not None
+ assert reg.get("demo_cap").name == "demo_cap"