Files
leocrm/app/plugins/builtins/ai_assistant/plugin.py
T
Agent Zero 98eb1d0d89
Check Cross-Plugin Imports / check (push) Has been cancelled
feat: Plugin-System Umbau — 6 Phasen komplett abgeschlossen
Phase 1: Contracts konsequent nutzen
- 12 neue contracts.py erstellt (alle 19 Plugins haben jetzt contracts)
- 4 bestehende contracts.py an zentrale ContractRegistry angepasst
- Alle 19 Plugins haben on_deactivate mit Contract-Unregister
- 0 echte problematische INTER-Plugin Imports

Phase 2: Hooks/Filters-System
- app/core/hooks.py (HookRegistry mit actions + filters)
- 15 Hook-Punkte in Core-Services (contact, auth, mail, calendar, user, dms)
- BasePlugin.on_deactivate meldet alle Hooks ab

Phase 3: Plugin-Isolation
- scripts/check_cross_plugin_imports.py (Linting-Regel)
- .github/workflows/check-cross-plugin-imports.yml (CI/CD)
- .pre-commit-cross-plugin.yaml (Pre-commit Hook)
- 155 Dateien geprueft, 0 Verstoesse

Phase 4: Plugin-Versioning
- app/plugins/semver.py (SemVer mit Parse, Compare, Pre-release)
- migration_runner.py erweitert: run_migration_down, rollback_to_version
- manifest.py: min_app_version Feld
- registry.py: App-Version-Compatibility-Check bei Installation
- GET /api/v1/plugins/updates Endpoint

Phase 5: Marketplace-Vorbereitung
- app/plugins/signature.py (Ed25519 Signatur-Validierung)
- app/plugins/quarantine.py (Plugin-Quarantine mit Validierung)
- app/models/plugin_allowlist.py + Migration 0046
- manifest.py: author, license, homepage, icon, screenshots, changelog, marketplace_tags, price
- registry.py: discover_external(), discover_all()
- POST /api/v1/plugins/install-marketplace (deaktiviert)

Phase 6: Manifest-Anpassung
- manifest.py: 12 neue Felder + SemVer/Hook-Name Validierung
- MANIFEST_SCHEMA_DOC aktualisiert
- Alle 19 Plugin-Manifeste aktualisiert
- Frontend PluginUiManifest Typ erweitert

Zusaetzliche Bug-Fixes:
- test_sample-Modul erstellt
- conftest.py Deadlock-Prevention
- SESSION_COOKIE_SECURE=true
- dump.rdb aus Git entfernt + .gitignore
- backup.py datetime.utcnow -> func.now()
- system_settings.py JSONB-Import nach oben
- tax.py Mapped[float] -> Mapped[Decimal]
- notification.py type_key-Laengen vereinheitlicht

Tests: 91 neue Tests, alle bestanden
2026-07-26 23:15:34 +02:00

155 lines
6.0 KiB
Python

"""AI Assistant plugin — multi-provider LLM chat, agents, tools."""
from __future__ import annotations
import logging
from typing import Any
from app.plugins.base import BasePlugin
from app.plugins.manifest import PluginManifest, PluginRouteDef, FrontendMenuItem, FrontendPageRoute, FrontendSettingsPage
logger = logging.getLogger(__name__)
class AIAssistantPlugin(BasePlugin):
"""AI Assistant plugin: multi-provider LLM chat with agents and tools."""
manifest = PluginManifest(
name="ai_assistant",
version="1.0.0",
display_name="KI Assistent",
description=(
"AI Assistant with multi-provider LLM support, custom agents, "
"plugin tools, and streaming chat."
),
dependencies=["kommunikation"],
routes=[
PluginRouteDef(
path="/api/v1/ai",
module="app.plugins.builtins.ai_assistant.routes",
router_attr="router",
),
],
events=[],
migrations=["0001_initial.sql", "0002_folders_attachments.sql"],
permissions=[
"ai:read",
"ai:write",
"ai:config",
"ai:agents",
"ai:tools",
],
is_core=True,
menu_items=[
FrontendMenuItem(label_key='nav.aiAssistant', label='KI Assistent', path='/ai-assistant', icon='Bot', order=90),
],
page_routes=[
FrontendPageRoute(path='/ai-assistant', component='@/pages/AIAssistant', protected=True),
],
settings_pages=[
FrontendSettingsPage(path='ai', label_key='settings.ai', label='AI Settings', component='@/pages/AISettings', icon='Bot', order=60),
],
author="LeoCRM Team",
min_app_version="1.0.0",
hooks=["contact.after_create", "contact.after_update"],
contract_version="1.0.0",
)
def __init__(self) -> None:
super().__init__()
self._ai_handler = None
self._msg_handler = None
async def on_install(self, db, service_container) -> None:
"""Seed default provider and agent."""
from app.plugins.builtins.ai_assistant.services import seed_defaults
await seed_defaults(db)
async def on_activate(self, db, service_container, event_bus) -> None:
"""Activate plugin: register CRM API tool and participant handler."""
await super().on_activate(db, service_container, event_bus)
# Register the generic CRM API tool — gives AI full system access
try:
from app.plugins.builtins.ai_assistant.crm_api_tool import register_crm_api_tool
from app.plugins.builtins.ai_assistant.tool_registry import get_tool_registry
register_crm_api_tool(get_tool_registry())
logger.info("CRM API tool registered — AI has full system access")
except Exception:
logger.exception("Failed to register CRM API tool")
# Register as participant in the kommunikation system
try:
from app.plugins.builtins.ai_assistant.participant_handler import (
AIParticipantHandler,
)
from app.plugins.builtins.kommunikation.contracts import (
get_participant_registry,
)
self._ai_handler = AIParticipantHandler(service_container)
get_participant_registry().register("ai", self._ai_handler)
print("[STARTUP] AI Assistant registered as participant 'ai'", flush=True)
logger.info("AI Assistant registered as participant 'ai'")
except Exception as e:
print(f"[STARTUP] Failed to register AI Assistant as participant: {e}", flush=True)
logger.exception("Failed to register AI Assistant as participant")
# Subscribe to message.received events
try:
self._msg_handler = self._on_message_received
event_bus.subscribe("message.received", self._msg_handler)
logger.info("AI Assistant subscribed to message.received events")
except Exception:
logger.exception("Failed to subscribe to message.received events")
async def _on_message_received(self, payload: dict[str, Any]) -> None:
"""Handle message.received event by delegating to the AI participant handler."""
if self._ai_handler is None:
return
try:
await self._ai_handler.handle_event(payload)
except Exception:
logger.exception("Error in AI participant handler for message.received")
async def on_deactivate(self, db, service_container, event_bus) -> None:
"""Deactivate plugin: unregister participant and event subscriptions."""
# Contract abmelden
from app.plugins.builtins.contracts import get_contract_registry
get_contract_registry().unregister(self.manifest.name)
# Unregister from participant registry
try:
from app.plugins.builtins.kommunikation.contracts import (
get_participant_registry,
)
get_participant_registry().unregister("ai")
logger.info("AI Assistant unregistered as participant 'ai'")
except Exception:
logger.exception("Failed to unregister AI Assistant as participant")
# Unsubscribe from message.received events
if self._msg_handler:
try:
event_bus.unsubscribe("message.received", self._msg_handler)
except Exception:
logger.exception("Failed to unsubscribe from message.received events")
self._msg_handler = None
self._ai_handler = None
await super().on_deactivate(db, service_container, event_bus)
def get_notification_types(self) -> list[dict[str, Any]]:
return [
{
"type_key": "ai_response_error",
"category": "ai",
"label": "KI Antwort-Fehler",
"description": "Fehler bei der KI-Antwortgenerierung",
"is_enabled_by_default": True,
},
]