initial commit heh
This commit is contained in:
78 files changed
+11181
No files matched your search
@@ -0,0 +1,68 @@
|
||||
"""Dynamic extension and tool loader for HomeAgent."""
|
||||
|
||||
import importlib.util
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from homeagent.tools.registry import ToolRegistry, get_tool_registry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def load_extensions_from_directory(
|
||||
directory: Path,
|
||||
registry: Optional[ToolRegistry] = None,
|
||||
) -> int:
|
||||
"""Scan directory and import all tools from Python files.
|
||||
|
||||
Searches for:
|
||||
- <dir>/*.py
|
||||
- <dir>/*/tools.py
|
||||
- <dir>/*/__init__.py
|
||||
|
||||
Inspects each loaded module for functions decorated with @tool or a setup(registry) hook.
|
||||
"""
|
||||
if registry is None:
|
||||
registry = get_tool_registry()
|
||||
|
||||
if not directory.exists() or not directory.is_dir():
|
||||
logger.warning("Extensions directory '%s' does not exist.", directory)
|
||||
return 0
|
||||
|
||||
registered_count = 0
|
||||
|
||||
# Collect python files
|
||||
py_files: list[Path] = []
|
||||
for path in directory.rglob("*.py"):
|
||||
if path.name.startswith("_") and path.name != "__init__.py":
|
||||
continue
|
||||
py_files.append(path)
|
||||
|
||||
for py_file in py_files:
|
||||
module_name = f"homeagent_ext_{py_file.stem}_{abs(hash(str(py_file)))}"
|
||||
try:
|
||||
spec = importlib.util.spec_from_file_location(module_name, py_file)
|
||||
if spec is None or spec.loader is None:
|
||||
continue
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
# Check for explicit setup / register hook
|
||||
if hasattr(module, "register_tools") and callable(module.register_tools):
|
||||
module.register_tools(registry)
|
||||
elif hasattr(module, "setup") and callable(module.setup):
|
||||
module.setup(registry)
|
||||
|
||||
# Auto-discover any @tool functions in the module
|
||||
for attr_name in dir(module):
|
||||
attr = getattr(module, attr_name)
|
||||
if callable(attr) and hasattr(attr, "__tool_definition__"):
|
||||
registry.register(attr)
|
||||
registered_count += 1
|
||||
|
||||
logger.info("Loaded extension module from %s", py_file)
|
||||
except Exception as e:
|
||||
logger.error("Failed to load extension from %s: %s", py_file, e)
|
||||
|
||||
return registered_count
|
||||
Reference in new issue
Block a user