Coverage for little_loops / extension.py: 85%
55 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-04-02 13:03 -0500
« prev ^ index » next coverage.py v7.12.0, created at 2026-04-02 13:03 -0500
1"""Extension system for little-loops.
3Provides the extension Protocol, a reference implementation, and discovery/loading
4utilities for external packages to hook into little-loops via structured events.
6Public exports:
7 LLExtension: Protocol that extensions must satisfy
8 NoopLoggerExtension: Reference extension that logs events to a JSONL file
9 ExtensionLoader: Discovers and loads extensions from config and entry points
10"""
12from __future__ import annotations
14import importlib
15import json
16import logging
17from importlib.metadata import entry_points
18from pathlib import Path
19from typing import Any, Protocol, runtime_checkable
21from little_loops.events import LLEvent
23logger = logging.getLogger(__name__)
25ENTRY_POINT_GROUP = "little_loops.extensions"
28@runtime_checkable
29class LLExtension(Protocol):
30 """Protocol for little-loops extensions.
32 Any class with an ``on_event`` method matching this signature is a valid
33 extension. Extensions receive structured events from the EventBus.
34 """
36 def on_event(self, event: LLEvent) -> None:
37 """Handle an event from little-loops.
39 Args:
40 event: Structured event with type, timestamp, and payload
41 """
42 ...
45class NoopLoggerExtension:
46 """Reference extension that logs events to a JSONL file.
48 Demonstrates the extension API by writing each event as a JSON line
49 to a specified log file. Useful for debugging and as a template for
50 building custom extensions.
51 """
53 def __init__(self, log_path: Path | None = None) -> None:
54 self._log_path = log_path or Path(".ll/extension-events.jsonl")
55 self._log_path.parent.mkdir(parents=True, exist_ok=True)
57 def on_event(self, event: LLEvent) -> None:
58 """Append event to JSONL log file."""
59 with open(self._log_path, "a", encoding="utf-8") as f:
60 f.write(json.dumps(event.to_dict()) + "\n")
63class ExtensionLoader:
64 """Discover and load extensions from config paths and entry points."""
66 @staticmethod
67 def from_config(extension_paths: list[str]) -> list[LLExtension]:
68 """Load extensions from dotted module paths.
70 Each path should be in the format "module.path:ClassName".
71 Extensions that fail to load are skipped with a warning.
73 Args:
74 extension_paths: List of "module:Class" strings
76 Returns:
77 List of successfully loaded extension instances
78 """
79 extensions: list[Any] = []
80 for path in extension_paths:
81 try:
82 module_path, class_name = path.rsplit(":", 1)
83 module = importlib.import_module(module_path)
84 cls = getattr(module, class_name)
85 extensions.append(cls())
86 except Exception:
87 logger.warning("Failed to load extension from config: %s", path, exc_info=True)
88 return extensions
90 @staticmethod
91 def from_entry_points() -> list[LLExtension]:
92 """Discover extensions via importlib.metadata entry points.
94 Looks for entry points in the "little_loops.extensions" group.
96 Returns:
97 List of successfully loaded extension instances
98 """
99 extensions: list[Any] = []
100 try:
101 eps = entry_points(group=ENTRY_POINT_GROUP)
102 except TypeError:
103 # Python 3.11 compatibility: entry_points() may not support group kwarg
104 eps = entry_points().get(ENTRY_POINT_GROUP, []) # type: ignore[attr-defined, assignment]
105 for ep in eps:
106 try:
107 cls = ep.load()
108 extensions.append(cls())
109 except Exception:
110 logger.warning("Failed to load extension entry point: %s", ep.name, exc_info=True)
111 return extensions
113 @staticmethod
114 def load_all(config_paths: list[str] | None = None) -> list[LLExtension]:
115 """Load extensions from all discovery sources.
117 Combines extensions from config paths and entry points.
119 Args:
120 config_paths: Optional list of "module:Class" strings from config
122 Returns:
123 Combined list of all loaded extensions
124 """
125 extensions: list[Any] = []
126 if config_paths:
127 extensions.extend(ExtensionLoader.from_config(config_paths))
128 extensions.extend(ExtensionLoader.from_entry_points())
129 return extensions