Plugin System

DeskBot has a plugin registry based on Python entry points. Plugins can subscribe to events, register new commands, and extend the application lifecycle without modifying the core codebase.


The Plugin protocol

Every plugin must implement the Plugin protocol. The lifecycle is:

flowchart LR load --> start --> stop --> unload
Hook Called when Purpose
load() Plugin is first loaded Register event handlers, set up resources
start() Application starts running Begin background tasks
stop() Application is shutting down Cancel background tasks
unload() Plugin is being removed Clean up persistent resources

Only info and load are required; the other hooks have safe no-op defaults.

PluginState

Each plugin has a PluginState that tracks its lifecycle:

stateDiagram-v2 UNLOADED --> LOADED LOADED --> STARTED STARTED --> STOPPED STOPPED --> UNLOADED LOADED --> ERRORED STARTED --> ERRORED ERRORED --> UNLOADED

PluginInfo

PluginInfo is a frozen dataclass with metadata about the plugin:

Field Type Description
name str Unique plugin identifier
version str Semantic version (default "0.1.0")
description str Human-readable description
author str Author name
depends tuple[str, ...] Names of plugins this one depends on

PluginRegistry

PluginRegistry manages the full lifecycle of every plugin and ensures dependency ordering:

from robot.plugins.registry import PluginRegistry
from robot.events.bus import InMemoryEventBus

bus = InMemoryEventBus()
registry = PluginRegistry(bus=bus)

# Register plugins
registry.register(my_plugin)

# Load and start all plugins (respects dependency order)
await registry.load_all()
await registry.start_all()

# Later, shut down
await registry.stop_all()
await registry.unload_all()

Registry API

Method Description
register(plugin) Register a plugin by name
unregister(name) Remove a plugin (must be UNLOADED or ERRORED)
load_all() Load all registered plugins in dependency order
start_all() Start all loaded plugins
stop_all() Stop all started plugins in reverse order
unload_all() Unload all plugins in reverse order
get(name) Return a plugin by name
list_plugins() Return info for all registered plugins
state_of(name) Return the current state of a plugin
discover_entry_points() Discover plugins from deskbot.plugins entry points

Plugins are loaded in topological order so that dependencies are satisfied. Circular dependencies raise a PluginError.


Entry-point discovery

A package can register a plugin via Python entry points:

[project.entry-points."deskbot.plugins"]
my_plugin = "my_package.plugins:MyPlugin"

Enable entry-point discovery with environment variables:

DESKBOT_PLUGINS__ENABLED=true
DESKBOT_PLUGINS__DISCOVER_ENTRY_POINTS=true

Explicit plugin packages can also be configured:

DESKBOT_PLUGINS__PLUGIN_PACKAGES='["my_package"]'

Example: a minimal plugin

"""A minimal plugin that subscribes to events."""

from robot.plugins.plugin import Plugin, PluginInfo, PluginState
from robot.events.bus import InMemoryEventBus
from robot.events.events import EmotionChanged


class GreetPlugin:
    """Logs a greeting whenever the robot changes emotion."""

    def __init__(self, bus: InMemoryEventBus) -> None:
        self._bus = bus
        self._sub_id: int | None = None

    @property
    def info(self) -> PluginInfo:
        return PluginInfo(
            name="greet",
            version="1.0.0",
            description="Logs a message on emotion changes",
        )

    async def load(self) -> None:
        # Subscribe to the event bus
        self._sub_id = self._bus.subscribe(EmotionChanged, self._on_emotion)

    async def start(self) -> None:
        pass  # No background tasks needed

    async def stop(self) -> None:
        pass  # No background tasks to cancel

    async def unload(self) -> None:
        # Remove the event handler
        if self._sub_id is not None:
            self._bus.unsubscribe(self._sub_id)

    async def _on_emotion(self, event: EmotionChanged) -> None:
        print(f"Emotion changed: {event.previous} -> {event.current}")

Built-in integrations (not plugins)

The MQTT bridge and Home Assistant discovery are app-level services wired directly into DeskBotApp, not plugins. See:

  • MQTT Bridge - publishes/subscribes events via MQTT.
  • Home Assistant - exposes the robot as an HA entity via MQTT Auto Discovery.

The calibration and settings web dashboards are served as static files by the API layer (see REST API), not as plugins.

The plugin system is the extension point for third-party capabilities. Plugins should use the event bus rather than reaching directly into unrelated application components.


API reference

robot.plugins.plugin.Plugin

Bases: Protocol

The plugin interface.

Implementations must provide info and load. The other hooks have safe defaults.

Source code in src/robot/plugins/plugin.py
@runtime_checkable
class Plugin(Protocol):
    """The plugin interface.

    Implementations must provide ``info`` and ``load``. The other hooks
    have safe defaults.
    """

    @property
    def info(self) -> PluginInfo:
        """Return plugin metadata."""
        ...

    async def load(self) -> None:
        """Called once when the plugin is first loaded.

        Use this to register event handlers, set up resources, etc.
        """
        ...

    async def start(self) -> None:
        """Called when the application starts running.

        Use this to begin background tasks.
        """
        ...

    async def stop(self) -> None:
        """Called when the application is shutting down.

        Use this to cancel background tasks and release resources.
        """
        ...

    async def unload(self) -> None:
        """Called when the plugin is being removed.

        Use this to clean up any persistent resources.
        """
        ...

info property

Return plugin metadata.

load() async

Called once when the plugin is first loaded.

Use this to register event handlers, set up resources, etc.

Source code in src/robot/plugins/plugin.py
async def load(self) -> None:
    """Called once when the plugin is first loaded.

    Use this to register event handlers, set up resources, etc.
    """
    ...

start() async

Called when the application starts running.

Use this to begin background tasks.

Source code in src/robot/plugins/plugin.py
async def start(self) -> None:
    """Called when the application starts running.

    Use this to begin background tasks.
    """
    ...

stop() async

Called when the application is shutting down.

Use this to cancel background tasks and release resources.

Source code in src/robot/plugins/plugin.py
async def stop(self) -> None:
    """Called when the application is shutting down.

    Use this to cancel background tasks and release resources.
    """
    ...

unload() async

Called when the plugin is being removed.

Use this to clean up any persistent resources.

Source code in src/robot/plugins/plugin.py
async def unload(self) -> None:
    """Called when the plugin is being removed.

    Use this to clean up any persistent resources.
    """
    ...

robot.plugins.plugin.PluginInfo dataclass

Metadata about a plugin.

Source code in src/robot/plugins/plugin.py
@dataclass(slots=True, frozen=True)
class PluginInfo:
    """Metadata about a plugin."""

    name: str
    version: str = "0.1.0"
    description: str = ""
    author: str = ""
    depends: tuple[str, ...] = ()

    def __hash__(self) -> int:
        return hash(self.name)

    def __eq__(self, other: object) -> bool:
        if isinstance(other, PluginInfo):
            return self.name == other.name
        return NotImplemented

robot.plugins.plugin.PluginState

Bases: str, Enum

Lifecycle states a plugin can be in.

Source code in src/robot/plugins/plugin.py
class PluginState(str, Enum):
    """Lifecycle states a plugin can be in."""

    UNLOADED = "unloaded"
    LOADED = "loaded"
    STARTED = "started"
    STOPPED = "stopped"
    ERRORED = "errored"

robot.plugins.registry.PluginRegistry

Manages plugin lifecycle: load, start, stop, unload.

Usage::

registry = PluginRegistry(bus=event_bus)
registry.register(my_plugin)
await registry.load_all()
await registry.start_all()
# ... later ...
await registry.stop_all()
await registry.unload_all()
Source code in src/robot/plugins/registry.py
class PluginRegistry:
    """Manages plugin lifecycle: load, start, stop, unload.

    Usage::

        registry = PluginRegistry(bus=event_bus)
        registry.register(my_plugin)
        await registry.load_all()
        await registry.start_all()
        # ... later ...
        await registry.stop_all()
        await registry.unload_all()
    """

    def __init__(self, bus: InMemoryEventBus) -> None:
        self._bus = bus
        self._plugins: OrderedDict[str, Plugin] = OrderedDict()
        self._states: dict[str, PluginState] = OrderedDict()

    # ------------------------------------------------------------------ register
    def register(self, plugin: Plugin) -> None:
        """Register a plugin by name.

        Raises :class:`PluginError` if a plugin with the same name is
        already registered.
        """
        name = plugin.info.name
        if name in self._plugins:
            raise PluginError(f"plugin {name!r} is already registered")
        self._plugins[name] = plugin
        self._states[name] = PluginState.UNLOADED

    def unregister(self, name: str) -> None:
        """Remove a plugin. Must be in UNLOADED or ERRORED state."""
        state = self._states.get(name)
        if state is None:
            raise PluginError(f"plugin {name!r} is not registered")
        if state not in (PluginState.UNLOADED, PluginState.ERRORED):
            raise PluginError(
                f"cannot unregister plugin {name!r} in state {state.value}; "
                "stop and unload it first"
            )
        del self._plugins[name]
        del self._states[name]

    # ------------------------------------------------------------------ lifecycle
    async def load_all(self) -> None:
        """Load all registered plugins in dependency order."""
        ordered = self._topological_sort()
        for name in ordered:
            plugin = self._plugins[name]
            try:
                await plugin.load()
                self._states[name] = PluginState.LOADED
                _log.info("plugin.loaded", name=name)
            except Exception:
                self._states[name] = PluginState.ERRORED
                _log.exception("plugin.load_failed", name=name)

    async def start_all(self) -> None:
        """Start all loaded plugins."""
        for name, plugin in self._plugins.items():
            if self._states[name] == PluginState.LOADED:
                try:
                    await plugin.start()
                    self._states[name] = PluginState.STARTED
                    _log.info("plugin.started", name=name)
                except Exception:
                    self._states[name] = PluginState.ERRORED
                    _log.exception("plugin.start_failed", name=name)

    async def stop_all(self) -> None:
        """Stop all started plugins in reverse order."""
        for name in reversed(list(self._plugins.keys())):
            if self._states[name] == PluginState.STARTED:
                try:
                    await self._plugins[name].stop()
                    self._states[name] = PluginState.STOPPED
                    _log.info("plugin.stopped", name=name)
                except Exception:
                    self._states[name] = PluginState.ERRORED
                    _log.exception("plugin.stop_failed", name=name)

    async def unload_all(self) -> None:
        """Unload all plugins in reverse order."""
        for name in reversed(list(self._plugins.keys())):
            if self._states[name] in (
                PluginState.LOADED,
                PluginState.STOPPED,
                PluginState.UNLOADED,
            ):
                try:
                    await self._plugins[name].unload()
                    self._states[name] = PluginState.UNLOADED
                    _log.info("plugin.unloaded", name=name)
                except Exception:
                    self._states[name] = PluginState.ERRORED
                    _log.exception("plugin.unload_failed", name=name)

    # ------------------------------------------------------------------ query
    def get(self, name: str) -> Plugin:
        """Return a plugin by name."""
        if name not in self._plugins:
            raise PluginError(f"plugin {name!r} not found")
        return self._plugins[name]

    def list_plugins(self) -> list[PluginInfo]:
        """Return info for all registered plugins."""
        return [p.info for p in self._plugins.values()]

    def state_of(self, name: str) -> PluginState:
        """Return the current state of a plugin."""
        return self._states.get(name, PluginState.UNLOADED)

    @property
    def plugin_count(self) -> int:
        return len(self._plugins)

    # ------------------------------------------------------------------ discovery
    def discover_entry_points(self) -> list[Plugin]:
        """Discover plugins from the ``deskbot.plugins`` entry point group.

        Returns a list of instantiated plugins. Call :meth:`register`
        to add them to this registry.
        """
        plugins: list[Plugin] = []
        try:
            # Python 3.12+ uses importlib.metadata directly.
            from importlib.metadata import entry_points

            eps = entry_points(group="deskbot.plugins")
            for ep in eps:
                try:
                    factory = ep.load()
                    plugin: Plugin = factory(bus=self._bus)
                    plugins.append(plugin)
                    _log.info("plugin.discovered", name=ep.name, module=ep.value)
                except Exception:
                    _log.exception("plugin.discovery_failed", entry_point=ep.name)
        except Exception:
            _log.warning("plugin.entry_points_unavailable")
        return plugins

    # ------------------------------------------------------------------ internal
    def _topological_sort(self) -> list[str]:
        """Sort plugins so dependencies come first."""
        visited: set[str] = set()
        order: list[str] = []
        visiting: set[str] = set()

        def visit(name: str) -> None:
            if name in visited:
                return
            if name in visiting:
                raise PluginError(f"circular dependency involving {name!r}")
            visiting.add(name)
            plugin = self._plugins.get(name)
            if plugin is not None:
                for dep in plugin.info.depends:
                    if dep not in self._plugins:
                        raise PluginError(
                            f"plugin {name!r} depends on {dep!r} which is not registered"
                        )
                    visit(dep)
            visiting.discard(name)
            visited.add(name)
            order.append(name)

        for name in self._plugins:
            visit(name)
        return order

discover_entry_points()

Discover plugins from the deskbot.plugins entry point group.

Returns a list of instantiated plugins. Call :meth:register to add them to this registry.

Source code in src/robot/plugins/registry.py
def discover_entry_points(self) -> list[Plugin]:
    """Discover plugins from the ``deskbot.plugins`` entry point group.

    Returns a list of instantiated plugins. Call :meth:`register`
    to add them to this registry.
    """
    plugins: list[Plugin] = []
    try:
        # Python 3.12+ uses importlib.metadata directly.
        from importlib.metadata import entry_points

        eps = entry_points(group="deskbot.plugins")
        for ep in eps:
            try:
                factory = ep.load()
                plugin: Plugin = factory(bus=self._bus)
                plugins.append(plugin)
                _log.info("plugin.discovered", name=ep.name, module=ep.value)
            except Exception:
                _log.exception("plugin.discovery_failed", entry_point=ep.name)
    except Exception:
        _log.warning("plugin.entry_points_unavailable")
    return plugins

get(name)

Return a plugin by name.

Source code in src/robot/plugins/registry.py
def get(self, name: str) -> Plugin:
    """Return a plugin by name."""
    if name not in self._plugins:
        raise PluginError(f"plugin {name!r} not found")
    return self._plugins[name]

list_plugins()

Return info for all registered plugins.

Source code in src/robot/plugins/registry.py
def list_plugins(self) -> list[PluginInfo]:
    """Return info for all registered plugins."""
    return [p.info for p in self._plugins.values()]

load_all() async

Load all registered plugins in dependency order.

Source code in src/robot/plugins/registry.py
async def load_all(self) -> None:
    """Load all registered plugins in dependency order."""
    ordered = self._topological_sort()
    for name in ordered:
        plugin = self._plugins[name]
        try:
            await plugin.load()
            self._states[name] = PluginState.LOADED
            _log.info("plugin.loaded", name=name)
        except Exception:
            self._states[name] = PluginState.ERRORED
            _log.exception("plugin.load_failed", name=name)

register(plugin)

Register a plugin by name.

Raises :class:PluginError if a plugin with the same name is already registered.

Source code in src/robot/plugins/registry.py
def register(self, plugin: Plugin) -> None:
    """Register a plugin by name.

    Raises :class:`PluginError` if a plugin with the same name is
    already registered.
    """
    name = plugin.info.name
    if name in self._plugins:
        raise PluginError(f"plugin {name!r} is already registered")
    self._plugins[name] = plugin
    self._states[name] = PluginState.UNLOADED

start_all() async

Start all loaded plugins.

Source code in src/robot/plugins/registry.py
async def start_all(self) -> None:
    """Start all loaded plugins."""
    for name, plugin in self._plugins.items():
        if self._states[name] == PluginState.LOADED:
            try:
                await plugin.start()
                self._states[name] = PluginState.STARTED
                _log.info("plugin.started", name=name)
            except Exception:
                self._states[name] = PluginState.ERRORED
                _log.exception("plugin.start_failed", name=name)

state_of(name)

Return the current state of a plugin.

Source code in src/robot/plugins/registry.py
def state_of(self, name: str) -> PluginState:
    """Return the current state of a plugin."""
    return self._states.get(name, PluginState.UNLOADED)

stop_all() async

Stop all started plugins in reverse order.

Source code in src/robot/plugins/registry.py
async def stop_all(self) -> None:
    """Stop all started plugins in reverse order."""
    for name in reversed(list(self._plugins.keys())):
        if self._states[name] == PluginState.STARTED:
            try:
                await self._plugins[name].stop()
                self._states[name] = PluginState.STOPPED
                _log.info("plugin.stopped", name=name)
            except Exception:
                self._states[name] = PluginState.ERRORED
                _log.exception("plugin.stop_failed", name=name)

unload_all() async

Unload all plugins in reverse order.

Source code in src/robot/plugins/registry.py
async def unload_all(self) -> None:
    """Unload all plugins in reverse order."""
    for name in reversed(list(self._plugins.keys())):
        if self._states[name] in (
            PluginState.LOADED,
            PluginState.STOPPED,
            PluginState.UNLOADED,
        ):
            try:
                await self._plugins[name].unload()
                self._states[name] = PluginState.UNLOADED
                _log.info("plugin.unloaded", name=name)
            except Exception:
                self._states[name] = PluginState.ERRORED
                _log.exception("plugin.unload_failed", name=name)

unregister(name)

Remove a plugin. Must be in UNLOADED or ERRORED state.

Source code in src/robot/plugins/registry.py
def unregister(self, name: str) -> None:
    """Remove a plugin. Must be in UNLOADED or ERRORED state."""
    state = self._states.get(name)
    if state is None:
        raise PluginError(f"plugin {name!r} is not registered")
    if state not in (PluginState.UNLOADED, PluginState.ERRORED):
        raise PluginError(
            f"cannot unregister plugin {name!r} in state {state.value}; "
            "stop and unload it first"
        )
    del self._plugins[name]
    del self._states[name]

robot.plugins.registry.PluginError

Bases: DeskBotError

Plugin lifecycle or dependency error.

Source code in src/robot/plugins/registry.py
class PluginError(DeskBotError):
    """Plugin lifecycle or dependency error."""