Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

30.1 KB
Raw Blame
import debug from 'debug';

import type { OpenAIChatMessage } from '@/types/index';

import { ContextEngine } from '../../pipeline';
import {
  ActivationResultTrimProcessor,
  AgentCouncilFlattenProcessor,
  AgentSenderMessageProcessor,
  cacheEconomicsForProvider,
  CompressedGroupRoleTransformProcessor,
  DisabledToolCallFilter,
  GroupMessageFlattenProcessor,
  GroupOrchestrationFilterProcessor,
  GroupRoleTransformProcessor,
  HistoryTruncateProcessor,
  InputTemplateProcessor,
  LH_COMMAND_TOOL_IDENTIFIERS,
  MessageCleanupProcessor,
  MessageContentProcessor,
  PlaceholderMessageFilterProcessor,
  PlaceholderVariablesProcessor,
  ReactionFeedbackProcessor,
  RevokedDocumentResultFilter,
  StaleToolResultTrimProcessor,
  SubAgentResultMessageProcessor,
  SupervisorRoleRestoreProcessor,
  TaskCallbackMessageProcessor,
  TaskMessageProcessor,
  TasksFlattenProcessor,
  ToolActivationAnchorProcessor,
  ToolCallProcessor,
  ToolMessageReorder,
  VerifyMessageProcessor,
} from '../../processors';
import {
  ActiveTopicDocumentContextInjector,
  AgentAccountContextInjector,
  AgentBuilderContextInjector,
  AgentDocumentBeforeSystemInjector,
  AgentDocumentChangesInjector,
  AgentDocumentContextInjector,
  AgentDocumentMessageInjector,
  AgentDocumentSystemAppendInjector,
  AgentDocumentSystemReplaceInjector,
  AgentIdentityInjector,
  AgentManagementContextInjector,
  BotPlatformContextInjector,
  ConnectorOwnershipInjector,
  ContextSelectionsInjector,
  DiscordContextProvider,
  DocumentReferenceContextInjector,
  EvalContextSystemInjector,
  ExpertiseContextInjector,
  ForceFinishSummaryInjector,
  GoalContextSyntheticInjector,
  GroupAgentBuilderContextInjector,
  GroupContextInjector,
  HistorySummaryProvider,
  KnowledgeInjector,
  LocalSystemToolSnapshotInjector,
  ModelInfoProvider,
  OnboardingActionHintInjector,
  OnboardingContextInjector,
  OnboardingSyntheticStateInjector,
  PlanInjector,
  ProjectContextInjector,
  ProjectInstructionsInjector,
  RuntimeAdditionalContextProvider,
  selectActivatedSkills,
  SelectedSkillInjector,
  selectToolPromptManifests,
  SKILL_STORE_TOOL_ID,
  SkillContextProvider,
  SkillImportRouteInjector,
  SystemDateProvider,
  SystemRoleInjector,
  TaskManagerContextInjector,
  TodoInjector,
  ToolDiscoveryProvider,
  ToolSystemRoleProvider,
  TopicReferenceContextInjector,
  UserMemoryInjector,
  WorkspaceContextInjector,
} from '../../providers';
import { SelectedToolInjector } from '../../providers/SelectedToolInjector';
import type { ContextProcessor } from '../../types';
import { ToolNameResolver } from '../tools';
import type { MessagesEngineParams, MessagesEngineResult } from './types';

const log = debug('context-engine:MessagesEngine');

/** `AttachmentsIdentifier` from `@lobechat/builtin-tool-attachments`, inlined to avoid a package cycle */
const ATTACHMENTS_TOOL_ID = 'lobe-attachments';
const AGENT_DOCUMENTS_TOOL_ID = 'lobe-agent-documents';
const SKILLS_TOOL_ID = 'lobe-skills';

/**
 * MessagesEngine - High-level message processing engine
 *
 * This is a convenience wrapper around ContextEngine that provides
 * a pre-configured pipeline for common message processing scenarios.
 * It can be used by both frontend and backend through dependency injection.
 *
 * @example
 * ```typescript
 * const engine = new MessagesEngine({
 *   messages,
 *   model: 'gpt-4',
 *   provider: 'openai',
 *   systemRole: 'You are a helpful assistant',
 *   capabilities: {
 *     isCanUseFC: (m, p) => true,
 *     isCanUseVision: (m, p) => true,
 *   },
 * });
 *
 * const result = await engine.process();
 * console.log(result.messages);
 * ```
 */
export class MessagesEngine {
  private params: MessagesEngineParams;
  private toolNameResolver: ToolNameResolver;

  constructor(params: MessagesEngineParams) {
    this.params = params;
    this.toolNameResolver = new ToolNameResolver();
  }

  /**
   * Process messages and return OpenAI-compatible format
   */
  async process(): Promise<MessagesEngineResult> {
    const pipeline = this.buildPipeline();
    const result = await pipeline.process({ messages: this.params.messages });

    return {
      messages: result.messages as OpenAIChatMessage[],
      metadata: result.metadata,
      stats: result.stats,
    };
  }

  /**
   * Process messages and return only the messages array
   * This is a convenience method for simpler use cases
   */
  async processMessages(): Promise<OpenAIChatMessage[]> {
    const result = await this.process();
    return result.messages;
  }

  /**
   * Build the processing pipeline based on configuration
   */
  private buildPipeline(): ContextEngine {
    const processors = this.buildProcessors();
    log(`Built pipeline with ${processors.length} processors`);
    return new ContextEngine({ pipeline: processors });
  }

  /**
   * Build the list of processors based on configuration
   */
  private buildProcessors(): ContextProcessor[] {
    const {
      model,
      modelDisplayName,
      modelKnowledgeCutoff,
      provider,
      systemRole,
      agentIdentity,
      agentAccountContext,
      inputTemplate,
      enableAgentMode,
      enableHistoryCount,
      enableStaleToolResultTrim,
      historyCount,
      forceFinish,
      historySummary,
      formatHistorySummary,
      knowledge,
      skillsConfig,
      selectedSkills,
      selectedTools,
      toolDiscoveryConfig,
      toolsConfig,
      capabilities,
      variableGenerators,
      fileContext,
      messages,
      agentBuilderContext,
      botPlatformContext,
      workspaceContext,
      discordContext,
      connectorOwnershipNote,
      evalContext,
      projectInstructions,
      onboardingContext,
      agentManagementContext,
      groupAgentBuilderContext,
      additionalContexts,
      agentGroup,
      agentDocuments,
      agentDocumentChanges,
      revokedDocumentReads,
      planTodo,
      userMemory,
      initialContext,
      stepContext,
      topicReferences,
      documentReferences,
      enableSystemDate,
      timezone,
    } = this.params;

    const isAgentBuilderEnabled = !!agentBuilderContext;

    const isGroupAgentBuilderEnabled = !!groupAgentBuilderContext;
    const isAgentGroupEnabled = agentGroup?.agentMap && Object.keys(agentGroup.agentMap).length > 0;
    const isGroupContextEnabled =
      isAgentGroupEnabled || !!agentGroup?.currentAgentId || !!agentGroup?.members;
    const isUserMemoryEnabled = !!(userMemory?.enabled && userMemory?.memories);
    const hasSelectedSkills = (selectedSkills?.length ?? 0) > 0;
    const hasSelectedTools = (selectedTools?.length ?? 0) > 0;

    // Chat mode (`enableAgentMode === false`) suppresses agentic-only injectors:
    // skill discovery (<available_skills>), agent documents, and the
    // agent-management context (<current_agent> + <available_agents>).
    // Anything else β€” system role, knowledge bases, memory, web-browsing tool
    // prompts β€” remains untouched.
    const isAgentMode = enableAgentMode !== false;
    const isAgentManagementEnabled = !!agentManagementContext && isAgentMode;
    const hasAgentDocuments = !!agentDocuments && agentDocuments.length > 0 && isAgentMode;
    const hasActiveTopicDocument = !!initialContext?.activeTopicDocument;
    // Runtime message state is authoritative, including an empty clear tombstone.
    const isPlanEnabled = planTodo?.enabled && planTodo?.plan;
    const effectiveTodos =
      stepContext?.todos !== undefined
        ? stepContext.todos
        : planTodo?.enabled
          ? planTodo.todos
          : undefined;
    const isTodoEnabled = effectiveTodos !== undefined;

    const toolIds = toolsConfig?.tools || [];
    // Keep SystemDateProvider independent of dynamically activated tools:
    // toggling it off when web-browsing or user-memory is activated mid-run
    // mutates the leading system message and invalidates the prompt-cache prefix.
    const isSystemDateEnabled = enableSystemDate !== false;
    // An eval attempt renders "today" from its case clock, never the wall clock.
    const evalClock = evalContext?.sessionDate ? new Date(evalContext.sessionDate) : undefined;
    const currentUserMessage = [...messages]
      .reverse()
      .find((m) => m.role === 'user' && typeof m.content === 'string')?.content as
      string | undefined;

    // Mirror the injection gates of SkillContextProvider / ToolSystemRoleProvider
    // (enable flags + FC support + the shared select predicates) so
    // ActivationResultTrimProcessor only trims activation tool results whose full
    // documentation is confirmed to be injected into the system prompt for this
    // request.
    const canUseFC = capabilities?.isCanUseFC || (() => true);
    // Oversized file previews may only promise `readAttachment` when the model is actually sent that
    // tool; custom / exclusive tool modes, share visitors and clients without it get a plain preview.
    const canReadAttachment = toolIds.includes(ATTACHMENTS_TOOL_ID) && !!canUseFC(model, provider);
    // Same gate for referenced agent documents: only point at `readDocument` when it is sent.
    const canReadDocuments =
      toolIds.includes(AGENT_DOCUMENTS_TOOL_ID) && !!canUseFC(model, provider);
    // Same gate for filesystem skills: only require `activateSkill` when it is sent. A Custom-mode
    // agent or a goal turn that did not pin Skills still reaches them through readFile, and a run
    // that deferred the skill APIs has Skills enabled with its sandbox shell only.
    const skillsManifest = toolsConfig?.manifests?.find(
      (manifest) => manifest.identifier === SKILLS_TOOL_ID,
    );
    const canActivateSkill =
      toolIds.includes(SKILLS_TOOL_ID) &&
      (!skillsManifest || skillsManifest.api.some((api) => api.name === 'activateSkill')) &&
      !!canUseFC(model, provider);
    const injectedActivatedSkills =
      isAgentMode && (skillsConfig?.enabledSkills?.length ?? 0) > 0
        ? selectActivatedSkills(skillsConfig?.enabledSkills)
        : [];
    const injectedToolManifests =
      (toolsConfig?.manifests?.length ?? 0) > 0 && !!canUseFC(model, provider)
        ? selectToolPromptManifests(toolsConfig?.manifests)
        : [];

    // The skill-import route is only actionable when the Skill Store is reachable this
    // run β€” either already enabled, or listed for the activator to turn on.
    const isSkillStoreReachable =
      (toolsConfig?.manifests ?? []).some((m) => m.identifier === SKILL_STORE_TOOL_ID) ||
      (toolDiscoveryConfig?.availableTools ?? []).some((t) => t.identifier === SKILL_STORE_TOOL_ID);

    // Shared config for all agent document injectors
    const agentDocConfig = {
      currentUserMessage,
      documents: agentDocuments,
      enabled: hasAgentDocuments,
    };

    return [
      // =============================================
      // Phase 0: Placeholder Residue Filtering
      // Drop failed/abandoned assistant placeholders ("..." rows) BEFORE
      // truncation so residue never consumes history slots and never lands
      // at the payload tail (Claude 4.6+ rejects trailing assistant turns)
      // =============================================

      new PlaceholderMessageFilterProcessor(),

      // =============================================
      // Phase 1: History Truncation
      // MUST run first β€” all subsequent processors work on truncated messages only
      // =============================================

      new HistoryTruncateProcessor({ enableHistoryCount, historyCount }),

      // =============================================
      // Phase 2: System Message Assembly
      // Each provider appends content to a single system message via BaseSystemRoleProvider
      // =============================================

      // Agent documents β†’ before system (prepend as separate system message)
      new AgentDocumentBeforeSystemInjector(agentDocConfig),
      // Agent's system role (creates the initial system message)
      new SystemRoleInjector({ systemRole }),
      // Both sit directly after the persona because that is exactly where they
      // used to be: the server concatenated them onto `agentConfig.systemRole`
      // several pipeline stages before the engine ran. Moving them later would
      // push them behind every other Phase 2 provider.
      //
      // Connector attribution precedes the project instructions because
      // `discoverTools` runs before `prepareOperation` in the agent pipeline,
      // so that is the order the appends produced. Reversing these two changes
      // which block the model reads last.
      new ConnectorOwnershipInjector({ note: connectorOwnershipNote }),
      new ProjectInstructionsInjector({ instructions: projectInstructions }),
      // Agent identity (name/title) β€” lets the model answer "who are you?"
      // with the user-given name. Group chat establishes identity through
      // GroupContextInjector instead, so it is suppressed there.
      new AgentIdentityInjector({
        enabled: !isGroupContextEnabled,
        identity: agentIdentity,
      }),
      // The agent's own accounts + inbox, as first-class state. Injected right
      // after the person's identity because it refines "who am I" with "and I
      // can be reached here". Skipped entirely when the agent owns nothing.
      new AgentAccountContextInjector({
        context: agentAccountContext,
        enabled: isAgentMode,
      }),
      // Eval context (appends envPrompt)
      new EvalContextSystemInjector({ enabled: !!evalContext?.envPrompt, evalContext }),
      // Bot platform context (formatting instructions for non-Markdown platforms)
      new BotPlatformContextInjector({
        context: botPlatformContext,
        enabled: !!botPlatformContext,
      }),
      // System date
      new SystemDateProvider({ enabled: isSystemDateEnabled, now: evalClock, timezone }),
      // Model info (name / id / knowledge cutoff)
      new ModelInfoProvider({
        displayName: modelDisplayName,
        knowledgeCutoff: modelKnowledgeCutoff,
        modelId: model,
        nativeMediaCapabilities: {
          audio: capabilities?.isCanUseAudio?.(model, provider),
          video: capabilities?.isCanUseVideo?.(model, provider),
          vision: capabilities?.isCanUseVision?.(model, provider),
        },
      }),
      // Workspace context (app origin + workspace slug β†’ correct in-app links).
      // Sits with the other environment facts (date / model) after the
      // persona-level injectors.
      new WorkspaceContextInjector({
        context: workspaceContext,
        enabled: !!workspaceContext,
      }),
      // Skill context (available skills list + activated skill content).
      // Disabled in chat mode β€” pairs with the tools-engine gate so the LLM
      // sees neither the manifests nor the discovery prompt.
      new SkillContextProvider({
        canActivateSkill,
        enabled:
          isAgentMode && !!(skillsConfig?.enabledSkills && skillsConfig.enabledSkills.length > 0),
        enabledSkills: skillsConfig?.enabledSkills,
      }),
      // Tool system role (tool manifests and API definitions)
      new ToolSystemRoleProvider({
        enabled: !!(toolsConfig?.manifests && toolsConfig.manifests.length > 0),
        isCanUseFC: capabilities?.isCanUseFC || (() => true),
        manifests: toolsConfig?.manifests,
        model,
        provider,
      }),
      // History summary (conversation summary from compression)
      new HistorySummaryProvider({ formatHistorySummary, historySummary }),
      // Agent documents β†’ append to system message
      new AgentDocumentSystemAppendInjector(agentDocConfig),
      // Agent documents β†’ replace entire system message (destructive, runs last)
      new AgentDocumentSystemReplaceInjector(agentDocConfig),

      // =============================================
      // Phase 3: Context Injection (before first user message)
      // Providers consolidate into a single injection message via BaseFirstUserContentProvider
      // Order matters: first executed = first in content
      // =============================================

      // User memory
      new UserMemoryInjector({ ...userMemory, enabled: isUserMemoryEnabled }),
      // Operation-scoped learned expertise (captured once and reused verbatim across steps)
      new ExpertiseContextInjector({
        enabled: this.params.enableExpertise,
        expertise: this.params.expertise,
      }),
      // Group context (agent identity and group info for multi-agent chat)
      new GroupContextInjector({
        currentAgentId: agentGroup?.currentAgentId,
        currentAgentName: agentGroup?.currentAgentName,
        currentAgentRole: agentGroup?.currentAgentRole,
        enabled: isGroupContextEnabled,
        groupTitle: agentGroup?.groupTitle,
        members: agentGroup?.members,
        systemPrompt: agentGroup?.systemPrompt,
      }),
      // Discord context (channel/guild info)
      new DiscordContextProvider({ context: discordContext, enabled: !!discordContext }),
      // Plan (high-level plan document)
      new PlanInjector({ enabled: !!isPlanEnabled, plan: planTodo?.plan }),
      // Knowledge (agent files + knowledge bases)
      new KnowledgeInjector({
        canReadAttachment,
        fileContents: knowledge?.fileContents,
        knowledgeBases: knowledge?.knowledgeBases,
      }),
      // Agent documents β†’ before first user message
      new AgentDocumentContextInjector(agentDocConfig),
      // Tool Discovery (available tools for dynamic activation)
      new ToolDiscoveryProvider({
        availableTools: toolDiscoveryConfig?.availableTools,
        enabled:
          !!toolDiscoveryConfig?.availableTools && toolDiscoveryConfig.availableTools.length > 0,
      }),
      // Agent Builder context (current agent config/meta for editing)
      new AgentBuilderContextInjector({
        enabled: isAgentBuilderEnabled,
        agentContext: agentBuilderContext,
      }),
      // Agent Management context (available models and plugins)
      new AgentManagementContextInjector({
        enabled: isAgentManagementEnabled,
        context: agentManagementContext,
      }),
      // Group Agent Builder context (current group config/members for editing)
      new GroupAgentBuilderContextInjector({
        enabled: isGroupAgentBuilderEnabled,
        groupContext: groupAgentBuilderContext,
      }),
      // Onboarding context (phase guidance + document contents β€” stable, cacheable)
      new OnboardingContextInjector({
        enabled: !!onboardingContext?.phaseGuidance,
        onboardingContext,
      }),

      // =============================================
      // Phase 4: User Message Augmentation
      // Injects context into specific user messages (last user, selected, etc.)
      // =============================================

      // Agent documents β†’ after-first-user, context-end
      new AgentDocumentMessageInjector(agentDocConfig),
      // Agent-document change notes β†’ the user message each belongs to (the
      // index renders a snapshot; these say what changed since). Not gated on
      // `hasAgentDocuments`: a snapshot taken before the first document has no
      // rows, and the notes are then the only place new documents appear.
      new AgentDocumentChangesInjector({
        changes: agentDocumentChanges,
        enabled: isAgentMode && !!agentDocumentChanges,
      }),
      // Active topic document β†’ last user message, for continuing document work outside page scope
      new ActiveTopicDocumentContextInjector({
        activeTopicDocument: initialContext?.activeTopicDocument,
        enabled: hasActiveTopicDocument,
      }),
      // LobeHub skill URLs in the current message β†’ route them to the Skill Store
      // instead of letting the model crawl the page and follow its CLI steps.
      new SkillImportRouteInjector({ enabled: isSkillStoreReachable }),
      // Selected skills (ephemeral user-selected slash skills for this request)
      new SelectedSkillInjector({ enabled: hasSelectedSkills, selectedSkills }),
      // Selected tools (ephemeral user-selected @tool for this request)
      new SelectedToolInjector({ enabled: hasSelectedTools, selectedTools }),
      // Generic user-attached selections from chat/code/text contexts.
      new ContextSelectionsInjector({
        enabled: true,
        mcpAppsEnabled: this.params.enableMcpAppContext,
      }),
      // Local-system file snapshots (replay send-time @file reads as real tool results)
      new LocalSystemToolSnapshotInjector({ enabled: true }),
      // Project context (members, linked knowledge, open tasks) for a run inside a project
      new ProjectContextInjector({
        contextPrompt: initialContext?.projectContext?.contextPrompt,
        enabled: !!initialContext?.projectContext?.contextPrompt,
      }),
      // Task Manager page context (inject current tasks list/detail to last user message)
      new TaskManagerContextInjector({
        contextPrompt: initialContext?.taskManager?.contextPrompt,
        enabled: !!initialContext?.taskManager?.contextPrompt,
      }),
      // Topic Reference context (referenced topic summaries to last user message)
      new TopicReferenceContextInjector({
        enabled: !!(topicReferences && topicReferences.length > 0),
        topicReferences,
      }),
      // Document Reference context (dragged/referenced agent documents to last user message)
      new DocumentReferenceContextInjector({
        canReadDocuments,
        documentReferences,
        enabled: !!(documentReferences && documentReferences.length > 0),
      }),

      // =============================================
      // Phase 4.5: Virtual Tail Guidance
      // Inject high-churn runtime guidance at the tail to preserve stable prefix caching
      // =============================================

      // Goal progress overview (goal detail page conversation) β€” a synthetic
      // getGoalContext tool pair after the last user message: environment
      // state arrives as machine-provided tool output, not as user words.
      new GoalContextSyntheticInjector({
        enabled: !!initialContext?.goalOverview,
        overview: initialContext?.goalOverview,
      }),
      // Onboarding synthetic state (fake getOnboardingState tool call pair to drive action loop)
      new OnboardingSyntheticStateInjector({
        enabled: !!onboardingContext?.phaseGuidance,
        onboardingContext,
      }),
      // Onboarding action hints (phase-specific tool call reminders)
      new OnboardingActionHintInjector({
        enabled: !!onboardingContext?.phaseGuidance,
        onboardingContext,
      }),
      // Todo list (standalone virtual tail message)
      new TodoInjector({
        enabled: isTodoEnabled && planTodo?.injectTodos !== false,
        todos: effectiveTodos,
      }),
      new RuntimeAdditionalContextProvider({ additionalContexts }),

      // =============================================
      // Phase 5: Message Transformation
      // Flattens group/task messages, applies templates and variables
      // =============================================

      // Background sub-agent results arrive as user messages from the
      // sub-agent; mark them as its report before any user-text template
      new SubAgentResultMessageProcessor(),
      // Input template processing
      new InputTemplateProcessor({ inputTemplate }),
      // AgentCouncil message flatten
      new AgentCouncilFlattenProcessor(),
      // Group message flatten
      new GroupMessageFlattenProcessor(),
      // Tasks message flatten
      new TasksFlattenProcessor(),
      // Task message processing
      new TaskMessageProcessor(),
      // Second placeholder pass: the flatten steps above can expand "..."
      // residue hidden inside group/council/tasks children (invisible to the
      // Phase 0 pass, which only sees top-level messages), and
      // TaskMessageProcessor converts flattened `task` rows into assistant
      // messages β€” so this pass must run AFTER that conversion to catch
      // task-shaped residue too.
      new PlaceholderMessageFilterProcessor(),
      // Verify (delivery-checker) cards: drop empty UI-only ones; surface
      // auto-repair failure feedback as a user turn for the repair run
      new VerifyMessageProcessor(),
      // Task-callback cards: surface a finished task's handoff as a user turn
      // so the creator agent reads it and continues
      new TaskCallbackMessageProcessor(),
      // Revoked document reads β€” withholds historical readKnowledge /
      // readDocument bodies of documents deleted or disabled since they were
      // read, so a removed standing rule stops steering the agent. MUST run
      // AFTER the flatten steps (nested tool results become `role: 'tool'`
      // rows there) and BEFORE the group role transforms below, which fold
      // other members' results into user text and drop `plugin`.
      new RevokedDocumentResultFilter({ revokedDocumentReads }),
      // Supervisor role restore
      new SupervisorRoleRestoreProcessor(),
      // Compressed group role transform
      new CompressedGroupRoleTransformProcessor(),
      // Group orchestration filter (must run BEFORE GroupRoleTransformProcessor)
      ...(isAgentGroupEnabled && agentGroup.agentMap && agentGroup.currentAgentId
        ? [
            new GroupOrchestrationFilterProcessor({
              agentMap: Object.fromEntries(
                Object.entries(agentGroup.agentMap).map(([id, info]) => [id, { role: info.role }]),
              ),
              currentAgentId: agentGroup.currentAgentId,
              enabled: agentGroup.currentAgentRole !== 'supervisor',
            }),
          ]
        : []),
      // Group role transform (must run BEFORE ToolCallProcessor)
      ...(isAgentGroupEnabled && agentGroup.currentAgentId
        ? [
            new GroupRoleTransformProcessor({
              agentMap: agentGroup.agentMap!,
              currentAgentId: agentGroup.currentAgentId,
            }),
          ]
        : []),
      // Dynamic-activation result trimming β€” replaces activateTools /
      // activateSkill tool-result documents that are ALSO injected into the
      // system prompt (by ToolSystemRoleProvider / SkillContextProvider above)
      // with a short confirmation, so each activated document reaches the LLM
      // payload exactly once. MUST run AFTER the flatten steps (grouped /
      // compressed tool rows are only hoisted back to `role: 'tool'` with
      // plugin/pluginState there) and BEFORE ToolCallProcessor.
      new ActivationResultTrimProcessor({
        injectedManifests: injectedToolManifests,
        injectedSkills: injectedActivatedSkills,
      }),
      // Stale tool-result trimming β€” replaces the bodies of superseded tool
      // results (file reads later overwritten, stale browser snapshots, old
      // command output) with short placeholders. Rules are monotone so the
      // trimmed prefix stays byte-stable across requests and the prompt-cache
      // prefix survives; savings land at the operation boundary where the
      // cache is cold anyway. Same pipeline position constraints as
      // ActivationResultTrimProcessor above. Cache economics (TTL, read/write
      // prices) follow the active provider.
      new StaleToolResultTrimProcessor({
        economics: cacheEconomicsForProvider(provider),
        enabled: enableStaleToolResultTrim !== false,
      }),
      // Placeholder variables processing β€” MUST run AFTER all flatten / role
      // transform steps. AssistantGroup / Supervisor messages keep their real
      // content (including any `{{...}}` placeholders inside tool results)
      // nested under `children[].tools[].result.content`. The flatten processors
      // hoist that nested content into top-level `role: 'tool'` messages.
      // PlaceholderVariablesProcessor only walks `message.content`, so it MUST
      // run after the hoist or it would silently miss every placeholder buried
      // inside an assistantGroup. (Regression discovered while wiring lobehub
      // skill identity placeholders β€” see .)
      new PlaceholderVariablesProcessor({ variableGenerators: variableGenerators || {} }),

      // =============================================
      // Phase 6: Content Processing
      // Multimodal encoding, tool calls, reaction feedback
      // =============================================

      // Reaction feedback
      new ReactionFeedbackProcessor({ enabled: true }),
      // Who sent an agent β†’ agent message, and how to reply (string content only)
      new AgentSenderMessageProcessor({
        // Enabled now or activatable on demand: either way the agent can run `lh`.
        canRunLhCommand: [
          ...(toolsConfig?.manifests ?? []).map((manifest) => manifest.identifier),
          ...(toolDiscoveryConfig?.availableTools ?? []).map((tool) => tool.identifier),
        ].some((identifier) => LH_COMMAND_TOOL_IDENTIFIERS.includes(identifier)),
      }),
      // Message content processing (image encoding, multimodal)
      new MessageContentProcessor({
        canReadAttachment,
        fileContext: fileContext || { enabled: true, includeFileUrl: true },
        isCanUseAudio: capabilities?.isCanUseAudio || (() => false),
        isCanUseVideo: capabilities?.isCanUseVideo || (() => false),
        isCanUseVision: capabilities?.isCanUseVision || (() => true),
        model,
        provider,
      }),
      // Tool call processing
      new ToolCallProcessor({
        genToolCallingName: this.toolNameResolver.generate.bind(this.toolNameResolver),
        isCanUseFC: capabilities?.isCanUseFC || (() => true),
        model,
        provider,
      }),
      // Disabled historical tool calls (for scope-specific tool removal)
      new DisabledToolCallFilter({
        disabledToolIdentifiers: toolsConfig?.disabledToolIdentifiers,
      }),

      // =============================================
      // Phase 7: Cleanup
      // Final reordering, force finish, and message cleanup
      // =============================================

      // Tool message reordering
      new ToolMessageReorder(),
      // Force finish summary (when maxSteps exceeded)
      new ForceFinishSummaryInjector({ enabled: !!forceFinish }),
      // Only paired activation results still present in the outgoing conversation can own tools.
      ...(toolsConfig?.anchorActivatedTools
        ? [
            new ToolActivationAnchorProcessor({
              manifests: injectedToolManifests,
              variableGenerators,
            }),
          ]
        : []),
      // Message cleanup (final step)
      new MessageCleanupProcessor(),
    ];
  }
}