# Copyright (C) 2026 Mattia Zatelli # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . """ Base plugin class for the modular intent system. BaseIntentPlugin extends the existing BaseIntentHandler to inherit all query-building, aggregation, and result-creation helpers while adding plugin-specific metadata and auto-dispatch capabilities. """ import logging from dataclasses import dataclass, field from typing import Dict, List, Optional, Any from datetime import datetime from sqlalchemy.ext.asyncio import AsyncSession from app.models import Project from app.schemas.intent import SingleQueryPlan, SingleQueryResult from app.services.intent_handlers.base_handler import BaseIntentHandler logger = logging.getLogger(__name__) @dataclass class AuthorInfo: """Author information for the plugin.""" name: str url: Optional[str] = None @dataclass class SubIntentMetadata: """Metadata for a single sub-intent declared in manifest.yaml.""" id: str description: str examples: Dict[str, List[str]] = field(default_factory=dict) handler_method: str = "" @dataclass class IntentMetadata: """Metadata loaded from manifest.yaml.""" id: str version: str name: str description: str category: str enabled: bool priority: int author: AuthorInfo sub_intents: Dict[str, SubIntentMetadata] = field(default_factory=dict) i18n: Dict[str, Any] = field(default_factory=dict) prompt_fragment: Optional[str] = None depends_on: List[str] = field(default_factory=list) test_fixtures: Optional[str] = None class BaseIntentPlugin(BaseIntentHandler): """Base class for all intent plugins. Extends BaseIntentHandler to inherit all existing helpers: - build_base_query() - execute_aggregation() - create_result() - _apply_filter_to_query() / _apply_filter_group_to_query() - _apply_scope_to_query() - _get_filter_value() / _has_filter() / _create_filter_group() - get_element_provenance() - determine_presentation_format() - handle_custom_subintent() - _get_element_type_name() Each plugin overrides handler methods decorated with @sub_intent. The dispatcher calls these directly — no if/elif chains needed. """ # Loaded by the registry from manifest.yaml metadata: Optional[IntentMetadata] = None def __init__(self): super().__init__() async def handle( self, query_plan: SingleQueryPlan, project: Project, session: AsyncSession, context: Optional[Dict] = None ) -> SingleQueryResult: """Auto-dispatch to the correct @sub_intent method. The IntentDispatcher resolves query_plan.subtype to the decorated method. This default implementation is used when the dispatcher calls plugin.handle() directly — it looks up the sub-intent method on this instance. """ start_time = datetime.now() handler_method = self._find_sub_intent_handler(query_plan.subtype) if not handler_method: # Fall back to custom sub-intent handler for *.custom.* slugs if ".custom." in (query_plan.subtype or ""): logger.info( f"Falling back to custom handler for '{query_plan.subtype}' " f"in {self.__class__.__name__}" ) return await self.handle_custom_subintent( query_plan, project, session, context ) raise RuntimeError( f"No handler found for sub-intent '{query_plan.subtype}' " f"in {self.__class__.__name__}" ) result = await handler_method(query_plan, project, session, context) processing_time = int( (datetime.now() - start_time).total_seconds() * 1000 ) result.processing_time_ms = processing_time return result def _find_sub_intent_handler(self, sub_intent_id: str): """Look up the method decorated with @sub_intent for the given ID.""" for attr_name in dir(self): attr = getattr(self, attr_name, None) if callable(attr) and hasattr(attr, "_sub_intent_id"): if attr._sub_intent_id == sub_intent_id: return attr return None def get_registered_sub_intents(self) -> Dict[str, Any]: """Return a map of sub_intent_id -> bound method for all decorated methods.""" result = {} for attr_name in dir(self): attr = getattr(self, attr_name, None) if callable(attr) and hasattr(attr, "_sub_intent_id"): result[attr._sub_intent_id] = attr return result