Hooks
The AI Context module implements several hooks and provides two alter hooks for third-party modules.
Alter hooks
hook_ai_context_scope_info_alter()
Allows modules to add, modify, or remove scope plugin definitions before
they are used for discovery, settings tabs, and matching. Called from
AiContextScopeManager via alterInfo('ai_context_scope_info').
Use this to hide or replace scope plugins based on site configuration or optional module availability.
function hook_ai_context_scope_info_alter(array &$definitions): void {
if (!\Drupal::moduleHandler()->moduleExists('my_optional_module')) {
unset($definitions['my_scope']);
}
$definitions['department']['icon_class'] = 'ai-icon--scope-department';
}
Parameters:
$definitions-- scope plugin definitions keyed by plugin ID (by reference)
API group: @ingroup ai_context_scope_api
hook_ai_context_scope_values_alter()
Allows modules to add, modify, or remove values from any scope plugin.
Called when scope values are retrieved for display in forms, labels,
filters, and other display paths via
AiContextScopeInterface::getAlteredValues(). Matching uses stored value
IDs directly and does not invoke this hook.
function hook_ai_context_scope_values_alter(
array &$values,
string $scope_id,
?\Drupal\Core\Cache\CacheableMetadata $cache = NULL,
): void {
if ($scope_id === 'use_case') {
$values['custom_workflow'] = t('Custom Workflow');
}
if ($scope_id === 'language') {
unset($values['und']);
}
if ($cache) {
$cache->addCacheTags(['config:my_module.settings']);
}
}
Parameters:
$values-- associative array ofvalue_id => labelpairs (by reference)$scope_id-- plugin ID of the scope (e.g.,use_case,language)$cache-- optionalCacheableMetadatawhen labels are collected for a cached display. Add tags or contexts for sources the altered labels depend on. Existing two-argument implementations remain valid.
API group: @ingroup ai_context_scope_api
No consumer-type definition alter
There is no hook_ai_context_consumer_type_info_alter(). Consumer
type discovery is not alterable. Use the enabled key on
ai_context.consumer_type_settings.{type} to turn automatic push
off for every instance of that type. A disabled type still appears
in listings; pull-based tools keep working. See
Consumer type API.
Implemented hooks
hook_ENTITY_TYPE_insert() for ai_context_item
When a context item is inserted, adds its scope values to the denormalized
scope index table via ai_context.scope_index.
Implemented in ai_context_ai_context_item_insert() in ai_context.module.
hook_ENTITY_TYPE_update() for ai_context_item
When a context item is updated, refreshes its scope index rows. If the item is a parent and its scope values changed, reindexes inheriting children so their indexed scope mirrors the parent.
Implemented in ai_context_ai_context_item_update() in ai_context.module.
hook_ENTITY_TYPE_delete() for ai_context_item
When a parent context item is deleted, clears the parent and
subcontext_type fields from all children to prevent orphaned references.
Also removes the item's rows from the scope index.
Implemented in ai_context_ai_context_item_delete() in ai_context.module.
hook_entity_delete()
When a non-context-item entity is deleted, asks opted-in scope plugins
whether to scrub stored values
(AiContextScopeStoredValueInterface::shouldScrubAfterEntityDelete()),
then clears entity item references from context items that pointed at
the deleted entity. Removing the last value that limited an item can
unpublish that item. Deleting a host entity also removes its matching
row from ai_context.consumers when a consumer type maps that
entity (Agent: ai_agent → agent:{id}, Automator:
ai_automator → automator:{id}). Disabled and unavailable
types are still asked. A type that fails to instantiate or map
is skipped and logged so one broken plugin cannot abort the
delete.
A consumer row is removed only when a host entity is deleted outside a module uninstall. A delete during an uninstall is the type going away, not an admin removing one consumer, so the saved override survives. The consumers listing shows it as Off (type unavailable), or as Off (stale) when the consumer type is still installed. Core deletes host entities at several points during an uninstall:
ConfigManager::uninstall()marks each config entity it deletes withisUninstalling(). Those deletes skip consumer cleanup. This covers host entities deleted while a different module is torn down in the same run, for example an automator with an enforced dependency on a module that requiresai_automators.- Earlier,
ModuleInstaller::uninstall()deletes every bundle of the module's entity types. Field configs on those bundles are deleted, and their dependents are deleted withoutisUninstalling(). An automator on a field of anautomator_chainbundle is deleted this way whenai_automatorsis uninstalled. Its row is removed like any host entity delete, recorded for the request, and restored byhook_modules_uninstalled(). - A module's own
hook_uninstall()runs beforeConfigManager::uninstall(), so host entities it deletes carry noisUninstalling()either. They are recorded and restored the same way.
Availability cannot decide this: core clears core.extension only
after the config entities are gone, so the type still reports as
installed while the deletes run. Config sync is not special-cased:
the host entities are deleted the same way. After the extension step,
core imports ai_context.consumers from the sync source again, so
the synced file decides which rows remain.
Implemented in ai_context_entity_delete() in ai_context.module.
hook_module_preuninstall()
Before Dynamic Entity Reference is uninstalled, captures the Specific Entities references held by historical context item revisions. The capture is kept in State until the uninstall succeeds; it does not change revision logs while their values are still present. An earlier confirmed capture must be recovered before a new one replaces it.
Implemented in ai_context_module_preuninstall() in
ai_context.module.
hook_uninstall()
Removes the CCC tools from every AI agent and keeps the agents. AI Agents
1.3 makes an agent depend on the module that provides each of its tools, so
core would otherwise delete every agent with a CCC tool. The cleanup
removes the CCC tools from the agent tools, tool settings, tool usage limits
and default information tools, and logs a notice that names the changed
agents. A CCC tool is a tool whose ID starts with ai_context:, or whose
plugin provider or module dependencies include ai_context. An agent that
still depends on ai_context without a CCC tool is saved too, so that its
dependencies are calculated again. An agent with an enforced dependency on
ai_context does not change, and core deletes it. The other tools and
settings of the agent do not change.
The cleanup also removes the CCC tools from the tools to add, the tools to remove, the tool settings and the tool usage limits of AI agent overrides (AI Agents 1.3 and later), and logs a notice that names the changed overrides. Otherwise an override adds a missing tool back to its agent, and the agent fails.
The uninstall confirm form still lists the agents with a CCC tool as configuration to delete, because it is built before this hook runs. The agents are kept.
Also revokes the role permissions that core cannot handle while CCC is uninstalled: those of the AI Context editorial workflow, the permission to translate context items and Scheduler's permissions for context items. Otherwise core logs an error, leaves them on the role, or deletes a role that depends on CCC only through them. Then deletes the workflow, and the Diff and Scheduler settings for context items.
Implemented in ai_context_uninstall() in ai_context.install.
hook_entity_bundle_delete()
When a bundle is deleted, asks opted-in scope plugins whether to scrub
stored values
(AiContextScopeStoredValueInterface::shouldScrubAfterBundleDelete()).
Removing the last value that limited an item can unpublish that item.
Entity Types keeps a type-level All value (type:_all), because All
still means every current and future bundle of that type.
Implemented in ai_context_entity_bundle_delete() in ai_context.module.
hook_modules_uninstalled()
First puts back the ai_context.consumers rows removed during this
request, skipping rows that are present again. These are host entities that
core deleted during bundle cleanup or a module's hook_uninstall(),
without isUninstalling() (see hook_entity_delete() above). The
restore also runs during config synchronization, but there it only
keeps active config consistent between the import steps: core imports
ai_context.consumers from the sync source again after the extension
step. The removed rows are held in ai_context.removed_consumer_rows,
which is tagged persist so they survive the container rebuilds
during an uninstall. When stored config repeats a consumer ID, only
the first row is put back, because the first row is the one that
takes effect (see Consumer API). A row removed
earlier in the same request, before an uninstall starts, is also
restored. Only code that deletes a host entity and then uninstalls a module
in the same process, such as a script or an update hook, can reach
this, and the result is a kept row an admin can remove.
Uninstalling a module that provided entity types, vocabularies, or languages does not fire the per-option delete hooks for leftover stored values. This hook then asks every opted-in plugin to drop what is now stale, including stale values on restored rows. Dropping the last value that limited an item can unpublish that item.
After a successful Dynamic Entity Reference uninstall, it also writes the captured references into affected revision logs. That write runs during config synchronization too. If it fails, the confirmed notes remain in State and cron retries them; the other uninstall hooks and core cache flush still run.
The hook does nothing when ai_context itself is being uninstalled.
It skips the stale-value scrub during config synchronization: sync
processes extension changes before config values, so a scrub then
would compare stored values to a half-imported environment.
Implemented in ai_context_modules_uninstalled() in ai_context.module.
hook_entity_type_build()
Registers the AiContextItemIntegrity constraint on ai_context_item so
subcontext integrity rules are enforced through entity validation and storage
pre-save checks.
hook_cron()
Purges old usage records based on configured limits (usage_max_records
and usage_max_age). It also retries confirmed revision notes from a
successful Dynamic Entity Reference uninstall. Runs during each cron
execution.
hook_theme()
Registers theme hooks:
ai_context_overview-- the overview dashboard pageai_context_pill_list-- renders a list of labels as pill-style tags. By default the first two labels stay visible and the rest collapse into a+Npill (max_visible, default 2).max_visible0 puts every label in+N. Long labels use an ellipsis (truncate, default TRUE). PasstruncateFALSE to keep the full label, as the consumer listing does for count pills.AiContextThemeHooks::preprocessAiContextPillList()encodes tooltip values soPrice <10stays readable and markup cannot execute afterai/ai_global.jsassignsdata-ai-tooltiptoinnerHTML. A LegacyHook bridge covers Drupal 10.ai_context_item-- entity theme hook; full view usesai-context-item--full.html.twig, default view usesai-context-item.html.twig. Template suggestions are added inhook_theme_suggestions_ai_context_item(). Initial preprocess is registered inAiContextThemeHooks::theme()and implemented byAiContextThemeHooks::preprocessAiContextItem(), which delegates toAiContextItemViewBuilder. The hook class is autowired inai_context.services.ymlvia theAiContextItemViewBuilderclass alias.
hook_local_tasks_alter()
Conditionally shows or hides the Overview tab based on the
show_overview_page setting.
hook_menu_local_tasks_alter()
Hides the derived per-type and per-scope tab group (including its "All"
tab) on the Consumer Types and Scope overview routes, where it would
otherwise merge into the Settings trail. Implemented in
AiContextLocalTaskHooks, registered in ai_context.services.yml with
a LegacyHook bridge for Drupal 10.
Main menu link deriver
AiContextMainMenuLinkDeriver, declared in ai_context.links.menu.yml,
provides one optional link when main_menu_enabled is on. The derived link
uses main_menu_title and the ai_context.context_redirect route. With
Navigation installed it belongs to the Navigation content menu; otherwise
it belongs to the admin menu under system.admin. Sites running both
Navigation and Toolbar show this link in Navigation only. Turning the link on
or off, or changing its title while it is on, requests a deferred router
rebuild, which also rebuilds menu links; see
ai_context.settings_config_subscriber.
hook_toolbar_alter()
Adds the config:system.menu.admin cache tag to the Toolbar admin tray. Core
only tags a rendered menu with its menu when it has items, so a user whose tray
was empty would otherwise keep a cached empty tray after the item is turned on.
The menu rebuild invalidates this tag. Implemented in ai_context.module.
hook_module_implements_alter()
Changes the order of three groups of hooks:
- The module's Scheduler hide-date hooks run before the hooks of Scheduler Content Moderation Integration, so missing state field storage is installed first.
- The module's
hook_form_alter()runs after Scheduler's, so it can modify Scheduler form elements. - The module's
hook_entity_insert()andhook_entity_update()run after the hooks of Content Moderation. See the next section.
Drupal 11.2 deprecates hook_module_implements_alter() without a
#[LegacyModuleImplementsAlter] attribute, and Drupal 12.0 removes it. On
Drupal 12, this order must come from the order argument of #[Hook].
hook_entity_insert() and hook_entity_update()
Save the other translations of a detached subcontext item. When Enable subcontext hierarchy is off, a save detaches an item from its parent. A child that used the scope of its parent then has no scope, so every published translation is unpublished, not only the saved one.
Content Moderation stores the moderation state of the saved translation only, in its own insert and update hooks. These hooks run after those of Content Moderation and save each other translation in its own revision, in the same database transaction. When Content Moderation keeps the save as a pending revision, the hooks archive its published default revision only if that revision also relies on its parent's scope. The archiving revisions are based on the saved revision so the latest revision keeps the editor's text.
When the workflow has no unpublished default-revision state, the item cannot be unpublished. It stays published, and an error is logged.
Implemented in ai_context_entity_insert() and ai_context_entity_update() in
ai_context.module, which call
AiContextItem::saveDetachedTranslationsAfterSave().
hook_form_alter()
Applies to AI Context Item entity forms and the AI Agent edit form:
- Moves Scheduler fields to the sidebar
- Groups moderation state with revision information
- Hides
entity_itemsfield when no entity types are allowed - Adds a "Context Control Center" section to the agent form with a link to consumer context settings
hook_field_widget_single_element_form_alter()
Restricts the dynamic entity reference widget on entity_items to only
show allowed entity types and enforces one entity per field row.
hook_page_attachments_alter()
Attaches the ai_context/ai_context library globally.
hook_gin_content_form_routes()
Registers context item add/edit form routes with the Gin admin theme for content-form styling.
hook_ENTITY_TYPE_view() for ai_context_item
Attaches the ai_context_item CSS/JS library on the full view mode.
Canonical and revision routes render with the full view mode; layout and
sidebar variables are built by AiContextItemViewBuilder via
AiContextThemeHooks::preprocessAiContextItem().
hook_block_access()
Forbids page_title_block on the canonical context item route so the
template H1 is the only title. Revision view keeps the route revision title
from page_title_block.
hook_preprocess_html()
Adds a page-ai-context-item-view body class on canonical and revision
context item view routes.
hook_entity_type_alter()
Delegates to DiffHooks for Diff module integration (adding diff field
builders to entity type definitions).
hook_modules_installed()
Delegates to DiffHooks to register diff field builders when the Diff
module is installed.