Skip to content

Architecture

This section provides a developer-oriented overview of the AI Context module's architecture.

Installing via recipe or config sync? See Recipe and config-sync installs for what config to import and a working example recipe.

Entities

The module defines two entity types:

ai_context_item (content entity)

The primary entity. Stores context text (markdown), scope values, target entity references, parent-child relationships, and moderation state. Extends EditorialContentEntityBase with translation and revision support. The entity type is bundleless.

  • Base table: ai_context_item
  • Data table: ai_context_item_field_data
  • Revision tables: ai_context_item_revision, ai_context_item_field_revision

Publishing defaults (default_status, new_revision) are stored in ai_context.settings and edited via AiContextItemSettingsForm at /admin/config/ai/context/settings/items. Scheduler settings for the entity type use Scheduler's no-bundle settings form (scheduler.no_bundle_entity_type_settings.ai_context_item).

ai_context_usage (content entity)

Stores usage tracking records -- which context items were selected, by which consumer, on which route, and which tools/entities were involved.

Plugin system

AiContextScope plugins

The scope system is built on Drupal's plugin API. Scope plugins define categories/dimensions for context items. See Scope API and Custom scopes.

AiContextConsumerType plugins

Consumer types describe how a kind of thing receives context. AI Context ships the agent and automator types. Other types belong in the consuming project unless they only read public entity storage and emitted request tags. See Consumer type API.

AiFunctionCall plugins

The module provides three function call plugins in the Context Tools (context_tools) function group for discovery, loading, and relevance-based selection:

  • ai_context:list_ai_context_items
  • ai_context:load_ai_context_item_by_id
  • ai_context:get_relevant_ai_context_items

See Function calls.

Services

The module registers over 20 services covering scope management, context selection, rendering, usage tracking, event handling, and routing. The selection factory also provides convenience methods for callers that do not use a saved consumer row. See Services for the full reference.

Before depending on a service or class from contrib code, check API stability, which defines the public surface (selection factory, selection/result models, selector pipeline events, scope plugins, consumer type plugins) versus the internal selector pipeline and supporting services. For permission and entity access rules, see Access boundaries.

Event subscribers

Four event subscribers integrate with the module:

  • AiContextBuildSystemPromptSubscriber -- appends selected context to agent system prompts via the AI Agents module (respects loop-aware injection when enabled)
  • AiContextPreGenerateResponseSubscriber -- appends selected context to generic chat provider calls via PreGenerateResponseEvent
  • AiContextAgentToolSubscriber -- tracks entity modifications by agent tools via the AI Agents module
  • AiContextScopeConfigSubscriber -- asks opted-in scope plugins to scrub stored values when their settings config is saved (skipped during config import)

Contrib modules may also subscribe to selector pipeline events to alter or observe selection output.

See Events.

Hooks

The module implements several hooks and provides alter hooks for scope plugin definitions and scope values. hook_modules_uninstalled() runs a full stale-value scrub after another module is uninstalled. See Hooks.

Key data flows

Context selection pipeline (generic chat path)

  1. AiContextPreGenerateResponseSubscriber listens for PreGenerateResponseEvent at priority -100
  2. Exits unless the operation is chat and a consumer type can match the request tags
  3. AiContextProviderRequestContextFactory builds a snapshot and the router claims a consumer
  4. Builds an AiContextSelection via AiContextSelectionFactory::fromConsumer() using the latest user message as the task and entity_context as the entity
  5. The same selector pipeline as the agent path runs
  6. Final text is appended to the chat input system prompt
  7. An ai_context invocation result is written to event metadata and input debug data

See Events.

Context selection pipeline (agent path)

  1. AiContextBuildSystemPromptSubscriber listens for BuildSystemPromptEvent
  2. Passes BuildSystemPromptEvent payload values to AiContextRequestInfoResolver::applyRequestInfo()
  3. Builds an AiContextSelection via AiContextSelectionFactory::fromConsumer()
  4. The selection factory invokes the internal selector pipeline (loading, prefiltering, scoring, subcontext resolution, rendering)
  5. AiContextScopeResolver applies hard context filters and scores items against the selection's scope subscriptions
  6. AiContextSubcontextResolver resolves child items for selected parents (skipped when subcontext_enabled is FALSE in ai_context.settings)
  7. AiContextSelectionEvents::ITEMS_SELECTED fires; subscribers may filter or replace the final item list (see Events)
  8. AiContextRenderer renders items within the token limit
  9. AiContextSelectionEvents::TEXT_RENDERED fires; subscribers may alter rendered text or merge cache metadata before the result is built
  10. Final text is appended to the agent's system prompt

See Context Selection for the complete site-builder-facing pipeline and Scope API for the scoring formula.

Context access (non-agent path)

Non-agent modules can use the convenience methods on ai_context.selection_factory:

  1. Caller invokes getRenderedContext() or getResult() on the factory
  2. Factory internally builds an AiContextSelection via fromParameters()
  3. Runs the internal selector pipeline (including selector pipeline events)
  4. Returns rendered text or the full AiContextSelectionResult

Subcontext integrity

Subcontext is gated by the Enable subcontext hierarchy setting in ai_context.settings (subcontext_enabled). When disabled, parent/type fields are cleared on save and AiContextSubcontextResolver is not invoked during selection.

Subcontext relationships are enforced as a persistence contract on ai_context_item entities, not only during context selection. The entity validation layer prevents self-parenting, nested subcontexts, and converting items with children into subcontexts. It also requires subcontext_type when a parent is selected. Parent deletion clears child parent and subcontext_type references.

See Services for the validator and hierarchy services, Subcontext for site-builder guidance, and Hooks for constraint registration and delete cleanup.

Usage tracking pipeline

  1. AiContextBuildSystemPromptSubscriber captures the runner ID on AgentStartedExecutionEvent
  2. After context selection, records usage via AiContextUsageTracker
  3. AiContextAgentToolSubscriber listens for AgentToolFinishedExecutionEvent and records tool usage and entity modifications