mirror of
https://github.com/agentscope-ai/ReMe.git
synced 2026-11-27 23:58:47 +00:00
Some checks failed
CI and Release / Docker / Build and test / amd64 (push) Has been cancelled
CI and Release / Docker / Build and test / arm64 (push) Has been cancelled
Security / CodeQL / Analyze python (push) Has been cancelled
CI / Python quality / Pre-commit (push) Has been cancelled
CI / Python tests / Unit Tests - py3.12 (push) Has been cancelled
CI / Python tests / Unit Tests - py3.13 (push) Has been cancelled
CI / Python tests / Unit Tests - py3.14 (push) Has been cancelled
CI / Python packages / Build and verify distributions (push) Has been cancelled
CI / Python quality / GitHub Actions (push) Has been cancelled
CI / Python tests / Hermes embedded - ubuntu-latest (push) Has been cancelled
CI / Python tests / Hermes embedded - windows-latest (push) Has been cancelled
CI / Python tests / Unit Tests - py3.11 (push) Has been cancelled
CI / ReMe Studio / Studio checks (push) Has been cancelled
Deploy / Documentation / Build documentation (push) Has been cancelled
CI / Windows / CLI smoke - py3.11 (push) Has been cancelled
Security / CodeQL / Analyze javascript-typescript (push) Has been cancelled
CI and Release / Docker / Publish multi-platform tags (push) Has been cancelled
Deploy / Documentation / deploy (push) Has been cancelled
* refactor(core): reorganize the ReMe runtime and shared helpers * test(status): import the base component from its canonical module * test: remove redundant unit checks * refactor(core): use canonical runtime imports and shared CLI discovery Restore evolve behavior to the base branch and update its imports. Use Application as the runtime entry point and encode SSE in the HTTP service. * fix(cli): honor caller config when service replay is incomplete Use partial startup overrides for port probes and resolve named configs before requesting the service process working directory.
163 lines
6.7 KiB
Python
163 lines
6.7 KiB
Python
"""Load explicitly enabled plugins into one application's config and registry.
|
|
|
|
Plugins expose a package-only ``reme.plugins`` entry point and declare two
|
|
optional mappings in ``plugin.yaml``: ``backends`` and ``application_defaults``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from collections.abc import Iterable, Mapping
|
|
from dataclasses import dataclass, field
|
|
from importlib import import_module
|
|
from importlib.metadata import EntryPoint
|
|
from typing import Any
|
|
|
|
from pydantic import StrictStr, TypeAdapter, ValidationError
|
|
|
|
from .manifest import PluginManifest, load_package_manifest
|
|
from ..components.base import ComponentMixin
|
|
from ..core.registry import ComponentRegistry, R, create_application_registry
|
|
from ..config import deep_merge_config, expand_env_vars
|
|
from ..config.config_parser import UndefinedEnvironmentVariableError
|
|
from ..core.entry_point import PLUGIN_ENTRY_POINT_GROUP, find_entry_points, unique_entry_point
|
|
|
|
_PLUGIN_NAMES = TypeAdapter(list[StrictStr])
|
|
|
|
|
|
def configured_plugin_names(config: Mapping[str, Any]) -> list[str]:
|
|
"""Validate the plugin list before inspecting or importing any provider."""
|
|
try:
|
|
return _PLUGIN_NAMES.validate_python(config.get("plugins", []))
|
|
except ValidationError as error:
|
|
raise ValueError("Application config 'plugins' must be a list of strings") from error
|
|
|
|
|
|
def _check_plugin_defaults(value: Any) -> None:
|
|
"""Report missing environment variables still present after applying overrides."""
|
|
if isinstance(value, UndefinedEnvironmentVariableError):
|
|
raise value
|
|
if isinstance(value, Mapping):
|
|
for item in value.values():
|
|
_check_plugin_defaults(item)
|
|
elif isinstance(value, list):
|
|
for item in value:
|
|
_check_plugin_defaults(item)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Backend:
|
|
"""One named component, step, or job backend contributed by a plugin."""
|
|
|
|
name: str
|
|
implementation: type[ComponentMixin]
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Plugin:
|
|
"""Resolved backend classes and defaults from one package manifest."""
|
|
|
|
name: str
|
|
backends: tuple[Backend, ...] = ()
|
|
config: Mapping[str, Any] = field(default_factory=dict)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class PluginRuntime:
|
|
"""Application config and registry after applying enabled plugins."""
|
|
|
|
config: dict[str, Any]
|
|
registry: ComponentRegistry
|
|
|
|
|
|
def _load_backend(target: str, *, plugin_name: str) -> type[ComponentMixin]:
|
|
"""Import one ``module:class`` backend target from a plugin manifest."""
|
|
module_name, separator, attribute = target.partition(":")
|
|
if not separator or not module_name or not attribute or ":" in attribute:
|
|
raise ValueError(f"Plugin '{plugin_name}' has invalid backend target: {target!r}")
|
|
try:
|
|
value: Any = import_module(module_name)
|
|
for part in attribute.split("."):
|
|
value = getattr(value, part)
|
|
except (AttributeError, ImportError) as exc:
|
|
raise ValueError(f"Plugin '{plugin_name}' cannot load backend '{target}': {exc}") from exc
|
|
if not isinstance(value, type) or not issubclass(value, ComponentMixin):
|
|
raise TypeError(f"Plugin '{plugin_name}' backend '{target}' is not a ComponentMixin class")
|
|
return value
|
|
|
|
|
|
def _plugin_from_manifest(name: str, manifest: PluginManifest) -> Plugin:
|
|
"""Convert a parsed manifest into one runtime plugin descriptor."""
|
|
backends = tuple(
|
|
Backend(backend_name, _load_backend(target, plugin_name=name))
|
|
for backend_name, target in manifest.backends.items()
|
|
)
|
|
return Plugin(name=name, backends=backends, config=manifest.application_defaults)
|
|
|
|
|
|
def _load_plugin(name: str, entry: EntryPoint) -> Plugin:
|
|
"""Load declared contributions without retaining import-time registrations."""
|
|
if ":" in entry.value:
|
|
raise ValueError(f"Plugin '{name}' requires a package-only entry point and plugin.yaml")
|
|
with R.preserve(allow_mutation=True):
|
|
manifest = load_package_manifest(entry.value, plugin_name=name)
|
|
return _plugin_from_manifest(name, manifest)
|
|
|
|
|
|
class PluginManager:
|
|
"""Resolve enabled plugins and apply their contributions to one application."""
|
|
|
|
def __init__(self, plugins: Iterable[Plugin] = ()) -> None:
|
|
self.plugins = tuple(plugins)
|
|
|
|
@classmethod
|
|
def discover(cls, specs: Iterable[str]) -> "PluginManager":
|
|
"""Load explicitly enabled plugins by entry-point name."""
|
|
if isinstance(specs, (str, bytes, Mapping)):
|
|
raise TypeError("Plugin names must be an iterable of strings")
|
|
plugins: list[Plugin] = []
|
|
seen: set[str] = set()
|
|
for name in specs:
|
|
if not isinstance(name, str):
|
|
raise TypeError(f"Invalid plugin name: {name!r}")
|
|
if not name:
|
|
raise ValueError("Plugin name cannot be empty")
|
|
if name in seen:
|
|
raise ValueError(f"Plugin '{name}' is enabled more than once")
|
|
entries = find_entry_points(PLUGIN_ENTRY_POINT_GROUP, name)
|
|
entry = unique_entry_point(entries, name, provider="Plugin")
|
|
if entry is None:
|
|
raise ValueError(f"Plugin '{name}' is not installed")
|
|
plugin = _load_plugin(name, entry)
|
|
plugins.append(plugin)
|
|
seen.add(name)
|
|
return cls(plugins)
|
|
|
|
def merge_config(self, application_config: Mapping[str, Any]) -> dict[str, Any]:
|
|
"""Place plugin application defaults below the user's resolved config."""
|
|
merged: dict[str, Any] = {}
|
|
if not self.plugins:
|
|
return dict(application_config)
|
|
for plugin in self.plugins:
|
|
defaults = expand_env_vars(dict(plugin.config), defer_undefined=True)
|
|
merged = deep_merge_config(merged, defaults)
|
|
merged = deep_merge_config(merged, application_config)
|
|
_check_plugin_defaults(merged)
|
|
return merged
|
|
|
|
def register(self, registry: ComponentRegistry) -> None:
|
|
"""Register every backend into an application-local registry."""
|
|
for plugin in self.plugins:
|
|
for backend in plugin.backends:
|
|
registry.add(backend.name, backend.implementation, owner=plugin.name)
|
|
|
|
def build_runtime(self, application_config: Mapping[str, Any]) -> PluginRuntime:
|
|
"""Apply resolved plugins to an independent registry and config."""
|
|
registry = create_application_registry()
|
|
self.register(registry)
|
|
return PluginRuntime(config=self.merge_config(application_config), registry=registry)
|
|
|
|
|
|
def resolve_plugin_runtime(application_config: Mapping[str, Any]) -> PluginRuntime:
|
|
"""Build one local registry, with user config overriding plugin application defaults."""
|
|
manager = PluginManager.discover(configured_plugin_names(application_config))
|
|
return manager.build_runtime(application_config)
|