π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(chat): route leading agent mentions directly (#14237)
Inneib94aa1da901c
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.tsindex 9733495d31d..84c123ea49d 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts@@ -3,6 +3,7 @@ import { act, renderHook } from '@testing-library/react';import { TRPCClientError } from '@trpc/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { agentService } from '@/services/agent';import { aiChatService } from '@/services/aiChat';import { chatService } from '@/services/chat';import { messageService } from '@/services/message';@@ -12,7 +13,7 @@ import { getSessionStoreState } from '@/store/session';import * as toolStoreModule from '@/store/tool';import { useChatStore } from '../../../../store';-import { createMockMessage, TEST_CONTENT, TEST_IDS } from './fixtures';+import { createMockAgentConfig, createMockMessage, TEST_CONTENT, TEST_IDS } from './fixtures';import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';// Keep zustand mock as it's needed globally@@ -52,6 +53,7 @@ beforeEach(() => {spyOnMessageService();const sessionStore = getSessionStoreState();vi.spyOn(sessionStore, 'triggerSessionUpdate').mockResolvedValue(undefined);+ vi.spyOn(agentService, 'getAgentConfigById').mockResolvedValue(createMockAgentConfig() as any);act(() => {useChatStore.setState({@@ -903,7 +905,7 @@ describe('ConversationLifecycle actions', () => {});describe('@agent mention delegation', () => {- it('should NOT set isSupervisor on assistant message when @agent is mentioned in non-group chat', async () => {+ it('should NOT set isSupervisor on assistant message when @agent uses supervisor path in non-group chat', async () => {const { result } = renderHook(() => useChatStore());const sendMessageInServerSpy = vi@@ -920,18 +922,18 @@ describe('ConversationLifecycle actions', () => {await act(async () => {await result.current.sendMessage({- message: '@Agent A hello',+ message: 'hello @Agent A',editorData: {root: {children: [{children: [+ { text: 'hello ', type: 'text' },{label: 'Agent A',metadata: { id: 'agent-a', type: 'agent' },type: 'mention',},- { text: ' hello', type: 'text' },],type: 'paragraph',},@@ -966,6 +968,195 @@ describe('ConversationLifecycle actions', () => {);});+ it('should directly call a single leading @agent in non-group chat', async () => {+ const { result } = renderHook(() => useChatStore());+ const targetAgentId = 'agent-direct-target';+ const toolMessageId = 'tool-call-agent-result';+ const message = '@Agent B hello';+ const createdThreadId = 'thread-created-by-send';++ const userMessage = createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ content: message,+ });+ let assistantMessage = createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ role: 'assistant',+ content: '',+ tools: [],+ });++ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({+ createdThreadId,+ messages: [userMessage, assistantMessage],+ topics: [],+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ (messageService.updateMessage as any).mockImplementation(+ async (_id: string, value: any) => {+ assistantMessage = { ...assistantMessage, ...value };+ return { messages: [userMessage, assistantMessage], success: true };+ },+ );+ (messageService.createMessage as any).mockImplementation(async (params: any) => {+ const toolMessage = createMockMessage({+ ...params,+ id: toolMessageId,+ role: 'tool',+ });++ return {+ id: toolMessageId,+ messages: [userMessage, assistantMessage, toolMessage],+ };+ });++ await act(async () => {+ await result.current.sendMessage({+ message,+ editorData: {+ root: {+ children: [+ {+ children: [+ {+ label: 'Agent B',+ metadata: { id: targetAgentId, type: 'agent' },+ type: 'mention',+ },+ { text: ' hello', type: 'text' },+ ],+ type: 'paragraph',+ },+ ],+ type: 'root',+ },+ } as any,+ context: createTestContext(),+ });+ });++ expect(agentService.getAgentConfigById).toHaveBeenCalledWith(targetAgentId);+ expect(messageService.updateMessage).toHaveBeenCalledWith(+ TEST_IDS.ASSISTANT_MESSAGE_ID,+ expect.objectContaining({+ content: '',+ tools: [+ expect.objectContaining({+ apiName: 'callAgent',+ identifier: 'lobe-agent-management',+ }),+ ],+ }),+ expect.objectContaining({ agentId: TEST_IDS.SESSION_ID }),+ );+ expect(messageService.createMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: TEST_IDS.SESSION_ID,+ content: `Called agent "${targetAgentId}" to respond.`,+ parentId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ plugin: expect.objectContaining({+ apiName: 'callAgent',+ identifier: 'lobe-agent-management',+ }),+ pluginState: {+ agentId: targetAgentId,+ instruction: message,+ mode: 'speak',+ },+ role: 'tool',+ }),+ );++ const execCall = (result.current.internal_execAgentRuntime as any).mock.calls[0]?.[0];+ expect(execCall).toEqual(+ expect.objectContaining({+ context: expect.objectContaining({+ agentId: TEST_IDS.SESSION_ID,+ scope: 'sub_agent',+ subAgentId: targetAgentId,+ }),+ inPortalThread: true,+ parentMessageId: toolMessageId,+ parentMessageType: 'tool',+ }),+ );+ expect(execCall.initialContext).toBeUndefined();+ expect(execCall.messages).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ id: toolMessageId, role: 'tool' }),+ expect.objectContaining({+ content: expect.stringContaining(message),+ role: 'user',+ }),+ ]),+ );+ });++ it('should keep supervisor delegation for multiple @agent mentions', async () => {+ const { result } = renderHook(() => useChatStore());++ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({+ messages: [+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),+ ],+ topics: [],+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ await act(async () => {+ await result.current.sendMessage({+ message: '@Agent A @Agent B compare',+ editorData: {+ root: {+ children: [+ {+ children: [+ {+ label: 'Agent A',+ metadata: { id: 'agent-a', type: 'agent' },+ type: 'mention',+ },+ { text: ' ', type: 'text' },+ {+ label: 'Agent B',+ metadata: { id: 'agent-b', type: 'agent' },+ type: 'mention',+ },+ { text: ' compare', type: 'text' },+ ],+ type: 'paragraph',+ },+ ],+ type: 'root',+ },+ } as any,+ context: createTestContext(),+ });+ });++ expect(agentService.getAgentConfigById).not.toHaveBeenCalledWith('agent-a');+ expect(result.current.internal_execAgentRuntime).toHaveBeenCalledWith(+ expect.objectContaining({+ initialContext: expect.objectContaining({+ initialContext: expect.objectContaining({+ mentionedAgents: [+ { id: 'agent-a', name: 'Agent A' },+ { id: 'agent-b', name: 'Agent B' },+ ],+ }),+ }),+ parentMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ parentMessageType: 'assistant',+ }),+ );+ });+it('should NOT inject mentionedAgents into initialContext when in group chat', async () => {const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/aiChat/actions/commandBus/index.ts b/src/store/chat/slices/aiChat/actions/commandBus/index.tsindex cde05ab4b1a..340e63fe137 100644--- a/src/store/chat/slices/aiChat/actions/commandBus/index.ts+++ b/src/store/chat/slices/aiChat/actions/commandBus/index.ts@@ -6,12 +6,14 @@ import { parseCommandsFromEditorData } from './parseCommands';import type { CommandHandlerContext, CommandRegistry, CommandSendOverrides } from './types';export { injectReferTopicNode } from './editorDataHelpers';+export type { SingleAgentMentionDirectRoute } from './parseCommands';export {hasNonActionContent,parseCommandsFromEditorData,parseMentionedAgentsFromEditorData,parseSelectedSkillsFromEditorData,parseSelectedToolsFromEditorData,+ parseSingleAgentMentionDirectRoute,} from './parseCommands';export type { CommandSendOverrides } from './types';diff --git a/src/store/chat/slices/aiChat/actions/commandBus/parseCommands.test.ts b/src/store/chat/slices/aiChat/actions/commandBus/parseCommands.test.tsindex 807d8d6a6c5..7b5ae327c18 100644--- a/src/store/chat/slices/aiChat/actions/commandBus/parseCommands.test.ts+++ b/src/store/chat/slices/aiChat/actions/commandBus/parseCommands.test.ts@@ -5,6 +5,7 @@ import {parseMentionedAgentsFromEditorData,parseSelectedSkillsFromEditorData,parseSelectedToolsFromEditorData,+ parseSingleAgentMentionDirectRoute,} from './parseCommands';describe('parseCommandsFromEditorData', () => {@@ -500,3 +501,159 @@ describe('parseMentionedAgentsFromEditorData', () => {]);});});++describe('parseSingleAgentMentionDirectRoute', () => {+ it('should return undefined for undefined editorData', () => {+ expect(parseSingleAgentMentionDirectRoute(undefined)).toBeUndefined();+ });++ it('should detect a single leading agent mention', () => {+ const editorData = {+ root: {+ children: [+ {+ children: [+ {+ label: 'Agent B',+ metadata: { id: 'agent-b', type: 'agent' },+ type: 'mention',+ },+ { text: ' please review this', type: 'text' },+ ],+ type: 'paragraph',+ },+ ],+ type: 'root',+ },+ };++ expect(parseSingleAgentMentionDirectRoute(editorData)).toEqual({+ agent: { id: 'agent-b', name: 'Agent B' },+ });+ });++ it('should allow whitespace before the leading agent mention', () => {+ const editorData = {+ root: {+ children: [+ {+ children: [+ { text: ' \n\t ', type: 'text' },+ {+ label: 'Agent B',+ metadata: { id: 'agent-b', type: 'agent' },+ type: 'mention',+ },+ ],+ type: 'paragraph',+ },+ ],+ type: 'root',+ },+ };++ expect(parseSingleAgentMentionDirectRoute(editorData)).toEqual({+ agent: { id: 'agent-b', name: 'Agent B' },+ });+ });++ it('should reject an agent mention when text appears first', () => {+ const editorData = {+ root: {+ children: [+ {+ children: [+ { text: 'please ask ', type: 'text' },+ {+ label: 'Agent B',+ metadata: { id: 'agent-b', type: 'agent' },+ type: 'mention',+ },+ ],+ type: 'paragraph',+ },+ ],+ type: 'root',+ },+ };++ expect(parseSingleAgentMentionDirectRoute(editorData)).toBeUndefined();+ });++ it('should reject multiple mention nodes even when only one is an agent', () => {+ const editorData = {+ root: {+ children: [+ {+ children: [+ {+ label: 'Agent B',+ metadata: { id: 'agent-b', type: 'agent' },+ type: 'mention',+ },+ {+ label: 'Topic X',+ metadata: { id: 'topic-x', type: 'topic' },+ type: 'mention',+ },+ ],+ type: 'paragraph',+ },+ ],+ type: 'root',+ },+ };++ expect(parseSingleAgentMentionDirectRoute(editorData)).toBeUndefined();+ });++ it('should reject a single non-agent mention', () => {+ const editorData = {+ root: {+ children: [+ {+ children: [+ {+ label: 'Topic X',+ metadata: { id: 'topic-x', type: 'topic' },+ type: 'mention',+ },+ ],+ type: 'paragraph',+ },+ ],+ type: 'root',+ },+ };++ expect(parseSingleAgentMentionDirectRoute(editorData)).toBeUndefined();+ });++ it('should reject when an action tag appears before the mention', () => {+ const editorData = {+ root: {+ children: [+ {+ children: [+ {+ actionCategory: 'skill',+ actionLabel: 'User Memory',+ actionType: 'user_memory',+ type: 'action-tag',+ },+ {+ label: 'Agent B',+ metadata: { id: 'agent-b', type: 'agent' },+ type: 'mention',+ },+ ],+ type: 'paragraph',+ },+ ],+ type: 'root',+ },+ };++ expect(parseSingleAgentMentionDirectRoute(editorData)).toBeUndefined();+ });+});diff --git a/src/store/chat/slices/aiChat/actions/commandBus/parseCommands.ts b/src/store/chat/slices/aiChat/actions/commandBus/parseCommands.tsindex 22e484bdd85..562e435f7e9 100644--- a/src/store/chat/slices/aiChat/actions/commandBus/parseCommands.ts+++ b/src/store/chat/slices/aiChat/actions/commandBus/parseCommands.ts@@ -17,6 +17,10 @@ export interface ParsedActionTag {export interface ParsedCommand extends ParsedActionTag {}+export interface SingleAgentMentionDirectRoute {+ agent: RuntimeMentionedAgent;+}+/*** Walk the Lexical JSON tree to find all action-tag nodes.* Returns the extracted action tags in document order.@@ -108,6 +112,52 @@ export const parseMentionedAgentsFromEditorData = (return agents;};+/**+ * Detect the direct-route shorthand:+ * exactly one mention node in the whole document, and that mention is the+ * first meaningful node and points to an agent.+ */+export const parseSingleAgentMentionDirectRoute = (+ editorData: Record<string, any> | undefined,+): SingleAgentMentionDirectRoute | undefined => {+ if (!editorData) return;++ const mentions: Array<{+ label: string;+ metadata: Record<string, unknown>;+ node: any;+ }> = [];+ let firstMeaningfulNode: any;++ walkMeaningfulNode(editorData.root, (node) => {+ firstMeaningfulNode ??= node;++ if (node.type === 'mention' && node.metadata) {+ mentions.push({+ label: node.label ?? '',+ metadata: node.metadata,+ node,+ });+ }+ });++ if (mentions.length !== 1) return;++ const [mention] = mentions;+ if (firstMeaningfulNode !== mention.node) return;+ if (mention.metadata.type !== 'agent') return;++ const id = typeof mention.metadata.id === 'string' ? mention.metadata.id : undefined;+ if (!id) return;++ return {+ agent: {+ id,+ name: mention.label || id,+ },+ };+};+/*** Check if editorData contains any meaningful text content* besides action-tag nodes (whitespace-only counts as empty).@@ -147,6 +197,32 @@ function walkMentionNode(}}+function walkMeaningfulNode(node: any, cb: (node: any) => void): void {+ if (!node) return;++ if (isMeaningfulNode(node)) {+ cb(node);+ }++ if (Array.isArray(node.children)) {+ for (const child of node.children) {+ walkMeaningfulNode(child, cb);+ }+ }+}++function isMeaningfulNode(node: any): boolean {+ if (!node?.type || Array.isArray(node.children)) return false;++ if (node.type === 'text') {+ return typeof node.text === 'string' && node.text.trim().length > 0;+ }++ if (node.type === 'linebreak') return false;++ return true;+}+function walkNode(node: any, out: ParsedActionTag[]): void {if (!node) return;diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.tsindex bfcf5a86b28..615c26afd24 100644--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts@@ -1,17 +1,23 @@// Disable the auto sort key eslint rule to make the code more logic and readable-import { createCallAgentManifest } from '@lobechat/builtin-tool-agent-management';+import type { CallAgentParams, CallAgentState } from '@lobechat/builtin-tool-agent-management';+import {+ AgentManagementApiName,+ AgentManagementIdentifier,+ createCallAgentManifest,+} from '@lobechat/builtin-tool-agent-management';import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';import { isDesktop, LOADING_FLAT } from '@lobechat/const';import { formatSelectedSkillsContext, formatSelectedToolsContext } from '@lobechat/context-engine';import { chainCompressContext } from '@lobechat/prompts';-import {- type ChatImageItem,- type ChatThreadType,- type ChatVideoItem,- type ConversationContext,- type SendMessageParams,- type SendMessageServerResponse,- type UIChatMessage,+import type {+ ChatImageItem,+ ChatThreadType,+ ChatToolPayload,+ ChatVideoItem,+ ConversationContext,+ SendMessageParams,+ SendMessageServerResponse,+ UIChatMessage,} from '@lobechat/types';import { nanoid } from '@lobechat/utils';import { TRPCClientError } from '@trpc/client';@@ -19,12 +25,13 @@ import { t } from 'i18next';import { markUserValidAction } from '@/business/client/markUserValidAction';import { message as antdMessage } from '@/components/AntdStaticMethods';+import { agentService } from '@/services/agent';import { aiChatService } from '@/services/aiChat';import { chatService } from '@/services/chat';import { resolveSelectedSkillsWithContent } from '@/services/chat/mecha/skillPreload';import { resolveSelectedToolsWithContent } from '@/services/chat/mecha/toolPreload';import { messageService } from '@/services/message';-import { getAgentStoreState } from '@/store/agent';+import { getAgentStoreState, useAgentStore } from '@/store/agent';import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';import { agentGroupByIdSelectors, getChatGroupStoreState } from '@/store/agentGroup';import { resolveHeteroResume } from '@/store/chat/slices/aiChat/actions/heteroResume';@@ -48,13 +55,14 @@ import { dbMessageSelectors, displayMessageSelectors, topicSelectors } from '../import { messageMapKey } from '../../../utils/messageMapKey';import { topicMapKey } from '../../../utils/topicMapKey';import { AI_RUNTIME_OPERATION_TYPES } from '../../operation/types';+import type { CommandSendOverrides, SingleAgentMentionDirectRoute } from './commandBus';import {- type CommandSendOverrides,hasNonActionContent,injectReferTopicNode,parseMentionedAgentsFromEditorData,parseSelectedSkillsFromEditorData,parseSelectedToolsFromEditorData,+ parseSingleAgentMentionDirectRoute,processCommands,} from './commandBus';/**@@ -231,7 +239,11 @@ export class ConversationLifecycleActionImpl {isGroupSupervisor = group?.supervisorAgentId === agentId;}// In non-group context, @agent mentions make the current agent act as supervisor- const hasMentionedAgents = !context.groupId && mentionedAgents.length > 0;+ const directMentionRoute = !context.groupId+ ? parseSingleAgentMentionDirectRoute(editorData)+ : undefined;+ const hasMentionedAgents =+ !context.groupId && !directMentionRoute && mentionedAgents.length > 0;const operationContext = {...context,@@ -870,48 +882,59 @@ export class ConversationLifecycleActionImpl {// ββ AI execution (client mode) ββ{- const displayMessages = displayMessageSelectors.getDisplayMessagesByKey(- messageMapKey(execContext),- )(this.#get());-try {- // When agents are @mentioned, inject a slim callAgent-only manifest- // so the AI can delegate directly without activating the full agent-management tool- const injectedManifests = hasMentionedAgents ? [createCallAgentManifest()] : undefined;- const activeTopicDocumentInitialContext =- await resolveActiveTopicDocumentInitialContext(execContext);-- const hasInitialContext = hasMentionedAgents || !!injectedManifests;-- // Note: selectedSkills and selectedTools are NOT passed here β they are- // persisted into the user message content above so they survive across- // turns without re-injection.- const agentRuntimeInitialContext = hasInitialContext- ? {- initialContext: {- // Only inject mentionedAgents in non-group context to avoid- // group @member mentions (including ALL_MEMBERS) leaking into agent-management- ...(hasMentionedAgents ? { mentionedAgents } : undefined),- ...(injectedManifests ? { injectedManifests } : undefined),- },- phase: 'init' as const,- }- : undefined;- const mergedAgentRuntimeInitialContext = mergeAgentRuntimeInitialContexts(- activeTopicDocumentInitialContext,- agentRuntimeInitialContext,- );-- await internal_execAgentRuntime({- context: execContext,- initialContext: mergedAgentRuntimeInitialContext,- messages: displayMessages,- parentMessageId: data.assistantMessageId,- parentMessageType: 'assistant',- parentOperationId: operationId,- inPortalThread: !!data.createdThreadId,- skipCreateFirstMessage: true,- });+ if (directMentionRoute) {+ await this.#executeDirectMentionRoute({+ assistantMessageId: data.assistantMessageId,+ context: execContext,+ directMentionRoute,+ inPortalThread: !!data.createdThreadId,+ instruction: message,+ parentOperationId: operationId,+ });+ } else {+ const displayMessages = displayMessageSelectors.getDisplayMessagesByKey(+ messageMapKey(execContext),+ )(this.#get());++ // When agents are @mentioned, inject a slim callAgent-only manifest+ // so the AI can delegate directly without activating the full agent-management tool+ const injectedManifests = hasMentionedAgents ? [createCallAgentManifest()] : undefined;+ const activeTopicDocumentInitialContext =+ await resolveActiveTopicDocumentInitialContext(execContext);++ const hasInitialContext = hasMentionedAgents || !!injectedManifests;++ // Note: selectedSkills and selectedTools are NOT passed here β they are+ // persisted into the user message content above so they survive across+ // turns without re-injection.+ const agentRuntimeInitialContext = hasInitialContext+ ? {+ initialContext: {+ // Only inject mentionedAgents in non-group context to avoid+ // group @member mentions (including ALL_MEMBERS) leaking into agent-management+ ...(hasMentionedAgents ? { mentionedAgents } : undefined),+ ...(injectedManifests ? { injectedManifests } : undefined),+ },+ phase: 'init' as const,+ }+ : undefined;+ const mergedAgentRuntimeInitialContext = mergeAgentRuntimeInitialContexts(+ activeTopicDocumentInitialContext,+ agentRuntimeInitialContext,+ );++ await internal_execAgentRuntime({+ context: execContext,+ initialContext: mergedAgentRuntimeInitialContext,+ messages: displayMessages,+ parentMessageId: data.assistantMessageId,+ parentMessageType: 'assistant',+ parentOperationId: operationId,+ inPortalThread: !!data.createdThreadId,+ skipCreateFirstMessage: true,+ });+ }const userFiles = dbMessageSelectors.dbUserFiles(this.#get())@@ -937,6 +960,154 @@ export class ConversationLifecycleActionImpl {};};+ async #executeDirectMentionRoute({+ assistantMessageId,+ context,+ inPortalThread,+ directMentionRoute,+ instruction,+ parentOperationId,+ }: {+ assistantMessageId: string;+ context: ConversationContext;+ inPortalThread?: boolean;+ directMentionRoute: SingleAgentMentionDirectRoute;+ instruction: string;+ parentOperationId: string;+ }): Promise<void> {+ const targetAgentId = directMentionRoute.agent.id;+ const callAgentParams: CallAgentParams = {+ agentId: targetAgentId,+ instruction,+ };+ const toolPayload: ChatToolPayload = {+ apiName: AgentManagementApiName.callAgent,+ arguments: JSON.stringify(callAgentParams),+ id: `call_agent_${nanoid()}`,+ identifier: AgentManagementIdentifier,+ source: 'builtin',+ type: 'builtin',+ };+ const callAgentState: CallAgentState = {+ agentId: targetAgentId,+ instruction,+ mode: 'speak',+ };+ const toolResultContent = `Called agent "${targetAgentId}" to respond.`;++ const { operationId } = this.#get().startOperation({+ context: { ...context, messageId: assistantMessageId },+ label: 'Direct Agent Mention',+ metadata: {+ apiName: AgentManagementApiName.callAgent,+ targetAgentId,+ tool_call_id: toolPayload.id,+ },+ parentOperationId,+ type: 'toolCalling',+ });++ try {+ this.#get().internal_dispatchMessage(+ {+ id: assistantMessageId,+ type: 'updateMessage',+ value: { content: '' },+ },+ { operationId },+ );+ await this.#get().optimisticUpdateMessageContent(+ assistantMessageId,+ '',+ { tools: [toolPayload] },+ { operationId },+ );++ const toolMessage = await this.#get().optimisticCreateMessage(+ {+ agentId: context.agentId!,+ content: toolResultContent,+ groupId: context.groupId,+ parentId: assistantMessageId,+ plugin: toolPayload,+ pluginState: callAgentState,+ role: 'tool',+ threadId: context.threadId,+ tool_call_id: toolPayload.id,+ topicId: context.topicId ?? undefined,+ },+ { operationId },+ );++ if (!toolMessage) {+ throw new Error(+ `[directMentionRoute] Failed to create callAgent tool message for agentId: ${targetAgentId}`,+ );+ }++ const preloadError = await this.#preloadDirectMentionAgentConfig(targetAgentId);+ if (preloadError) {+ await this.#get().optimisticUpdateMessageContent(toolMessage.id, preloadError, undefined, {+ operationId,+ });+ this.#get().completeOperation(operationId);+ return;+ }++ const currentMessages = dbMessageSelectors.getDbMessagesByKey(messageMapKey(context))(+ this.#get(),+ );+ const trimmedInstruction = instruction.trim();+ const now = Date.now();+ const messagesWithInstruction = trimmedInstruction+ ? [+ ...currentMessages,+ {+ content: `<speaker name="Supervisor" />\n${instruction}`,+ createdAt: now,+ id: `virtual_speak_instruction_${now}`,+ role: 'user' as const,+ updatedAt: now,+ },+ ]+ : currentMessages;++ await this.#get().internal_execAgentRuntime({+ context: { ...context, scope: 'sub_agent', subAgentId: targetAgentId },+ inPortalThread,+ messages: messagesWithInstruction,+ parentMessageId: toolMessage.id,+ parentMessageType: 'tool',+ parentOperationId: operationId,+ });++ this.#get().completeOperation(operationId);+ } catch (error) {+ this.#get().failOperation(operationId, {+ type: 'DirectMentionRouteError',+ message: error instanceof Error ? error.message : String(error),+ });+ throw error;+ }+ }++ async #preloadDirectMentionAgentConfig(agentId: string): Promise<string | undefined> {+ const targetAgentExists = useAgentStore.getState().agentMap[agentId];+ if (targetAgentExists) return;++ try {+ const config = await agentService.getAgentConfigById(agentId);+ if (!config) {+ return `Agent "${agentId}" not found in your workspace. Please check the agent ID and try again.`;+ }++ useAgentStore.getState().internal_dispatchAgentMap(agentId, config);+ } catch (error) {+ console.error('[directMentionRoute] Failed to load agent config:', error);+ return `Failed to load agent "${agentId}": ${(error as Error).message}`;+ }+ }+continueGenerationMessage = async (id: string, messageId: string): Promise<void> => {const message = dbMessageSelectors.getDbMessageById(id)(this.#get());if (!message) return;