🤯 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
♻️ refactor: move skills/tools to @ mention with direct context injection (#13419)
Inneidbdbe16da97f
diff --git a/packages/builtin-agent-onboarding/src/toolSystemRole.ts b/packages/builtin-agent-onboarding/src/toolSystemRole.tsindex b4e3075b2e2..7fed2980d10 100644--- a/packages/builtin-agent-onboarding/src/toolSystemRole.ts+++ b/packages/builtin-agent-onboarding/src/toolSystemRole.ts@@ -5,7 +5,7 @@ Turn protocol:1. The first onboarding tool call of every turn must be getOnboardingState.2. Follow the phase returned by getOnboardingState. Do not advance the flow out of order. Exception: if the user clearly signals they want to leave (busy, disengaging, says goodbye), skip directly to a brief wrap-up and call finishOnboarding regardless of the current phase.3. Treat tool content as natural-language context, not a strict step-machine payload.-4. Prefer the lobe-user-interaction askUserQuestion API for structured collection, explicit choices, or UI-mediated input. For natural exploratory conversation, direct plain-text questions are allowed and often preferable.+4. Prefer the \`lobe-user-interaction________builtin\` tool for structured collection, explicit choices, or UI-mediated input. For natural exploratory conversation, direct plain-text questions are allowed and often preferable.5. Never claim something was saved, updated, created, or completed unless the corresponding tool call succeeded. If a tool call fails, recover from that result only.6. Never finish onboarding before the summary is shown and lightly confirmed, unless the user clearly signals they want to leave.diff --git a/packages/builtin-tool-activator/src/systemRole.ts b/packages/builtin-tool-activator/src/systemRole.tsindex 5dc866006a5..c8c0469953e 100644--- a/packages/builtin-tool-activator/src/systemRole.ts+++ b/packages/builtin-tool-activator/src/systemRole.ts@@ -20,6 +20,7 @@ export const systemPrompt = `You have access to a Tools & Skills Activator that- Provide the exact skill name- Returns the skill content (instructions, templates, guidelines) that you should follow- If the skill is not found, you'll receive a list of available skills+ - **IMPORTANT**: If a skill's content is already provided in \`<selected_skill_context>\` within the user message, do NOT call activateSkill for that skill — its instructions are already loaded and ready to use</tool_selection_guidelines><skill_store_discovery>diff --git a/packages/builtin-tool-agent-management/src/callAgentManifest.ts b/packages/builtin-tool-agent-management/src/callAgentManifest.tsnew file mode 100644index 00000000000..bc925dc9713--- /dev/null+++ b/packages/builtin-tool-agent-management/src/callAgentManifest.ts@@ -0,0 +1,43 @@+import type { InjectedToolManifest } from '@lobechat/types';++import { AgentManagementManifest } from './manifest';+import { AgentManagementApiName, AgentManagementIdentifier } from './types';++const callAgentSystemRole = `You have a callAgent tool to delegate tasks to other AI agents.++<execution_guide>+### Synchronous Call (default)+callAgent(agentId, instruction) — agent responds directly in conversation.++### Asynchronous Task+callAgent(agentId, instruction, runAsTask: true, taskTitle: "...") — agent works in background.+Use runAsTask for complex/long operations that shouldn't block conversation.+</execution_guide>`;++/**+ * Create a slim manifest containing only the callAgent API.+ * Used when @mentioned agents need delegation without the full Agent Management toolset.+ */+export const createCallAgentManifest = (): InjectedToolManifest => {+ const callAgentApi = AgentManagementManifest.api.find(+ (api) => api.name === AgentManagementApiName.callAgent,+ );++ if (!callAgentApi) {+ throw new Error('callAgent API not found in AgentManagementManifest');+ }++ return {+ api: [+ {+ description: callAgentApi.description,+ name: callAgentApi.name,+ parameters: callAgentApi.parameters,+ },+ ],+ identifier: AgentManagementIdentifier,+ meta: { description: 'Delegate tasks to other agents', title: 'Agent Management' },+ systemRole: callAgentSystemRole,+ type: 'builtin',+ };+};diff --git a/packages/builtin-tool-agent-management/src/index.ts b/packages/builtin-tool-agent-management/src/index.tsindex 95ce02e077d..a19e7045476 100644--- a/packages/builtin-tool-agent-management/src/index.ts+++ b/packages/builtin-tool-agent-management/src/index.ts@@ -1,3 +1,4 @@+export * from './callAgentManifest';export * from './manifest';export * from './systemRole';export * from './types';diff --git a/packages/builtin-tool-web-onboarding/src/ExecutionRuntime/utils.ts b/packages/builtin-tool-web-onboarding/src/ExecutionRuntime/utils.tsindex 4bc9c0ca98a..1403e793ef1 100644--- a/packages/builtin-tool-web-onboarding/src/ExecutionRuntime/utils.ts+++ b/packages/builtin-tool-web-onboarding/src/ExecutionRuntime/utils.ts@@ -54,7 +54,7 @@ export const formatWebOnboardingStateMessage = (state: OnboardingStateContext) =const phaseGuidance = PHASE_GUIDANCE[state.phase] || '';const parts: string[] = [phaseGuidance,- 'Questioning rule: use lobe-user-interaction askUserQuestion for structured collection or explicit UI input. For natural exploratory questions, plain text is allowed.',+ 'Questioning rule: use `lobe-user-interaction________builtin` tool for structured collection or explicit UI input. For natural exploratory questions, plain text is allowed.',];if (state.remainingDiscoveryExchanges !== undefined && state.remainingDiscoveryExchanges > 0) {diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.tsindex 3b311e381a0..0c0d59e7f01 100644--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts@@ -50,6 +50,7 @@ import {TopicReferenceContextInjector,UserMemoryInjector,} from '../../providers';+import { SelectedToolInjector } from '../../providers/SelectedToolInjector';import type { ContextProcessor } from '../../types';import { ToolNameResolver } from '../tools';import type { MessagesEngineParams, MessagesEngineResult } from './types';@@ -138,6 +139,7 @@ export class MessagesEngine {knowledge,skillsConfig,selectedSkills,+ selectedTools,toolDiscoveryConfig,toolsConfig,capabilities,@@ -171,6 +173,7 @@ export class MessagesEngine {isAgentGroupEnabled || !!agentGroup?.currentAgentId || !!agentGroup?.members;const isUserMemoryEnabled = !!(userMemory?.enabled && userMemory?.memories);const hasSelectedSkills = (selectedSkills?.length ?? 0) > 0;+ const hasSelectedTools = (selectedTools?.length ?? 0) > 0;const hasAgentDocuments = !!agentDocuments && agentDocuments.length > 0;// Page editor is enabled if either direct pageContentContext or initialContext.pageEditor is provided@@ -304,6 +307,8 @@ export class MessagesEngine {new AgentDocumentMessageInjector(agentDocConfig),// 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 }),// Page selections (inject user-selected text into each user message)new PageSelectionsInjector({ enabled: isPageEditorEnabled }),// Page Editor context (inject current page content to last user message)diff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.tsindex 665faef9beb..c75440e29a3 100644--- a/packages/context-engine/src/engine/messages/types.ts+++ b/packages/context-engine/src/engine/messages/types.ts@@ -3,6 +3,7 @@ import type { FileContent, KnowledgeBaseInfo, PageContentContext } from '@lobechimport type {RuntimeInitialContext,RuntimeSelectedSkill,+ RuntimeSelectedTool,RuntimeStepContext,} from '@lobechat/types';@@ -251,6 +252,8 @@ export interface MessagesEngineParams {skillsConfig?: SkillsConfig;/** Skills explicitly selected by the user for the current request */selectedSkills?: RuntimeSelectedSkill[];+ /** Tools explicitly selected by the user for the current request */+ selectedTools?: RuntimeSelectedTool[];// ========== Tool Discovery ==========/** Tool Discovery configuration (available tools for dynamic activation) */diff --git a/packages/context-engine/src/providers/AgentManagementContextInjector.ts b/packages/context-engine/src/providers/AgentManagementContextInjector.tsindex a67ce291e0a..d8a5b6c420c 100644--- a/packages/context-engine/src/providers/AgentManagementContextInjector.ts+++ b/packages/context-engine/src/providers/AgentManagementContextInjector.ts@@ -174,7 +174,7 @@ const formatMentionedAgentsContext = (mentionedAgents: RuntimeMentionedAgent[]):.join('\n');return `<mentioned_agents>-<instruction>The user has @mentioned the following agent(s) in their message. You MUST use the callAgent tool to delegate the user's request to the mentioned agent. Do NOT attempt to handle the request yourself — call the agent and let them respond.</instruction>+<instruction>The user has @mentioned the following agent(s) in their message. You MUST call the \`lobe-agent-management____callAgent____builtin\` tool to delegate the user's request to the mentioned agent. Do NOT attempt to handle the request yourself — call the agent and let them respond.</instruction>${agentsXml}</mentioned_agents>`;};diff --git a/packages/context-engine/src/providers/SelectedSkillInjector.ts b/packages/context-engine/src/providers/SelectedSkillInjector.tsindex 047f5453629..30e155d56a2 100644--- a/packages/context-engine/src/providers/SelectedSkillInjector.ts+++ b/packages/context-engine/src/providers/SelectedSkillInjector.ts@@ -3,6 +3,7 @@ import type { RuntimeSelectedSkill } from '@lobechat/types';import debug from 'debug';import { BaseLastUserContentProvider } from '../base/BaseLastUserContentProvider';+import { CONTEXT_INSTRUCTION, SYSTEM_CONTEXT_END, SYSTEM_CONTEXT_START } from '../base/constants';import type { PipelineContext, ProcessorOptions } from '../types';declare module '../types' {@@ -21,22 +22,84 @@ export interface SelectedSkillInjectorConfig {selectedSkills?: RuntimeSelectedSkill[];}-const formatSelectedSkills = (selectedSkills: RuntimeSelectedSkill[]): string | null => {+export const formatSelectedSkills = (selectedSkills: RuntimeSelectedSkill[]): string | null => {if (selectedSkills.length === 0) return null;const lines = [- 'The user explicitly selected these skills for this request. Prefer them when relevant.',+ 'The user explicitly selected these skills for this request. Their full instructions are already loaded below — do NOT call activateSkill for these skills, use the provided content directly.','<selected_skills>',- ...selectedSkills.map(- (skill) =>- ` <skill identifier="${escapeXml(skill.identifier)}" name="${escapeXml(skill.name)}" />`,- ),- '</selected_skills>',];+ for (const skill of selectedSkills) {+ if (skill.content) {+ lines.push(+ ` <skill identifier="${escapeXml(skill.identifier)}" name="${escapeXml(skill.name)}">`,+ skill.content,+ ' </skill>',+ );+ } else {+ lines.push(+ ` <skill identifier="${escapeXml(skill.identifier)}" name="${escapeXml(skill.name)}" />`,+ );+ }+ }++ lines.push('</selected_skills>');+return lines.join('\n');};+/**+ * Format selected skills as a complete system-context block for message content persistence.+ * Returns null if no skills with content are provided.+ */+export const formatSelectedSkillsContext = (+ selectedSkills: RuntimeSelectedSkill[],+): string | null => {+ const inner = formatSelectedSkills(selectedSkills);+ if (!inner) return null;++ return [+ SYSTEM_CONTEXT_START,+ CONTEXT_INSTRUCTION,+ `<selected_skill_context>`,+ inner,+ `</selected_skill_context>`,+ SYSTEM_CONTEXT_END,+ ].join('\n');+};++/**+ * Extract skill identifiers @mentioned in earlier messages via their persisted editorData.+ * Walks the Lexical JSON tree looking for action-tag nodes with actionCategory === 'skill'.+ */+const collectMentionedSkillIds = (+ messages: PipelineContext['messages'],+ excludeIndex: number,+): Set<string> => {+ const ids = new Set<string>();+ for (let i = 0; i < messages.length; i++) {+ if (i === excludeIndex) continue;+ const ed = messages[i].editorData;+ if (!ed) continue;+ walkActionTags(ed.root, (category, type) => {+ if (category === 'skill' && type) ids.add(String(type));+ });+ }+ return ids;+};++/** Walk Lexical JSON tree to find action-tag nodes. */+const walkActionTags = (node: any, cb: (category: string, type: string) => void): void => {+ if (!node) return;+ if (node.type === 'action-tag') {+ cb(node.actionCategory, node.actionType);+ }+ if (Array.isArray(node.children)) {+ for (const child of node.children) walkActionTags(child, cb);+ }+};+/*** Selected Skill Injector* Appends user-selected slash-menu skills to the last user message as ephemeral context.@@ -55,24 +118,42 @@ export class SelectedSkillInjector extends BaseLastUserContentProvider {if (this.config.enabled === false) return this.markAsExecuted(context);const clonedContext = this.cloneContext(context);- const selectedSkills = this.config.selectedSkills ?? [];+ const allSelectedSkills = this.config.selectedSkills ?? [];- if (selectedSkills.length === 0) {+ if (allSelectedSkills.length === 0) {log('No selected skills, skipping injection');return this.markAsExecuted(clonedContext);}+ // Deduplicate: skip skills already @mentioned in earlier messages (via editorData)+ const lastUserIndex = this.findLastUserMessageIndex(clonedContext.messages);- const content = formatSelectedSkills(selectedSkills);+ if (lastUserIndex === -1) {+ log('No user messages found, skipping injection');+ return this.markAsExecuted(clonedContext);+ }- if (!content) {- log('No selected skill content generated, skipping injection');+ const previousIds = collectMentionedSkillIds(clonedContext.messages, lastUserIndex);+ const selectedSkills =+ previousIds.size > 0+ ? allSelectedSkills.filter((s) => !previousIds.has(s.identifier))+ : allSelectedSkills;++ if (selectedSkills.length < allSelectedSkills.length) {+ log(+ 'Deduplicated %d skills already @mentioned in earlier messages (via editorData)',+ allSelectedSkills.length - selectedSkills.length,+ );+ }++ if (selectedSkills.length === 0) {+ log('All selected skills already injected in earlier messages, skipping');return this.markAsExecuted(clonedContext);}- const lastUserIndex = this.findLastUserMessageIndex(clonedContext.messages);+ const content = formatSelectedSkills(selectedSkills);- if (lastUserIndex === -1) {- log('No user messages found, skipping injection');+ if (!content) {+ log('No selected skill content generated, skipping injection');return this.markAsExecuted(clonedContext);}diff --git a/packages/context-engine/src/providers/SelectedToolInjector.ts b/packages/context-engine/src/providers/SelectedToolInjector.tsnew file mode 100644index 00000000000..8d9463905c7--- /dev/null+++ b/packages/context-engine/src/providers/SelectedToolInjector.ts@@ -0,0 +1,175 @@+import { escapeXml } from '@lobechat/prompts';+import type { RuntimeSelectedTool } from '@lobechat/types';+import debug from 'debug';++import { BaseLastUserContentProvider } from '../base/BaseLastUserContentProvider';+import { CONTEXT_INSTRUCTION, SYSTEM_CONTEXT_END, SYSTEM_CONTEXT_START } from '../base/constants';+import type { PipelineContext, ProcessorOptions } from '../types';++declare module '../types' {+ interface PipelineContextMetadataOverrides {+ selectedToolContext?: {+ injected: boolean;+ toolsCount: number;+ };+ }+}++const log = debug('context-engine:provider:SelectedToolInjector');++export interface SelectedToolInjectorConfig {+ enabled?: boolean;+ selectedTools?: RuntimeSelectedTool[];+}++export const formatSelectedTools = (selectedTools: RuntimeSelectedTool[]): string | null => {+ if (selectedTools.length === 0) return null;++ const lines = [+ 'The user explicitly selected these tools for this request. Use them proactively without waiting for further instruction.',+ '<selected_tools>',+ ];++ for (const tool of selectedTools) {+ if (tool.content) {+ // Tool has preloaded context — inject full description+ lines.push(+ ` <tool identifier="${escapeXml(tool.identifier)}" name="${escapeXml(tool.name)}">`,+ tool.content,+ ' </tool>',+ );+ } else {+ lines.push(+ ` <tool identifier="${escapeXml(tool.identifier)}" name="${escapeXml(tool.name)}" />`,+ );+ }+ }++ lines.push('</selected_tools>');++ return lines.join('\n');+};++/**+ * Format selected tools as a complete system-context block for message content persistence.+ * Returns null if no tools are provided.+ */+export const formatSelectedToolsContext = (selectedTools: RuntimeSelectedTool[]): string | null => {+ const inner = formatSelectedTools(selectedTools);+ if (!inner) return null;++ return [+ SYSTEM_CONTEXT_START,+ CONTEXT_INSTRUCTION,+ `<selected_tool_context>`,+ inner,+ `</selected_tool_context>`,+ SYSTEM_CONTEXT_END,+ ].join('\n');+};++/**+ * Extract tool identifiers @mentioned in earlier messages via their persisted editorData.+ */+const collectMentionedToolIds = (+ messages: PipelineContext['messages'],+ excludeIndex: number,+): Set<string> => {+ const ids = new Set<string>();+ for (let i = 0; i < messages.length; i++) {+ if (i === excludeIndex) continue;+ const ed = messages[i].editorData;+ if (!ed) continue;+ walkActionTags(ed.root, (category, type) => {+ if (category === 'tool' && type) ids.add(String(type));+ });+ }+ return ids;+};++/** Walk Lexical JSON tree to find action-tag nodes. */+const walkActionTags = (node: any, cb: (category: string, type: string) => void): void => {+ if (!node) return;+ if (node.type === 'action-tag') {+ cb(node.actionCategory, node.actionType);+ }+ if (Array.isArray(node.children)) {+ for (const child of node.children) walkActionTags(child, cb);+ }+};++/**+ * Selected Tool Injector+ * Appends user-selected tools to the last user message as ephemeral context.+ */+export class SelectedToolInjector extends BaseLastUserContentProvider {+ readonly name = 'SelectedToolInjector';++ constructor(+ private config: SelectedToolInjectorConfig,+ options: ProcessorOptions = {},+ ) {+ super(options);+ }++ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {+ if (this.config.enabled === false) return this.markAsExecuted(context);++ const clonedContext = this.cloneContext(context);+ const allSelectedTools = this.config.selectedTools ?? [];++ if (allSelectedTools.length === 0) {+ log('No selected tools, skipping injection');+ return this.markAsExecuted(clonedContext);+ }++ // Deduplicate: skip tools already @mentioned in earlier messages (via editorData)+ const lastUserIndex = this.findLastUserMessageIndex(clonedContext.messages);++ if (lastUserIndex === -1) {+ log('No user messages found, skipping injection');+ return this.markAsExecuted(clonedContext);+ }++ const previousIds = collectMentionedToolIds(clonedContext.messages, lastUserIndex);+ const selectedTools =+ previousIds.size > 0+ ? allSelectedTools.filter((t) => !previousIds.has(t.identifier))+ : allSelectedTools;++ if (selectedTools.length < allSelectedTools.length) {+ log(+ 'Deduplicated %d tools already @mentioned in earlier messages (via editorData)',+ allSelectedTools.length - selectedTools.length,+ );+ }++ if (selectedTools.length === 0) {+ log('All selected tools already injected in earlier messages, skipping');+ return this.markAsExecuted(clonedContext);+ }++ const content = formatSelectedTools(selectedTools);++ if (!content) {+ log('No selected tool content generated, skipping injection');+ return this.markAsExecuted(clonedContext);+ }++ const hasExistingWrapper = this.hasExistingSystemContext(clonedContext);+ const contentToAppend = hasExistingWrapper+ ? this.createContextBlock(content, 'selected_tool_context')+ : this.wrapWithSystemContext(content, 'selected_tool_context');++ this.appendToLastUserMessage(clonedContext, contentToAppend);++ clonedContext.metadata.selectedToolContext = {+ injected: true,+ toolsCount: selectedTools.length,+ };++ log('Selected tool context appended, tools count: %d', selectedTools.length);++ return this.markAsExecuted(clonedContext);+ }+}diff --git a/packages/context-engine/src/providers/__tests__/AgentManagementContextInjector.test.ts b/packages/context-engine/src/providers/__tests__/AgentManagementContextInjector.test.tsindex a9e56578972..b06a1997ef6 100644--- a/packages/context-engine/src/providers/__tests__/AgentManagementContextInjector.test.ts+++ b/packages/context-engine/src/providers/__tests__/AgentManagementContextInjector.test.ts@@ -90,7 +90,9 @@ describe('AgentManagementContextInjector', () => {expect(delegationMsg.content).toContain('<mentioned_agents>');expect(delegationMsg.content).toContain('agt_designer');expect(delegationMsg.content).toContain('Designer Agent');- expect(delegationMsg.content).toContain('MUST use the callAgent tool');+ expect(delegationMsg.content).toContain(+ 'MUST call the `lobe-agent-management____callAgent____builtin` tool',+ );expect(delegationMsg.meta.injectType).toBe('agent-mention-delegation');});diff --git a/packages/context-engine/src/providers/__tests__/SelectedSkillInjector.test.ts b/packages/context-engine/src/providers/__tests__/SelectedSkillInjector.test.tsindex 7b4077e2847..15174f6af27 100644--- a/packages/context-engine/src/providers/__tests__/SelectedSkillInjector.test.ts+++ b/packages/context-engine/src/providers/__tests__/SelectedSkillInjector.test.ts@@ -47,6 +47,31 @@ describe('SelectedSkillInjector', () => {});});+ it('should inject skill content inline when available', async () => {+ const provider = new SelectedSkillInjector({+ selectedSkills: [+ {+ content: 'Use grep to search the codebase.\n\n## Usage\ngrep pattern file',+ identifier: 'grep',+ name: 'Grep',+ },+ { identifier: 'translate', name: 'Translate' },+ ],+ });++ const context = createContext([{ content: 'Search for foo', id: 'user-1', role: 'user' }]);++ const result = await provider.process(context);+ const content = result.messages[0].content as string;++ // Skill with content: open/close tag with content inside+ expect(content).toContain('<skill identifier="grep" name="Grep">');+ expect(content).toContain('Use grep to search the codebase.');+ expect(content).toContain('</skill>');+ // Skill without content: self-closing tag+ expect(content).toContain('<skill identifier="translate" name="Translate" />');+ });+it('should reuse existing system context wrapper on the last user message', async () => {const provider = new SelectedSkillInjector({selectedSkills: [{ identifier: 'user_memory', name: 'User Memory' }],diff --git a/packages/context-engine/src/providers/__tests__/SelectedToolInjector.test.ts b/packages/context-engine/src/providers/__tests__/SelectedToolInjector.test.tsnew file mode 100644index 00000000000..0b095f71402--- /dev/null+++ b/packages/context-engine/src/providers/__tests__/SelectedToolInjector.test.ts@@ -0,0 +1,102 @@+import { describe, expect, it } from 'vitest';++import type { PipelineContext } from '../../types';+import { SelectedToolInjector } from '../SelectedToolInjector';++const createContext = (messages: any[] = []): PipelineContext => ({+ initialState: {+ messages: [],+ model: 'gpt-4',+ provider: 'openai',+ },+ isAborted: false,+ messages,+ metadata: {+ maxTokens: 4096,+ model: 'gpt-4',+ },+});++describe('SelectedToolInjector', () => {+ it('should skip when no tools selected', async () => {+ const provider = new SelectedToolInjector({ selectedTools: [] });++ const context = createContext([{ content: 'Current request', id: 'user-1', role: 'user' }]);++ const result = await provider.process(context);++ expect(result.messages).toHaveLength(1);+ expect(result.messages[0].content).toBe('Current request');+ expect(result.metadata.selectedToolContext).toBeUndefined();+ });++ it('should inject selected tools into the last user message', async () => {+ const provider = new SelectedToolInjector({+ selectedTools: [+ { identifier: 'web-search', name: 'Web Search' },+ { identifier: 'code-interpreter', name: 'Code Interpreter' },+ ],+ });++ const context = createContext([+ { content: 'Earlier question', id: 'user-1', role: 'user' },+ { content: 'Assistant reply', id: 'assistant-1', role: 'assistant' },+ { content: 'Current request', id: 'user-2', role: 'user' },+ ]);++ const result = await provider.process(context);++ expect(result.messages).toHaveLength(3);+ expect(result.messages[2].content).toContain('Current request');+ expect(result.messages[2].content).toContain('<selected_tool_context>');+ expect(result.messages[2].content).toContain('<selected_tools>');+ expect(result.messages[2].content).toContain(+ '<tool identifier="web-search" name="Web Search" />',+ );+ expect(result.metadata.selectedToolContext).toEqual({+ injected: true,+ toolsCount: 2,+ });+ });++ it('should inject tool content inline when available', async () => {+ const provider = new SelectedToolInjector({+ selectedTools: [+ {+ content: 'Search the web for information.\n\nAvailable APIs:\n- search: Search the web',+ identifier: 'web-search',+ name: 'Web Search',+ },+ { identifier: 'dalle', name: 'DALL-E' },+ ],+ });++ const context = createContext([+ { content: 'Find info about cats', id: 'user-1', role: 'user' },+ ]);++ const result = await provider.process(context);++ const content = result.messages[0].content as string;+ // Tool with content: rendered as open/close tag with content inside+ expect(content).toContain('<tool identifier="web-search" name="Web Search">');+ expect(content).toContain('Search the web for information.');+ expect(content).toContain('</tool>');+ // Tool without content: self-closing tag+ expect(content).toContain('<tool identifier="dalle" name="DALL-E" />');+ });++ it('should skip when disabled', async () => {+ const provider = new SelectedToolInjector({+ enabled: false,+ selectedTools: [{ identifier: 'web-search', name: 'Web Search' }],+ });++ const context = createContext([{ content: 'Current request', id: 'user-1', role: 'user' }]);++ const result = await provider.process(context);++ expect(result.messages[0].content).toBe('Current request');+ expect(result.metadata.selectedToolContext).toBeUndefined();+ });+});diff --git a/packages/context-engine/src/providers/index.ts b/packages/context-engine/src/providers/index.tsindex 6a414839a15..88ee2e053d8 100644--- a/packages/context-engine/src/providers/index.ts+++ b/packages/context-engine/src/providers/index.ts@@ -21,7 +21,16 @@ export { HistorySummaryProvider } from './HistorySummary';export { KnowledgeInjector } from './KnowledgeInjector';export { PageEditorContextInjector } from './PageEditorContextInjector';export { PageSelectionsInjector } from './PageSelectionsInjector';-export { SelectedSkillInjector } from './SelectedSkillInjector';+export {+ formatSelectedSkills,+ formatSelectedSkillsContext,+ SelectedSkillInjector,+} from './SelectedSkillInjector';+export {+ formatSelectedTools,+ formatSelectedToolsContext,+ SelectedToolInjector,+} from './SelectedToolInjector';export { SkillContextProvider } from './SkillContextProvider';export { SystemDateProvider } from './SystemDateProvider';export { SystemRoleInjector } from './SystemRoleInjector';@@ -78,6 +87,7 @@ export type { KnowledgeInjectorConfig } from './KnowledgeInjector';export type { PageEditorContextInjectorConfig } from './PageEditorContextInjector';export type { PageSelectionsInjectorConfig } from './PageSelectionsInjector';export type { SelectedSkillInjectorConfig } from './SelectedSkillInjector';+export type { SelectedToolInjectorConfig } from './SelectedToolInjector';export type { SkillContextProviderConfig, SkillMeta } from './SkillContextProvider';export type { SystemDateProviderConfig } from './SystemDateProvider';export type { SystemRoleInjectorConfig } from './SystemRoleInjector';diff --git a/packages/types/src/stepContext.ts b/packages/types/src/stepContext.tsindex f758a93e9c5..3cec4cb27c8 100644--- a/packages/types/src/stepContext.ts+++ b/packages/types/src/stepContext.ts@@ -79,6 +79,12 @@ export interface InitialPageEditorContext {* Captured from slash-menu skill action tags before send*/export interface RuntimeSelectedSkill {+ /**+ * Preloaded skill content (markdown instructions).+ * When present, injected directly into user message instead of+ * constructing fake activateSkill tool-call preload messages.+ */+ content?: string;/*** Skill identifier used by runtime/tooling*/@@ -94,6 +100,12 @@ export interface RuntimeSelectedSkill {* Captured from slash-menu tool action tags before send*/export interface RuntimeSelectedTool {+ /**+ * Preloaded tool context (systemRole + API descriptions).+ * When present, injected directly into user message instead of relying on+ * LLM to discover/activate the tool at runtime — saves tokens.+ */+ content?: string;/*** Tool identifier used by runtime/tooling*/@@ -158,6 +170,23 @@ export interface RuntimeMentionedAgent {name: string;}+/**+ * A slim tool manifest injected at runtime by callers (e.g. @mention → callAgent).+ * Structurally compatible with LobeToolManifest from @lobechat/context-engine+ * without requiring a cross-package import.+ */+export interface InjectedToolManifest {+ api: Array<{+ description: string;+ name: string;+ parameters: Record<string, any>;+ }>;+ identifier: string;+ meta: { description?: string; title?: string };+ systemRole?: string;+ type?: 'builtin' | 'default' | 'markdown' | 'mcp' | 'standalone';+}+/*** Initial Context*@@ -165,6 +194,12 @@ export interface RuntimeMentionedAgent {* Remains constant throughout the operation lifecycle.*/export interface RuntimeInitialContext {+ /**+ * Ad-hoc tool manifests injected by callers for the current request.+ * Merged into the tool resolution output without passing through ToolsEngine.+ * Deduplication: manifests whose identifier already appears in enabledToolIds are skipped.+ */+ injectedManifests?: InjectedToolManifest[];/*** Agents explicitly @mentioned by the user in the input editor.* When present in a non-group conversation, the current agent acts asdiff --git a/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.ts b/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.tsindex 90ece93149a..a5359b1e86f 100644--- a/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.ts+++ b/src/features/ChatInput/InputEditor/ActionTag/ActionTagPlugin.ts@@ -53,9 +53,20 @@ export class ActionTagPlugin {const mdService = this.kernel.requireService(IMarkdownShortCutService);// Writer: ActionTagNode → markdown+ // Skills → <skill name="..." label="..." />, Tools → <tool name="..." label="..." />+ // Commands fall back to <action type="..." category="command" label="..." />mdService?.registerMarkdownWriter(ActionTagNode.getType(), (ctx: any, node: any) => {if ($isActionTagNode(node)) {- ctx.appendLine(`<action type="${node.actionType}" category="${node.actionCategory}" />`);+ const cat = node.actionCategory;+ if (cat === 'skill') {+ ctx.appendLine(`<skill name="${node.actionType}" label="${node.actionLabel}" />`);+ } else if (cat === 'tool') {+ ctx.appendLine(`<tool name="${node.actionType}" label="${node.actionLabel}" />`);+ } else {+ ctx.appendLine(+ `<action type="${node.actionType}" category="${cat}" label="${node.actionLabel}" />`,+ );+ }}});}@@ -65,8 +76,15 @@ export class ActionTagPlugin {xmlService?.registerXMLWriter(ActionTagNode.getType(), (node: any, ctx: any) => {if ($isActionTagNode(node)) {+ const cat = node.actionCategory;+ if (cat === 'skill') {+ return ctx.createXmlNode('skill', { label: node.actionLabel, name: node.actionType });+ }+ if (cat === 'tool') {+ return ctx.createXmlNode('tool', { label: node.actionLabel, name: node.actionType });+ }return ctx.createXmlNode('action', {- category: node.actionCategory,+ category: cat,label: node.actionLabel,type: node.actionType,});@@ -74,15 +92,32 @@ export class ActionTagPlugin {return false;});- xmlService?.registerXMLReader('action', (xmlElement: any) => {- return {- actionCategory: (xmlElement.getAttribute('category') || 'skill') as ActionTagCategory,- actionLabel: xmlElement.getAttribute('label') || '',- actionType: (xmlElement.getAttribute('type') || 'translate') as ActionTagType,- type: ActionTagNode.getType(),- version: 1,- } satisfies SerializedActionTagNode;+ // Read <skill>, <tool>, and legacy <action> tags+ const readSkill = (xmlElement: any): SerializedActionTagNode => ({+ actionCategory: 'skill',+ actionLabel: xmlElement.getAttribute('label') || '',+ actionType: (xmlElement.getAttribute('name') || '') as ActionTagType,+ type: ActionTagNode.getType(),+ version: 1,});+ const readTool = (xmlElement: any): SerializedActionTagNode => ({+ actionCategory: 'tool',+ actionLabel: xmlElement.getAttribute('label') || '',+ actionType: (xmlElement.getAttribute('name') || '') as ActionTagType,+ type: ActionTagNode.getType(),+ version: 1,+ });+ const readLegacyAction = (xmlElement: any): SerializedActionTagNode => ({+ actionCategory: (xmlElement.getAttribute('category') || 'skill') as ActionTagCategory,+ actionLabel: xmlElement.getAttribute('label') || '',+ actionType: (xmlElement.getAttribute('type') || 'translate') as ActionTagType,+ type: ActionTagNode.getType(),+ version: 1,+ });++ xmlService?.registerXMLReader('skill', readSkill);+ xmlService?.registerXMLReader('tool', readTool);+ xmlService?.registerXMLReader('action', readLegacyAction);}destroy(): void {diff --git a/src/features/ChatInput/InputEditor/ActionTag/types.ts b/src/features/ChatInput/InputEditor/ActionTag/types.tsindex ad1ee00b9d6..9c6f1869a31 100644--- a/src/features/ChatInput/InputEditor/ActionTag/types.ts+++ b/src/features/ChatInput/InputEditor/ActionTag/types.ts@@ -1,9 +1,9 @@/**- * Slash action architecture:+ * Action tag architecture:*- * 1. Command — Built-in, line-start only, executed client-side before send- * 2. Skill — Skill package, line-start, can be preloaded before execution- * 3. Tool — Explicit tool selection, line-start, separate from skill packages+ * 1. Command — Built-in, line-start only (slash menu), executed client-side before send+ * 2. Skill — Skill package, inserted via @ mention, preloaded before execution+ * 3. Tool — Explicit tool selection, inserted via @ mention, context injected directly*/export type ActionTagCategory = 'command' | 'skill' | 'tool';diff --git a/src/features/ChatInput/InputEditor/ActionTag/useEnabledSkills.ts b/src/features/ChatInput/InputEditor/ActionTag/useEnabledSkills.tsdeleted file mode 100644index e84928635cb..00000000000--- a/src/features/ChatInput/InputEditor/ActionTag/useEnabledSkills.ts+++ /dev/null@@ -1,82 +0,0 @@-import isEqual from 'fast-deep-equal';-import { useMemo } from 'react';--import { useToolStore } from '@/store/tool';-import {- agentSkillsSelectors,- builtinToolSelectors,- klavisStoreSelectors,- lobehubSkillStoreSelectors,- pluginSelectors,-} from '@/store/tool/selectors';--import type { ActionTagData } from './types';--/**- * Collects all available slash-selectable skills/tools and returns them as ActionTagData[].- */-export const useEnabledSkills = (): ActionTagData[] => {- // All data sources- const builtinList = useToolStore(builtinToolSelectors.metaList, isEqual);- const builtinSkills = useToolStore(builtinToolSelectors.installedBuiltinSkills, isEqual);- const installedPlugins = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);- const klavisServers = useToolStore(klavisStoreSelectors.getServers, isEqual);- const lobehubSkillServers = useToolStore(lobehubSkillStoreSelectors.getServers, isEqual);- const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);- const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);-- return useMemo(() => {- const items: ActionTagData[] = [];- const skillNameMap = new Map<string, string>();- const toolNameMap = new Map<string, string>();-- const skillIconMap = new Map<string, string | undefined>();- const toolIconMap = new Map<string, string | undefined>();-- for (const item of builtinList) {- toolNameMap.set(item.identifier, item.meta?.title || item.identifier);- toolIconMap.set(item.identifier, item.meta?.avatar);- }- for (const item of installedPlugins) {- toolNameMap.set(item.identifier, item.title || item.identifier);- toolIconMap.set(item.identifier, item.avatar);- }- for (const item of klavisServers) {- toolNameMap.set(item.identifier, item.serverName || item.identifier);- toolIconMap.set(item.identifier, item.icon);- }- for (const item of lobehubSkillServers) {- toolNameMap.set(item.identifier, item.name || item.identifier);- toolIconMap.set(item.identifier, item.icon);- }-- for (const item of builtinSkills) {- skillNameMap.set(item.identifier, item.name || item.identifier);- skillIconMap.set(item.identifier, item.avatar);- }- for (const item of marketAgentSkills) {- skillNameMap.set(item.identifier, item.name || item.identifier);- }- for (const item of userAgentSkills) {- skillNameMap.set(item.identifier, item.name || item.identifier);- }-- for (const [id, label] of skillNameMap) {- items.push({ category: 'skill', icon: skillIconMap.get(id), label, type: id });- }-- for (const [id, label] of toolNameMap) {- items.push({ category: 'tool', icon: toolIconMap.get(id), label, type: id });- }-- return items;- }, [- builtinList,- builtinSkills,- installedPlugins,- klavisServers,- lobehubSkillServers,- marketAgentSkills,- userAgentSkills,- ]);-};diff --git a/src/features/ChatInput/InputEditor/ActionTag/useInstalledSkillsAndTools.ts b/src/features/ChatInput/InputEditor/ActionTag/useInstalledSkillsAndTools.tsnew file mode 100644index 00000000000..2b8616cddaf--- /dev/null+++ b/src/features/ChatInput/InputEditor/ActionTag/useInstalledSkillsAndTools.ts@@ -0,0 +1,90 @@+import isEqual from 'fast-deep-equal';+import { useMemo } from 'react';++import { useToolStore } from '@/store/tool';+import {+ agentSkillsSelectors,+ builtinToolSelectors,+ klavisStoreSelectors,+ lobehubSkillStoreSelectors,+ pluginSelectors,+} from '@/store/tool/selectors';++import type { ActionTagData } from './types';++/**+ * Collects all installed skills and tools, returning them as ActionTagData[].+ * Skills: builtinSkills, lobehubSkillServers, marketAgentSkills, userAgentSkills+ * Tools: installedPlugins (excluding skill-type entries), klavisServers+ */+export const useInstalledSkillsAndTools = (): ActionTagData[] => {+ const builtinSkills = useToolStore(builtinToolSelectors.installedBuiltinSkills, isEqual);+ const installedPlugins = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);+ const klavisServers = useToolStore(klavisStoreSelectors.getServers, isEqual);+ const lobehubSkillServers = useToolStore(lobehubSkillStoreSelectors.getServers, isEqual);+ const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);+ const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);++ return useMemo(() => {+ const items: ActionTagData[] = [];++ // --- Build skill set (identifier → { label, icon }) ---+ const skillMap = new Map<string, { icon?: string; label: string }>();++ for (const item of builtinSkills) {+ skillMap.set(item.identifier, { icon: item.avatar, label: item.name || item.identifier });+ }+ for (const item of lobehubSkillServers) {+ if (!skillMap.has(item.identifier)) {+ skillMap.set(item.identifier, { icon: item.icon, label: item.name || item.identifier });+ }+ }+ for (const item of marketAgentSkills) {+ if (!skillMap.has(item.identifier)) {+ skillMap.set(item.identifier, { label: item.name || item.identifier });+ }+ }+ for (const item of userAgentSkills) {+ if (!skillMap.has(item.identifier)) {+ skillMap.set(item.identifier, { label: item.name || item.identifier });+ }+ }++ // --- Build tool set, excluding identifiers already classified as skills ---+ const toolMap = new Map<string, { icon?: string; label: string }>();++ for (const item of installedPlugins) {+ // Skip entries that are actually skills (lobehub skill, agent skill, builtin skill)+ if (skillMap.has(item.identifier)) continue;+ if (!toolMap.has(item.identifier)) {+ toolMap.set(item.identifier, { icon: item.avatar, label: item.title || item.identifier });+ }+ }+ for (const item of klavisServers) {+ if (skillMap.has(item.identifier)) continue;+ if (!toolMap.has(item.identifier)) {+ toolMap.set(item.identifier, {+ icon: item.icon,+ label: item.serverName || item.identifier,+ });+ }+ }++ // --- Merge into output ---+ for (const [id, { icon, label }] of skillMap) {+ items.push({ category: 'skill', icon, label, type: id });+ }+ for (const [id, { icon, label }] of toolMap) {+ items.push({ category: 'tool', icon, label, type: id });+ }++ return items;+ }, [+ builtinSkills,+ installedPlugins,+ klavisServers,+ lobehubSkillServers,+ marketAgentSkills,+ userAgentSkills,+ ]);+};diff --git a/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts b/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.tsindex f228ab8f94b..b70ca9d8864 100644--- a/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts+++ b/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts@@ -1,9 +1,8 @@import type { IEditor, SlashOptions } from '@lobehub/editor';-import { SkillsIcon } from '@lobehub/ui/icons';import Fuse from 'fuse.js';import { $getSelection, $isRangeSelection } from 'lexical';import { ArchiveIcon, MessageSquarePlusIcon } from 'lucide-react';-import { createElement, type FC, useCallback } from 'react';+import { useCallback } from 'react';import { useTranslation } from 'react-i18next';import { useChatStore } from '@/store/chat';@@ -11,7 +10,6 @@ import { useChatStore } from '@/store/chat';import { useChatInputStore } from '../../store';import { INSERT_ACTION_TAG_COMMAND, type InsertActionTagPayload } from './command';import { type ActionTagData, BUILTIN_COMMANDS } from './types';-import { useEnabledSkills } from './useEnabledSkills';type SlashItem = NonNullable<SlashOptions['items'] extends (infer U)[] ? U : never>;@@ -28,45 +26,10 @@ const COMMAND_ICONS: Record<string, any> = {newTopic: MessageSquarePlusIcon,};-/** Remote/object URLs and data-URI images (plugin/skill avatars); not plain text. */-const shouldRenderIconAsImage = (str: string) =>- str.startsWith('http://') ||- str.startsWith('https://') ||- str.startsWith('blob:') ||- /^data:image\//i.test(str);--const iconCache = new Map<string, FC>();--const getIconComponent = (avatar: string | undefined): any => {- if (!avatar) return SkillsIcon;-- const cached = iconCache.get(avatar);- if (cached) return cached;-- let IconComp: FC;-- if (shouldRenderIconAsImage(avatar)) {- IconComp = () =>- createElement('img', {- alt: '',- height: 16,- src: avatar,- style: { flexShrink: 0, objectFit: 'contain' },- width: 16,- });- } else {- IconComp = () => createElement('span', { style: { fontSize: 16, lineHeight: 1 } }, avatar);- }-- iconCache.set(avatar, IconComp);- return IconComp;-};-export const useSlashActionItems = (): SlashOptions['items'] => {const { t } = useTranslation('editor');const editorInstance = useChatInputStore((s) => s.editor);const activeTopicId = useChatStore((s) => s.activeTopicId);- const enabledSkills = useEnabledSkills();return useCallback(async (@@ -89,21 +52,6 @@ export const useSlashActionItems = (): SlashOptions['items'] => {},});- const makeActionItem = (item: ActionTagData): SlashMenuOption => ({- icon: getIconComponent(item.icon),- key: `${item.category}-${item.type}`,- label: item.label,- metadata: { category: item.category, type: item.type },- onSelect: (editor: IEditor) => {- const payload: InsertActionTagPayload = {- category: item.category,- label: item.label,- type: item.type,- };- editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, payload);- },- });-// All action tags are line-start only for nowlet isAtLineStart = search === null;if (!isAtLineStart && editorInstance) {@@ -126,29 +74,20 @@ export const useSlashActionItems = (): SlashOptions['items'] => {if (!isAtLineStart) return [];- // 1. Built-in commands (filter newTopic when no active topic)+ // Built-in commands only (filter newTopic when no active topic)for (const action of BUILTIN_COMMANDS) {if (action.type === 'newTopic' && !activeTopicId) continue;allItems.push(makeCommandItem(action) as SlashItem);}- // 2. Enabled slash-selectable skills/tools- if (enabledSkills.length > 0) {- allItems.push({ type: 'divider' } as SlashItem);- for (const item of enabledSkills) {- allItems.push(makeActionItem(item) as SlashItem);- }- }-// Fuzzy filteringif (search?.matchingString && search.matchingString.length > 0) {- const searchable = allItems.filter((i) => !('type' in i) || (i as any).type !== 'divider');- const fuse = new Fuse(searchable, { keys: ['key', 'label'], threshold: 0.4 });+ const fuse = new Fuse(allItems, { keys: ['key', 'label'], threshold: 0.4 });return fuse.search(search.matchingString).map((r) => r.item);}return allItems;},- [t, editorInstance, activeTopicId, enabledSkills],+ [t, editorInstance, activeTopicId],);};diff --git a/src/features/ChatInput/InputEditor/MentionMenu/SearchView.tsx b/src/features/ChatInput/InputEditor/MentionMenu/SearchView.tsxindex 98670be94ac..7713964e2f2 100644--- a/src/features/ChatInput/InputEditor/MentionMenu/SearchView.tsx+++ b/src/features/ChatInput/InputEditor/MentionMenu/SearchView.tsx@@ -10,6 +10,21 @@ interface SearchViewProps {options: ISlashMenuOption[];}+const SEARCH_RESULT_CATEGORY_LABEL: Record<string, string> = {+ agent: 'Agent',+ member: 'Member',+ skill: 'Skill',+ tool: 'Tool',+ topic: 'Topic',+};++const getSearchResultCategoryLabel = (item: ISlashMenuOption): string | undefined => {+ const metadata = item.metadata as Record<string, unknown> | undefined;+ const type = metadata?.type;++ return typeof type === 'string' ? SEARCH_RESULT_CATEGORY_LABEL[type] : undefined;+};+const SearchView = memo<SearchViewProps>(({ options, activeKey, onSelectItem }) => {if (options.length === 0) {return <div className={styles.empty}>No results</div>;@@ -17,14 +32,23 @@ const SearchView = memo<SearchViewProps>(({ options, activeKey, onSelectItem })return (<div className={styles.scrollArea}>- {options.map((item) => (- <MenuItem- active={String(item.key) === activeKey}- item={item}- key={item.key}- onClick={onSelectItem}- />- ))}+ {options.map((item) => {+ const categoryLabel = getSearchResultCategoryLabel(item);++ return (+ <MenuItem+ active={String(item.key) === activeKey}+ item={item}+ key={item.key}+ extra={+ categoryLabel ? (+ <span className={styles.categoryExtra}>{categoryLabel}</span>+ ) : undefined+ }+ onClick={onSelectItem}+ />+ );+ })}</div>);});diff --git a/src/features/ChatInput/InputEditor/MentionMenu/types.ts b/src/features/ChatInput/InputEditor/MentionMenu/types.tsindex 1b3cd77992d..05c7e985bca 100644--- a/src/features/ChatInput/InputEditor/MentionMenu/types.ts+++ b/src/features/ChatInput/InputEditor/MentionMenu/types.ts@@ -1,7 +1,7 @@import type { ISlashMenuOption } from '@lobehub/editor';import type { ReactNode } from 'react';-export type MentionCategoryId = 'agent' | 'topic' | 'member';+export type MentionCategoryId = 'agent' | 'topic' | 'member' | 'skill' | 'tool';export interface MentionCategory {icon: ReactNode;diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsxindex 8c330599452..ca3a0cdef42 100644--- a/src/features/ChatInput/InputEditor/index.tsx+++ b/src/features/ChatInput/InputEditor/index.tsx@@ -25,7 +25,11 @@ import {import { useAgentId } from '../hooks/useAgentId';import { useChatInputStore, useStoreApi } from '../store';-import { useSlashActionItems } from './ActionTag';+import {+ INSERT_ACTION_TAG_COMMAND,+ type InsertActionTagPayload,+ useSlashActionItems,+} from './ActionTag';import { createMentionMenu } from './MentionMenu';import type { MentionMenuState } from './MentionMenu/types';import Placeholder from './Placeholder';@@ -249,6 +253,13 @@ const InputEditor = memo<{ defaultRows?: number }>(({ defaultRows = 2 }) => {topicId: option.metadata.topicId as string,topicTitle: String(option.metadata.topicTitle ?? option.label),});+ } else if (option.metadata?.type === 'skill' || option.metadata?.type === 'tool') {+ const payload: InsertActionTagPayload = {+ category: option.metadata.actionCategory as 'skill' | 'tool',+ label: String(option.label),+ type: String(option.metadata.actionType),+ };+ editor.dispatchCommand(INSERT_ACTION_TAG_COMMAND, payload);} else {editor.dispatchCommand(INSERT_MENTION_COMMAND, {label: String(option.label),diff --git a/src/features/ChatInput/InputEditor/useMentionCategories.tsx b/src/features/ChatInput/InputEditor/useMentionCategories.tsxindex e2174e7892c..e14d9c9d34d 100644--- a/src/features/ChatInput/InputEditor/useMentionCategories.tsx+++ b/src/features/ChatInput/InputEditor/useMentionCategories.tsx@@ -1,6 +1,7 @@import { Avatar, Icon } from '@lobehub/ui';-import { Bot, MessageSquareText, Users } from 'lucide-react';-import { useMemo } from 'react';+import { SkillsIcon } from '@lobehub/ui/icons';+import { Bot, MessageSquareText, Users, Wrench } from 'lucide-react';+import { createElement, useMemo } from 'react';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';@@ -11,12 +12,34 @@ import { homeAgentListSelectors } from '@/store/home/selectors';import { useAgentId } from '../hooks/useAgentId';import { useChatInputStore } from '../store';+import { useInstalledSkillsAndTools } from './ActionTag/useInstalledSkillsAndTools';import type { MentionCategory } from './MentionMenu/types';const MAX_AGENT_ITEMS = 20;const MAX_TOPIC_LABEL = 50;type MenuOptionWithMetadata = { key: string; metadata?: Record<string, unknown> };+/** Render a skill/tool avatar as a ReactNode icon. */+const shouldRenderIconAsImage = (str: string) =>+ str.startsWith('http://') ||+ str.startsWith('https://') ||+ str.startsWith('blob:') ||+ /^data:image\//i.test(str);++const renderAvatar = (avatar: string | undefined): React.ReactNode => {+ if (!avatar) return <Icon icon={SkillsIcon} size={16} />;+ if (shouldRenderIconAsImage(avatar)) {+ return createElement('img', {+ alt: '',+ height: 16,+ src: avatar,+ style: { flexShrink: 0, objectFit: 'contain' as const },+ width: 16,+ });+ }+ return createElement('span', { style: { fontSize: 16, lineHeight: 1 } }, avatar);+};+export const useMentionCategories = (): MentionCategory[] => {const currentAgentId = useAgentId();const allAgents = useHomeStore(homeAgentListSelectors.allAgents);@@ -32,6 +55,8 @@ export const useMentionCategories = (): MentionCategory[] => {const externalMentionItems = useChatInputStore((s) => s.mentionItems);const isGroupChat = !!externalMentionItems;+ const enabledSkills = useInstalledSkillsAndTools();+return useMemo(() => {const categories: MentionCategory[] = [];@@ -117,6 +142,56 @@ export const useMentionCategories = (): MentionCategory[] => {}}+ // --- Skills ---+ const skillItems = enabledSkills.filter((s) => s.category === 'skill');+ if (skillItems.length > 0) {+ categories.push({+ id: 'skill',+ icon: <Icon icon={SkillsIcon} size={16} />,+ items: skillItems.map((item) => ({+ icon: renderAvatar(item.icon),+ key: `skill-${item.type}`,+ label: item.label,+ metadata: {+ actionCategory: item.category,+ actionType: item.type,+ timestamp: 0,+ type: 'skill' as const,+ },+ })),+ label: 'Skills',+ });+ }++ // --- Tools ---+ const toolItems = enabledSkills.filter((s) => s.category === 'tool');+ if (toolItems.length > 0) {+ categories.push({+ id: 'tool',+ icon: <Icon icon={Wrench} size={16} />,+ items: toolItems.map((item) => ({+ icon: renderAvatar(item.icon),+ key: `tool-${item.type}`,+ label: item.label,+ metadata: {+ actionCategory: item.category,+ actionType: item.type,+ timestamp: 0,+ type: 'tool' as const,+ },+ })),+ label: 'Tools',+ });+ }+return categories;- }, [allAgents, currentAgentId, topics, activeTopicId, isGroupChat, externalMentionItems]);+ }, [+ allAgents,+ currentAgentId,+ topics,+ activeTopicId,+ isGroupChat,+ externalMentionItems,+ enabledSkills,+ ]);};diff --git a/src/features/CommandMenu/AskAIMenu.tsx b/src/features/CommandMenu/AskAIMenu.tsxindex 6de822a31d7..0862a898aa4 100644--- a/src/features/CommandMenu/AskAIMenu.tsx+++ b/src/features/CommandMenu/AskAIMenu.tsx@@ -34,7 +34,7 @@ const AskAIMenu = memo(() => {closeCommandMenu(); // Close immediatelyif (trimmedSearch) {// Use sendAsAgent to create a blank agent and open agent builder- useHomeStore.getState().sendAsAgent(trimmedSearch);+ useHomeStore.getState().sendAsAgent({ message: trimmedSearch });}};@@ -43,7 +43,7 @@ const AskAIMenu = memo(() => {closeCommandMenu(); // Close immediatelyif (trimmedSearch) {// Use sendAsGroup to create a blank group and open group builder- useHomeStore.getState().sendAsGroup(trimmedSearch);+ useHomeStore.getState().sendAsGroup({ message: trimmedSearch });}};diff --git a/src/routes/(main)/home/features/InputArea/useSend.ts b/src/routes/(main)/home/features/InputArea/useSend.tsindex 92cda00e9a7..981b8d611e9 100644--- a/src/routes/(main)/home/features/InputArea/useSend.ts+++ b/src/routes/(main)/home/features/InputArea/useSend.ts@@ -1,6 +1,7 @@import { SESSION_CHAT_URL } from '@lobechat/const';import { useCallback } from 'react';+import type { SendButtonHandler } from '@/features/ChatInput/store/initialState';import { useQueryRoute } from '@/hooks/useQueryRoute';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';@@ -17,59 +18,64 @@ export const useSend = () => {const homeInputLoading = useHomeStore((s) => s.homeInputLoading);- const send = useCallback(async () => {- const { inputMessage, mainInputEditor } = useChatStore.getState();- const fileList = fileChatSelectors.chatUploadFileList(useFileStore.getState());- const contextList = fileChatSelectors.chatContextSelections(useFileStore.getState());- const { sendAsAgent, sendAsGroup, sendAsWrite, sendAsResearch, inputActiveMode } =- useHomeStore.getState();+ const send = useCallback<SendButtonHandler>(+ async ({ getEditorData }) => {+ const { inputMessage, mainInputEditor } = useChatStore.getState();+ const editorData = getEditorData?.() ?? mainInputEditor?.getJSONState();+ const fileList = fileChatSelectors.chatUploadFileList(useFileStore.getState());+ const contextList = fileChatSelectors.chatContextSelections(useFileStore.getState());+ const { sendAsAgent, sendAsGroup, sendAsWrite, sendAsResearch, inputActiveMode } =+ useHomeStore.getState();- // Require input content (except for default inbox which can have files/context)- if (!inputMessage && fileList.length === 0 && contextList.length === 0) return;+ // Require input content (except for default inbox which can have files/context)+ if (!inputMessage && fileList.length === 0 && contextList.length === 0) return;- try {- switch (inputActiveMode) {- case 'agent': {- await sendAsAgent(inputMessage);- break;- }+ try {+ switch (inputActiveMode) {+ case 'agent': {+ await sendAsAgent({ editorData, message: inputMessage });+ break;+ }- case 'group': {- await sendAsGroup(inputMessage);- break;- }+ case 'group': {+ await sendAsGroup({ editorData, message: inputMessage });+ break;+ }- case 'write': {- await sendAsWrite(inputMessage);- break;- }+ case 'write': {+ await sendAsWrite({ editorData, message: inputMessage });+ break;+ }- case 'research': {- await sendAsResearch(inputMessage);- break;- }+ case 'research': {+ await sendAsResearch(inputMessage);+ break;+ }- default: {- // Default inbox behavior- if (!inboxAgentId) return;+ default: {+ // Default inbox behavior+ if (!inboxAgentId) return;- sendMessage({- context: { agentId: inboxAgentId },- contexts: contextList,- files: fileList,- message: inputMessage,- });+ sendMessage({+ context: { agentId: inboxAgentId },+ contexts: contextList,+ editorData,+ files: fileList,+ message: inputMessage,+ });- router.push(SESSION_CHAT_URL(inboxAgentId, false));+ router.push(SESSION_CHAT_URL(inboxAgentId, false));+ }}+ } finally {+ // Clear input and files after send+ clearChatUploadFileList();+ clearChatContextSelections();+ mainInputEditor?.clearContent();}- } finally {- // Clear input and files after send- clearChatUploadFileList();- clearChatContextSelections();- mainInputEditor?.clearContent();- }- }, [inboxAgentId, sendMessage, clearChatContextSelections, clearChatUploadFileList, router]);+ },+ [inboxAgentId, sendMessage, clearChatContextSelections, clearChatUploadFileList, router],+ );return {inboxAgentId,diff --git a/src/services/chat/chat.test.ts b/src/services/chat/chat.test.tsindex 2ddac410bb8..fdb5bca25a5 100644--- a/src/services/chat/chat.test.ts+++ b/src/services/chat/chat.test.ts@@ -997,35 +997,39 @@ describe('ChatService', () => {}),});- expect(getChatCompletionSpy).toHaveBeenCalledWith(- {+ const [requestPayload, requestContext] = getChatCompletionSpy.mock.calls[0]!;++ expect(requestPayload).toEqual(+ expect.objectContaining({enabledSearch: undefined,model: 'gpt-3.5-turbo-1106',stream: true,+ tools: seoTools,top_p: 1,- tools: [- {- type: 'function',- function: {- description: 'Get data from users',- name: 'seo____getData',- parameters: {- properties: { keyword: { type: 'string' }, url: { type: 'string' } },- required: ['keyword', 'url'],- type: 'object',- },- },- },- ],- messages: [- {- content: expect.stringContaining(getCurrentDateContent()),- role: 'system',- },- { content: 'https://vercel.com/ 请分析 chatGPT 关键词', role: 'user' },- ],- },- expect.anything(),+ }),+ );+ expect(requestPayload.messages).toBeDefined();+ const requestMessages = requestPayload.messages!;++ expect(requestMessages[0]).toEqual(+ expect.objectContaining({+ content: expect.stringContaining(getCurrentDateContent()),+ role: 'system',+ }),+ );+ expect(requestMessages[0].content).toContain('<available_skills>');+ expect(requestMessages[0].content).toContain(+ 'Use the runSkill tool to activate a skill when needed.',+ );+ expect(requestMessages[0].content).toContain('<tool name="SEO">');+ expect(requestMessages[1]).toEqual(+ expect.objectContaining({+ content: expect.stringContaining('https://vercel.com/ 请分析 chatGPT 关键词'),+ role: 'user',+ }),+ );+ expect(requestContext).toEqual(+ expect.objectContaining({ agentId: '', topicId: undefined }),);});@@ -1142,35 +1146,36 @@ describe('ChatService', () => {}),});- expect(getChatCompletionSpy).toHaveBeenCalledWith(- {+ const [requestPayload, requestContext] = getChatCompletionSpy.mock.calls[0]!;++ expect(requestPayload).toEqual(+ expect.objectContaining({enabledSearch: undefined,model: 'gpt-3.5-turbo-1106',stream: true,+ tools: seoTools,top_p: 1,- tools: [- {- type: 'function',- function: {- description: 'Get data from users',- name: 'seo____getData',- parameters: {- properties: { keyword: { type: 'string' }, url: { type: 'string' } },- required: ['keyword', 'url'],- type: 'object',- },- },- },- ],- messages: [- {- content: expect.stringContaining('system\n\n' + getCurrentDateContent()),- role: 'system',- },- { content: 'https://vercel.com/ 请分析 chatGPT 关键词', role: 'user' },- ],- },- expect.anything(),+ }),+ );+ expect(requestPayload.messages).toBeDefined();+ const requestMessages = requestPayload.messages!;++ expect(requestMessages[0]).toEqual(+ expect.objectContaining({+ content: expect.stringContaining('system\n\n' + getCurrentDateContent()),+ role: 'system',+ }),+ );+ expect(requestMessages[0].content).toContain('<available_skills>');+ expect(requestMessages[0].content).toContain('<tool name="SEO">');+ expect(requestMessages[1]).toEqual(+ expect.objectContaining({+ content: expect.stringContaining('https://vercel.com/ 请分析 chatGPT 关键词'),+ role: 'user',+ }),+ );+ expect(requestContext).toEqual(+ expect.objectContaining({ agentId: '', topicId: undefined }),);});@@ -1193,22 +1198,36 @@ describe('ChatService', () => {}),});- expect(getChatCompletionSpy).toHaveBeenCalledWith(- {+ const [requestPayload, requestContext] = getChatCompletionSpy.mock.calls[0]!;++ expect(requestPayload).toEqual(+ expect.objectContaining({enabledSearch: undefined,model: 'gpt-3.5-turbo-1106',stream: true,tools: undefined,top_p: 1,- messages: [- {- content: expect.stringContaining('system\n\n' + getCurrentDateContent()),- role: 'system',- },- { content: 'https://vercel.com/ 请分析 chatGPT 关键词', role: 'user' },- ],- },- expect.anything(),+ }),+ );+ expect(requestPayload.messages).toBeDefined();+ const requestMessages = requestPayload.messages!;++ expect(requestMessages[0]).toEqual(+ expect.objectContaining({+ content: expect.stringContaining('system\n\n' + getCurrentDateContent()),+ role: 'system',+ }),+ );+ expect(requestMessages[0].content).toContain('<available_skills>');+ expect(requestMessages[0].content).not.toContain('<tool name="SEO">');+ expect(requestMessages[1]).toEqual(+ expect.objectContaining({+ content: expect.stringContaining('https://vercel.com/ 请分析 chatGPT 关键词'),+ role: 'user',+ }),+ );+ expect(requestContext).toEqual(+ expect.objectContaining({ agentId: '', topicId: undefined }),);});});diff --git a/src/services/chat/mecha/contextEngineering.test.ts b/src/services/chat/mecha/contextEngineering.test.tsindex eae5aa7b5cb..e74fb9ace34 100644--- a/src/services/chat/mecha/contextEngineering.test.ts+++ b/src/services/chat/mecha/contextEngineering.test.ts@@ -351,14 +351,14 @@ describe('contextEngineering', () => {expect(Object.keys(systemMessage!).length).toEqual(2);});- it('should strip raw action tags from user messages before sending to model', async () => {+ it('should preserve normalized skill and tool tags in user messages before sending to model', async () => {vi.spyOn(isCanUseFCModule, 'isCanUseFC').mockReturnValue(true);const messages: UIChatMessage[] = [{role: 'user',content:- '<action type="grep" category="skill" /> <action type="lobe-notebook" category="tool" /> hi',+ '<skill name="grep" label="Grep" /> <tool name="lobe-notebook" label="Notebook" /> hi',createdAt: Date.now(),id: 'selected-skill-user',updatedAt: Date.now(),@@ -377,8 +377,8 @@ describe('contextEngineering', () => {});expect(result[1].role).toBe('user');expect(result[1].content).toContain('hi');- expect(result[1].content).not.toContain('<action type="grep" category="skill" />');- expect(result[1].content).not.toContain('<action type="lobe-notebook" category="tool" />');+ expect(result[1].content).toContain('<skill name="grep" label="Grep" />');+ expect(result[1].content).toContain('<tool name="lobe-notebook" label="Notebook" />');});describe('getAssistantContent', () => {diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.tsindex df23cdccb5d..371eac86450 100644--- a/src/services/chat/mecha/contextEngineering.ts+++ b/src/services/chat/mecha/contextEngineering.ts@@ -50,7 +50,6 @@ import {import { isCanUseVideo, isCanUseVision } from '../helper';import { combineUserMemoryData, resolveTopicMemories, resolveUserPersona } from './memoryManager';import { resolveClientSkills } from './skillEngineering';-import { stripActionTagsFromText } from './skillPreload';const log = debug('context-engine:contextEngineering');@@ -93,39 +92,6 @@ interface ContextEngineeringContext {topicId?: string;}-type TextContentPart = {- text?: string;- type?: string;- [key: string]: unknown;-};--const preprocessActionTags = (messages: UIChatMessage[]): UIChatMessage[] =>- messages.map((message) => {- if (message.role !== 'user') return message;-- if (typeof message.content === 'string') {- return {- ...message,- content: stripActionTagsFromText(message.content),- };- }-- if (Array.isArray(message.content)) {- const contentParts = message.content as TextContentPart[];-- return {- ...message,- content: contentParts.map((part) =>- part?.type === 'text' && typeof part.text === 'string'- ? { ...part, text: stripActionTagsFromText(part.text) }- : part,- ),- } as unknown as UIChatMessage;- }-- return message;- });-// REVIEW: Maybe we can constrain identity, preference, exp to reorder or trim the context instead of passing everything inexport const contextEngineering = async ({messages = [],@@ -149,8 +115,6 @@ export const contextEngineering = async ({topicId,memoryContext,}: ContextEngineeringContext): Promise<OpenAIChatMessage[]> => {- messages = preprocessActionTags(messages);-log('tools: %o', tools);// Check if Agent Builder tool is enabled@@ -600,6 +564,10 @@ export const contextEngineering = async ({initialContext,stepContext,+ // Selected skills/tools from user for this request+ selectedSkills: initialContext?.selectedSkills,+ selectedTools: initialContext?.selectedTools,+// Skills configuration — expose all installed skills so the AI can discover and activate themskillsConfig: {enabledSkills: plugins ? resolveClientSkills(plugins).skills : undefined,diff --git a/src/services/chat/mecha/skillPreload.test.ts b/src/services/chat/mecha/skillPreload.test.tsdeleted file mode 100644index 56ac55fc17b..00000000000--- a/src/services/chat/mecha/skillPreload.test.ts+++ /dev/null@@ -1,58 +0,0 @@-import { describe, expect, it, vi } from 'vitest';--import * as toolStoreModule from '@/store/tool';--import { prepareSelectedSkillPreload } from './skillPreload';--describe('prepareSelectedSkillPreload', () => {- it('should sanitize skill action tags and build persisted preload messages', async () => {- vi.spyOn(toolStoreModule, 'getToolStoreState').mockReturnValue({- agentSkillDetailMap: {},- agentSkills: [],- builtinSkills: [- {- content: 'Use grep to search the codebase.',- description: 'Search code with ripgrep',- identifier: 'grep',- name: 'Grep',- source: 'builtin',- },- ],- } as any);-- const result = await prepareSelectedSkillPreload({- message: '<action type="grep" category="skill" /> hi',- selectedSkills: [{ identifier: 'grep', name: 'Grep' }],- });-- expect(result).toHaveLength(2);- expect(result[0]).toEqual(- expect.objectContaining({- content: '',- role: 'assistant',- tools: [- expect.objectContaining({- apiName: 'activateSkill',- arguments: JSON.stringify({ name: 'Grep' }),- id: expect.any(String),- identifier: 'lobe-activator',- type: 'builtin',- }),- ],- }),- );- expect(result[1]).toEqual(- expect.objectContaining({- content: 'Use grep to search the codebase.',- plugin: expect.objectContaining({- apiName: 'activateSkill',- arguments: JSON.stringify({ name: 'Grep' }),- identifier: 'lobe-activator',- type: 'builtin',- }),- role: 'tool',- tool_call_id: result[0].tools?.[0].id,- }),- );- });-});diff --git a/src/services/chat/mecha/skillPreload.ts b/src/services/chat/mecha/skillPreload.tsindex 42daf242679..0d41c734664 100644--- a/src/services/chat/mecha/skillPreload.ts+++ b/src/services/chat/mecha/skillPreload.ts@@ -1,4 +1,3 @@-import { ActivatorApiName, LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';import {CredsIdentifier,type CredSummary,@@ -6,8 +5,7 @@ import {type UserCredsContext,} from '@lobechat/builtin-tool-creds';import { resourcesTreePrompt } from '@lobechat/prompts';-import type { RuntimeSelectedSkill, SendPreloadMessage, UserCredSummary } from '@lobechat/types';-import { nanoid } from '@lobechat/utils';+import type { RuntimeSelectedSkill, UserCredSummary } from '@lobechat/types';import { agentSkillService } from '@/services/skill';import { getToolStoreState } from '@/store/tool';@@ -27,42 +25,38 @@ interface PrepareSelectedSkillPreloadParams {userCreds?: UserCredSummary[];}-const ACTION_TAG_REGEX = /<action\b([^>]*)\/>/g;+// Match <skill name="..." label="..." /> and legacy <action type="..." category="skill" ... />+const SKILL_TAG_REGEX = /<skill\b([^>]*)\/>/g;+const LEGACY_ACTION_TAG_REGEX = /<action\b([^>]*)\/>/g;-const getActionAttr = (attrs: string, name: string): string | undefined => {+const getAttr = (attrs: string, name: string): string | undefined => {const match = new RegExp(`${name}="([^"]*)"`, 'i').exec(attrs);return match?.[1];};-const cleanupWhitespace = (text: string) =>- text- .replaceAll(/[ \t]{2,}/g, ' ')- .replaceAll(/\n{3,}/g, '\n\n')- .trim();-const extractSelectedSkillsFromText = (text: string): RuntimeSelectedSkill[] => {const parsedSkills: RuntimeSelectedSkill[] = [];- for (const match of text.matchAll(ACTION_TAG_REGEX)) {+ // New format: <skill name="..." label="..." />+ for (const match of text.matchAll(SKILL_TAG_REGEX)) {const attrs = match[1] || '';- if (getActionAttr(attrs, 'category') !== 'skill') continue;-- const identifier = getActionAttr(attrs, 'type');-+ const identifier = getAttr(attrs, 'name');if (!identifier) continue;+ parsedSkills.push({ identifier, name: getAttr(attrs, 'label') || identifier });+ }- parsedSkills.push({- identifier,- name: getActionAttr(attrs, 'label') || identifier,- });+ // Legacy format: <action type="..." category="skill" label="..." />+ for (const match of text.matchAll(LEGACY_ACTION_TAG_REGEX)) {+ const attrs = match[1] || '';+ if (getAttr(attrs, 'category') !== 'skill') continue;+ const identifier = getAttr(attrs, 'type');+ if (!identifier) continue;+ parsedSkills.push({ identifier, name: getAttr(attrs, 'label') || identifier });}return parsedSkills;};-export const stripActionTagsFromText = (text: string) =>- cleanupWhitespace(text.replaceAll(ACTION_TAG_REGEX, ''));-const resolveSelectedSkills = (message: string,selectedSkills?: RuntimeSelectedSkill[],@@ -146,55 +140,27 @@ const loadSkillContent = async (};};-const buildPersistedPreloadMessages = (skills: PreloadedSkill[]): SendPreloadMessage[] =>- skills.flatMap((skill, index) => {- const toolCallId = `selected_skill_${index}_${nanoid()}`;- const args = JSON.stringify({ name: skill.name });-- return [- {- content: '',- role: 'assistant',- tools: [- {- apiName: ActivatorApiName.activateSkill,- arguments: args,- id: toolCallId,- identifier: LobeActivatorIdentifier,- type: 'builtin',- },- ],- },- {- content: skill.content,- plugin: {- apiName: ActivatorApiName.activateSkill,- arguments: args,- identifier: LobeActivatorIdentifier,- type: 'builtin',- },- role: 'tool',- tool_call_id: toolCallId,- },- ];- });--export const prepareSelectedSkillPreload = async ({+/**+ * Enrich selected skills with preloaded content from skill store.+ * Skills with available content get it attached directly, enabling+ * SelectedSkillInjector to inline the content into the user message+ * instead of constructing fake activateSkill tool-call preload messages.+ */+export const resolveSelectedSkillsWithContent = async ({message,selectedSkills,userCreds,-}: PrepareSelectedSkillPreloadParams): Promise<SendPreloadMessage[]> => {- const resolvedSelectedSkills = resolveSelectedSkills(message, selectedSkills);+}: PrepareSelectedSkillPreloadParams): Promise<RuntimeSelectedSkill[]> => {+ const resolved = resolveSelectedSkills(message, selectedSkills);- if (resolvedSelectedSkills.length === 0) {- return [];- }+ if (resolved.length === 0) return [];- const resolvedSkills = (- await Promise.all(- resolvedSelectedSkills.map((selectedSkill) => loadSkillContent(selectedSkill, userCreds)),- )- ).filter((skill): skill is PreloadedSkill => !!skill);+ const enriched = await Promise.all(+ resolved.map(async (skill) => {+ const loaded = await loadSkillContent(skill, userCreds);+ return loaded ? { ...skill, content: loaded.content } : skill;+ }),+ );- return buildPersistedPreloadMessages(resolvedSkills);+ return enriched;};diff --git a/src/services/chat/mecha/toolPreload.ts b/src/services/chat/mecha/toolPreload.tsnew file mode 100644index 00000000000..a8e31844e98--- /dev/null+++ b/src/services/chat/mecha/toolPreload.ts@@ -0,0 +1,126 @@+import type { RuntimeSelectedTool } from '@lobechat/types';++import { getToolStoreState } from '@/store/tool';++// Match <tool name="..." label="..." /> and legacy <action type="..." category="tool" ... />+const TOOL_TAG_REGEX = /<tool\b([^>]*)\/>/g;+const LEGACY_ACTION_TAG_REGEX = /<action\b([^>]*)\/>/g;++const getAttr = (attrs: string, name: string): string | undefined => {+ const match = new RegExp(`${name}="([^"]*)"`, 'i').exec(attrs);+ return match?.[1];+};++export const extractSelectedToolsFromText = (text: string): RuntimeSelectedTool[] => {+ const parsedTools: RuntimeSelectedTool[] = [];++ // New format: <tool name="..." label="..." />+ for (const match of text.matchAll(TOOL_TAG_REGEX)) {+ const attrs = match[1] || '';+ const identifier = getAttr(attrs, 'name');+ if (!identifier) continue;+ parsedTools.push({ identifier, name: getAttr(attrs, 'label') || identifier });+ }++ // Legacy format: <action type="..." category="tool" label="..." />+ for (const match of text.matchAll(LEGACY_ACTION_TAG_REGEX)) {+ const attrs = match[1] || '';+ if (getAttr(attrs, 'category') !== 'tool') continue;+ const identifier = getAttr(attrs, 'type');+ if (!identifier) continue;+ parsedTools.push({ identifier, name: getAttr(attrs, 'label') || identifier });+ }++ return parsedTools;+};++const resolveSelectedTools = (+ message: string,+ selectedTools?: RuntimeSelectedTool[],+): RuntimeSelectedTool[] => {+ const merged = [...(selectedTools || []), ...extractSelectedToolsFromText(message)];+ const seen = new Set<string>();++ return merged.reduce<RuntimeSelectedTool[]>((acc, tool) => {+ if (!tool.identifier || seen.has(tool.identifier)) return acc;+ seen.add(tool.identifier);+ acc.push(tool);+ return acc;+ }, []);+};++/**+ * Resolve tool manifest content for a single tool.+ * Returns the tool's systemRole + API descriptions as a formatted string.+ */+const loadToolContent = (identifier: string): string | undefined => {+ const toolState = getToolStoreState();++ const builtinTool = (toolState.builtinTools || []).find(+ (t) => t.manifest?.identifier === identifier,+ );++ if (builtinTool?.manifest) {+ const { manifest } = builtinTool;+ const parts: string[] = [];++ if (manifest.systemRole) {+ parts.push(manifest.systemRole);+ }++ if (manifest.api?.length > 0) {+ const apiDescriptions = manifest.api+ .map((api) => `- ${api.name}: ${api.description}`)+ .join('\n');+ parts.push(`Available APIs:\n${apiDescriptions}`);+ }++ const content = parts.join('\n\n');+ return content || undefined;+ }++ const installedPlugin = (toolState.installedPlugins || []).find(+ (p) => p.identifier === identifier,+ );++ if (installedPlugin?.manifest) {+ const { manifest } = installedPlugin;+ const parts: string[] = [];++ if (manifest.systemRole) {+ parts.push(manifest.systemRole);+ }++ if (manifest.api?.length > 0) {+ const apiDescriptions = manifest.api+ .map((api) => `- ${api.name}: ${api.description}`)+ .join('\n');+ parts.push(`Available APIs:\n${apiDescriptions}`);+ }++ const content = parts.join('\n\n');+ return content || undefined;+ }++ return undefined;+};++/**+ * Enrich selected tools with preloaded content from tool manifests.+ * Tools with available manifest data (systemRole, API descriptions) get their+ * content resolved and attached directly, avoiding fake tool-call preload messages.+ */+export const resolveSelectedToolsWithContent = ({+ message,+ selectedTools,+}: {+ message: string;+ selectedTools?: RuntimeSelectedTool[];+}): RuntimeSelectedTool[] => {+ const resolved = resolveSelectedTools(message, selectedTools);++ return resolved.map((tool) => {+ const content = loadToolContent(tool.identifier);+ return content ? { ...tool, content } : tool;+ });+};diff --git a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.tsindex 9cce41ca888..67b7abecd22 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts@@ -293,7 +293,7 @@ describe('ConversationLifecycle actions', () => {expect(result.current.internal_execAgentRuntime).toHaveBeenCalled();});- it('should persist selected slash skills as preload messages before sending', async () => {+ it('should persist selected slash skills into user message content before sending', async () => {const { result } = renderHook(() => useChatStore());const sendMessageInServerSpy = vi@@ -303,7 +303,7 @@ describe('ConversationLifecycle actions', () => {createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),],- topics: [],+ topics: undefined,assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,userMessageId: TEST_IDS.USER_MESSAGE_ID,} as any);@@ -359,54 +359,27 @@ describe('ConversationLifecycle actions', () => {});});- expect(sendMessageInServerSpy).toHaveBeenCalledWith(+ const requestPayload = sendMessageInServerSpy.mock.calls[0]?.[0];++ expect(requestPayload?.newUserMessage).toEqual(expect.objectContaining({- newUserMessage: expect.objectContaining({- content:- '<action type="user_memory" category="skill" /> ' + TEST_CONTENT.USER_MESSAGE,- editorData: expect.objectContaining({- root: expect.any(Object),- }),+ content: expect.stringContaining(TEST_CONTENT.USER_MESSAGE),+ editorData: expect.objectContaining({+ root: expect.any(Object),}),- preloadMessages: [- expect.objectContaining({- content: '',- role: 'assistant',- tools: [- expect.objectContaining({- apiName: 'activateSkill',- arguments: JSON.stringify({ name: 'User Memory' }),- identifier: 'lobe-activator',- }),- ],- }),- expect.objectContaining({- content: 'Use the user memory skill content.',- role: 'tool',- }),- expect.objectContaining({- content: '',- role: 'assistant',- tools: [- expect.objectContaining({- apiName: 'activateSkill',- arguments: JSON.stringify({ name: 'Instruction' }),- identifier: 'lobe-activator',- }),- ],- }),- expect.objectContaining({- content: 'Use the instruction skill content.',- role: 'tool',- }),- ],}),- expect.any(AbortController),);- expect(- sendMessageInServerSpy.mock.calls[0]?.[0].newUserMessage.editorData?.root.children[0]- .children,- ).toEqual(+ expect(requestPayload?.newUserMessage.content).toContain('<selected_skill_context>');+ expect(requestPayload?.newUserMessage.content).toContain('identifier="user_memory"');+ expect(requestPayload?.newUserMessage.content).toContain('identifier="instruction"');+ expect(requestPayload?.newUserMessage.content).toContain(+ 'Use the user memory skill content.',+ );+ expect(requestPayload?.newUserMessage.content).toContain(+ 'Use the instruction skill content.',+ );+ expect(requestPayload?.preloadMessages).toBeUndefined();+ expect(requestPayload?.newUserMessage.editorData?.root.children[0].children).toEqual(expect.arrayContaining([expect.objectContaining({actionCategory: 'skill',@@ -415,19 +388,7 @@ describe('ConversationLifecycle actions', () => {}),]),);- expect(result.current.internal_execAgentRuntime).toHaveBeenCalledWith(- expect.objectContaining({- initialContext: expect.objectContaining({- initialContext: {- selectedSkills: [- { identifier: 'user_memory', name: 'User Memory' },- { identifier: 'instruction', name: 'Instruction' },- ],- },- phase: 'init',- }),- }),- );+ expect(result.current.internal_execAgentRuntime).toHaveBeenCalled();});it('should work when sending from home page (activeAgentId is empty but context.agentId exists)', async () => {@@ -475,18 +436,20 @@ describe('ConversationLifecycle actions', () => {expect(result.current.internal_execAgentRuntime).toHaveBeenCalled();});- it('should pass selected tool tags into runtime initialContext', async () => {+ it('should persist selected tool tags into user message content before runtime execution', 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);+ const sendMessageInServerSpy = 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: undefined,+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);await act(async () => {await result.current.sendMessage({@@ -519,18 +482,76 @@ describe('ConversationLifecycle actions', () => {});});- expect(result.current.internal_execAgentRuntime).toHaveBeenCalledWith(- expect.objectContaining({- initialContext: expect.objectContaining({- initialContext: {- selectedTools: [- { identifier: 'lobe-notebook', name: 'Notebook' },- { identifier: 'lobe-artifacts', name: 'Artifacts' },+ const requestPayload = sendMessageInServerSpy.mock.calls[0]?.[0];++ expect(requestPayload?.newUserMessage.content).toContain(TEST_CONTENT.USER_MESSAGE);+ expect(requestPayload?.newUserMessage.content).toContain('<selected_tool_context>');+ expect(requestPayload?.newUserMessage.content).toContain('identifier="lobe-notebook"');+ expect(requestPayload?.newUserMessage.content).toContain('name="Notebook"');+ expect(requestPayload?.newUserMessage.content).toContain('identifier="lobe-artifacts"');+ expect(requestPayload?.newUserMessage.content).toContain('name="Artifacts"');+ expect(result.current.internal_execAgentRuntime).toHaveBeenCalled();+ });++ it('should preserve editorData when enqueueing a queued message', async () => {+ const { result } = renderHook(() => useChatStore());+ const context = createTestContext();+ const contextKey = messageMapKey(context);+ const editorData = {+ root: {+ children: [+ {+ children: [+ {+ actionCategory: 'tool',+ actionLabel: 'Notebook',+ actionType: 'lobe-notebook',+ type: 'action-tag',+ },+ { text: ' queued message', type: 'text' },],+ type: 'paragraph',},- phase: 'init',- }),+ ],+ type: 'root',+ },+ };++ act(() => {+ useChatStore.setState({+ operations: {+ 'op-running': {+ childOperationIds: [],+ context,+ id: 'op-running',+ metadata: {},+ status: 'running',+ type: 'execAgentRuntime',+ },+ } as any,+ operationsByContext: {+ [contextKey]: ['op-running'],+ },+ });+ });++ const enqueueMessageSpy = vi.spyOn(result.current, 'enqueueMessage');++ await act(async () => {+ await result.current.sendMessage({+ context,+ editorData: editorData as any,+ message: 'queued message',+ });+ });++ expect(enqueueMessageSpy).toHaveBeenCalledWith(+ contextKey,+ expect.objectContaining({+ content: 'queued message',+ editorData,}),+ 'op-running',);});});diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.tsindex 86ea6cb8b8f..80d7e7a6276 100644--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts@@ -1,7 +1,8 @@// Disable the auto sort key eslint rule to make the code more logic and readable-import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';+import { createCallAgentManifest } from '@lobechat/builtin-tool-agent-management';import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';import { LOADING_FLAT } from '@lobechat/const';+import { formatSelectedSkillsContext, formatSelectedToolsContext } from '@lobechat/context-engine';import { chainCompressContext } from '@lobechat/prompts';import {type ChatImageItem,@@ -18,7 +19,8 @@ import { t } from 'i18next';import { markUserValidAction } from '@/business/client/markUserValidAction';import { aiChatService } from '@/services/aiChat';import { chatService } from '@/services/chat';-import { prepareSelectedSkillPreload } from '@/services/chat/mecha/skillPreload';+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 { agentSelectors } from '@/store/agent/selectors';@@ -196,10 +198,17 @@ export class ConversationLifecycleActionImpl {};const fileIdList = files?.map((f) => f.id);- const preloadMessages = await prepareSelectedSkillPreload({++ // Enrich selected skills/tools with preloaded content, injected directly+ // via SelectedSkillInjector/SelectedToolInjector — no fake tool-call preload messages+ const enrichedSelectedSkills = await resolveSelectedSkillsWithContent({message,selectedSkills,});+ const enrichedSelectedTools = resolveSelectedToolsWithContent({+ message,+ selectedTools,+ });const hasFile = !!fileIdList && fileIdList.length > 0;@@ -221,6 +230,7 @@ export class ConversationLifecycleActionImpl {{id: nanoid(),content: message,+ editorData: editorData ?? undefined,files: fileIdList,interruptMode: 'soft',createdAt: Date.now(),@@ -337,16 +347,43 @@ export class ConversationLifecycleActionImpl {const { model, provider } = agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());const topicId = operationContext.topicId;++ // Persist selected skill/tool context into user message content so it survives across turns.+ // Deduplicate: skip skills/tools already @mentioned in earlier messages (via editorData).+ const previouslyMentionedSkills = new Set<string>();+ const previouslyMentionedTools = new Set<string>();++ for (const m of messages) {+ if (m.role !== 'user') continue;+ for (const s of parseSelectedSkillsFromEditorData(m.editorData ?? undefined)) {+ previouslyMentionedSkills.add(s.identifier);+ }+ for (const t of parseSelectedToolsFromEditorData(m.editorData ?? undefined)) {+ previouslyMentionedTools.add(t.identifier);+ }+ }+ const dedupedSkills = enrichedSelectedSkills.filter(+ (s) => !previouslyMentionedSkills.has(s.identifier),+ );+ const dedupedTools = enrichedSelectedTools.filter(+ (t) => !previouslyMentionedTools.has(t.identifier),+ );++ const skillContext = formatSelectedSkillsContext(dedupedSkills);+ const toolContext = formatSelectedToolsContext(dedupedTools);+ const contextSuffix = [skillContext, toolContext].filter(Boolean).join('\n');+ const persistedContent = contextSuffix ? `${message}\n\n${contextSuffix}` : message;+data = await aiChatService.sendMessageInServer({newUserMessage: {- content: message,+ content: persistedContent,editorData,files: fileIdList,pageSelections,parentId,},- preloadMessages: preloadMessages.length > 0 ? preloadMessages : undefined,+ preloadMessages: undefined,// if there is topicId,then add topicId to messagetopicId: topicId ?? undefined,threadId: operationContext.threadId ?? undefined,@@ -556,30 +593,22 @@ export class ConversationLifecycleActionImpl {)(this.#get());try {- // When agents are @mentioned in non-group context, auto-enable agent-management tool- // so the supervisor can delegate via callAgent- const effectiveSelectedTools =- hasMentionedAgents &&- !selectedTools.some((t) => t.identifier === AgentManagementIdentifier)- ? [- ...selectedTools,- { identifier: AgentManagementIdentifier, name: 'Agent Management' },- ]- : selectedTools;-- const hasInitialContext =- effectiveSelectedTools.length > 0 || selectedSkills.length > 0 || hasMentionedAgents;+ // 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 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: {- ...(selectedSkills.length > 0 ? { selectedSkills } : undefined),- ...(effectiveSelectedTools.length > 0- ? { selectedTools: effectiveSelectedTools }- : undefined),// 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,}diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.tsindex 1d17b0dac80..e4a7027f713 100644--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts@@ -10,7 +10,7 @@ import { createPathScopeAudit } from '@lobechat/builtin-tool-local-system';import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';import { manualModeExcludeToolIds } from '@lobechat/builtin-tools';import { isDesktop } from '@lobechat/const';-import { type ToolsEngine } from '@lobechat/context-engine';+import { generateToolsFromManifest, type ToolsEngine } from '@lobechat/context-engine';import {type ConversationContext,type RuntimeInitialContext,@@ -200,18 +200,35 @@ export class StreamingExecutorActionImpl {toolIds: mergedToolIds,});- const enabledToolIds = toolsDetailed.enabledToolIds;+ // --- Merge injected manifests (generic, caller-driven) ---+ const injectedManifests = initialContext?.initialContext?.injectedManifests;+ const existingIdSet = new Set(toolsDetailed.enabledToolIds);+ // Skip manifests whose identifier is already enabled (dedup)+ const newInjected = injectedManifests?.filter((m) => !existingIdSet.has(m.identifier)) ?? [];++ const enabledToolIds = [+ ...toolsDetailed.enabledToolIds,+ ...newInjected.map((m) => m.identifier),+ ];+ const enabledManifests = [...toolsDetailed.enabledManifests, ...newInjected];+ const injectedTools = newInjected.flatMap((m) => generateToolsFromManifest(m));+ const tools = toolsDetailed.tools+ ? [...toolsDetailed.tools, ...injectedTools]+ : injectedTools.length > 0+ ? injectedTools+ : undefined;+// Use enabledManifests directly to avoid getEnabledPluginManifests adding default tools againconst toolManifestMap = Object.fromEntries(- toolsDetailed.enabledManifests.map((manifest) => [manifest.identifier, manifest]),+ enabledManifests.map((manifest) => [manifest.identifier, manifest]),);// Merge tools generation result into agentConfig for chatService to useconst agentConfigWithTools = {...agentConfig,- enabledManifests: toolsDetailed.enabledManifests,+ enabledManifests,enabledToolIds,- tools: toolsDetailed.tools,+ tools,};log(@@ -698,7 +715,12 @@ export class StreamingExecutorActionImpl {setTimeout(() => {useChatStore.getState()- .sendMessage({ message: mergedContent, files: mergedFiles, context: execContext })+ .sendMessage({+ context: execContext,+ editorData: merged.editorData,+ files: mergedFiles,+ message: mergedContent,+ }).catch((e: unknown) => {console.error('[internal_execAgentRuntime] sendMessage for queued content failed:',diff --git a/src/store/chat/slices/operation/__tests__/actions.test.ts b/src/store/chat/slices/operation/__tests__/actions.test.tsindex 93e55e94629..728a4842f2e 100644--- a/src/store/chat/slices/operation/__tests__/actions.test.ts+++ b/src/store/chat/slices/operation/__tests__/actions.test.ts@@ -2,6 +2,7 @@ import { act, renderHook } from '@testing-library/react';import { produce } from 'immer';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mergeQueuedMessages } from '@/store/chat/slices/operation/types';import { useChatStore } from '@/store/chat/store';describe('Operation Actions', () => {@@ -13,6 +14,51 @@ describe('Operation Actions', () => {vi.clearAllTimers();});+ describe('mergeQueuedMessages', () => {+ it('should preserve merged editorData for queued rich text messages', () => {+ const firstParagraph = {+ children: [+ {+ actionCategory: 'tool',+ actionLabel: 'Notebook',+ actionType: 'lobe-notebook',+ type: 'action-tag',+ },+ ],+ type: 'paragraph',+ };+ const secondParagraph = {+ children: [{ text: 'second message', type: 'text', version: 1 }],+ type: 'paragraph',+ };++ const merged = mergeQueuedMessages([+ {+ content: 'first message',+ createdAt: 1,+ editorData: { root: { children: [firstParagraph], type: 'root', version: 1 } },+ id: 'q1',+ interruptMode: 'soft',+ },+ {+ content: 'second message',+ createdAt: 2,+ editorData: { root: { children: [secondParagraph], type: 'root', version: 1 } },+ id: 'q2',+ interruptMode: 'soft',+ },+ ]);++ expect(merged.content).toBe('first message\n\nsecond message');+ expect(merged.editorData?.root.children).toHaveLength(3);+ expect(merged.editorData?.root.children[0]).toEqual(firstParagraph);+ expect(merged.editorData?.root.children[1]).toEqual(+ expect.objectContaining({ children: [], type: 'paragraph' }),+ );+ expect(merged.editorData?.root.children[2]).toEqual(secondParagraph);+ });+ });+describe('startOperation', () => {it('should create a new operation with correct initial state', () => {const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex 2202a1d785d..de6f20c133f 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -190,6 +190,8 @@ export interface Operation {export interface QueuedMessage {content: string;createdAt: number;+ /** Lexical editor JSON state for rich text rendering */+ editorData?: Record<string, any>;files?: string[];id: string;interruptMode: 'soft' | 'hard';@@ -200,9 +202,85 @@ export interface QueuedMessage {*/export interface MergedQueuedMessage {content: string;+ /** Lexical editor JSON state for rich text rendering */+ editorData?: Record<string, any>;files: string[];}+const createTextNode = (text: string) => ({+ detail: 0,+ format: 0,+ mode: 'normal',+ style: '',+ text,+ type: 'text',+ version: 1,+});++const createParagraphNode = (text = '') => ({+ children: text ? [createTextNode(text)] : [],+ direction: 'ltr',+ format: '',+ indent: 0,+ type: 'paragraph',+ version: 1,+});++const createEditorDataFromContent = (content: string): Record<string, any> | undefined => {+ if (!content) return undefined;++ return {+ root: {+ children: content.split('\n').map((line) => createParagraphNode(line)),+ direction: 'ltr',+ format: '',+ indent: 0,+ type: 'root',+ version: 1,+ },+ };+};++const normalizeQueuedEditorData = (message: QueuedMessage): Record<string, any> | undefined => {+ if (message.editorData?.root) return message.editorData;++ return createEditorDataFromContent(message.content);+};++const mergeQueuedEditorData = (messages: QueuedMessage[]): Record<string, any> | undefined => {+ const mergedChildren: any[] = [];+ let baseRoot: Record<string, any> | undefined;++ for (const message of messages) {+ const editorData = normalizeQueuedEditorData(message);+ const root = editorData?.root;+ const children = root?.children;++ if (!Array.isArray(children) || children.length === 0) continue;++ if (!baseRoot) {+ baseRoot = structuredClone(root);+ }++ if (mergedChildren.length > 0) {+ mergedChildren.push(createParagraphNode());+ }++ mergedChildren.push(...structuredClone(children));+ }++ if (mergedChildren.length === 0) return undefined;++ return {+ root: {+ ...baseRoot,+ children: mergedChildren,+ type: 'root',+ version: baseRoot?.version ?? 1,+ },+ };+};+/*** Merge multiple queued messages into a single message.* Sorted by creation time, content joined with double newlines.@@ -211,6 +289,7 @@ export const mergeQueuedMessages = (messages: QueuedMessage[]): MergedQueuedMessconst sorted = [...messages].sort((a, b) => a.createdAt - b.createdAt);return {content: sorted.map((m) => m.content).join('\n\n'),+ editorData: mergeQueuedEditorData(sorted),files: sorted.flatMap((m) => m.files ?? []),};};diff --git a/src/store/home/slices/homeInput/action.ts b/src/store/home/slices/homeInput/action.tsindex bc75791d21a..9c480a8cf41 100644--- a/src/store/home/slices/homeInput/action.ts+++ b/src/store/home/slices/homeInput/action.ts@@ -14,6 +14,11 @@ import { type StarterMode } from './initialState';const n = setNamespace('homeInput');+interface SendMessageWithEditorParams {+ editorData?: Record<string, any>;+ message: string;+}+type Setter = StoreSetter<HomeStore>;export const createHomeInputSlice = (set: Setter, get: () => HomeStore, _api?: unknown) =>new HomeInputActionImpl(set, get, _api);@@ -32,7 +37,7 @@ export class HomeInputActionImpl {this.#set({ inputActiveMode: null }, false, n('clearInputMode'));};- sendAsAgent = async (message: string): Promise<string> => {+ sendAsAgent = async ({ editorData, message }: SendMessageWithEditorParams): Promise<string> => {this.#set({ homeInputLoading: true }, false, n('sendAsAgent/start'));try {@@ -77,6 +82,7 @@ export class HomeInputActionImpl {await sendMessage({context: { agentId: agentBuilderId!, scope: 'agent_builder' },+ editorData,message,});}@@ -90,7 +96,7 @@ export class HomeInputActionImpl {}};- sendAsGroup = async (message: string): Promise<string> => {+ sendAsGroup = async ({ editorData, message }: SendMessageWithEditorParams): Promise<string> => {this.#set({ homeInputLoading: true }, false, n('sendAsGroup/start'));try {@@ -137,6 +143,7 @@ export class HomeInputActionImpl {const { sendMessage } = useChatStore.getState();await sendMessage({context: { agentId: groupAgentBuilderId, scope: 'group_agent_builder' },+ editorData,message,});}@@ -158,7 +165,7 @@ export class HomeInputActionImpl {this.#set({ inputActiveMode: null }, false, n('sendAsResearch'));};- sendAsWrite = async (message: string): Promise<string> => {+ sendAsWrite = async ({ editorData, message }: SendMessageWithEditorParams): Promise<string> => {this.#set({ homeInputLoading: true }, false, n('sendAsWrite/start'));try {@@ -197,6 +204,7 @@ export class HomeInputActionImpl {const { sendMessage } = useChatStore.getState();await sendMessage({context: { agentId: pageAgentId, scope: 'page' },+ editorData,message,});}diff --git a/src/store/session/slices/homeInput/action.test.ts b/src/store/session/slices/homeInput/action.test.tsindex 79081588493..9d01050aec6 100644--- a/src/store/session/slices/homeInput/action.test.ts+++ b/src/store/session/slices/homeInput/action.test.ts@@ -151,7 +151,7 @@ describe('HomeInputAction', () => {const { result } = renderHook(() => useSessionStore());await act(async () => {- await result.current.sendAsAgent('Test prompt');+ await result.current.sendAsAgent({ message: 'Test prompt' });});// createSession is called internally via the store action@@ -164,7 +164,7 @@ describe('HomeInputAction', () => {const longMessage = 'A'.repeat(100);await act(async () => {- await result.current.sendAsAgent(longMessage);+ await result.current.sendAsAgent({ message: longMessage });});expect(sessionService.createSession).toHaveBeenCalled();@@ -174,7 +174,7 @@ describe('HomeInputAction', () => {const { result } = renderHook(() => useSessionStore());await act(async () => {- await result.current.sendAsAgent('Test');+ await result.current.sendAsAgent({ message: 'Test' });});expect(mockNavigate).toHaveBeenCalledWith('/agent/new-agent-id/profile');@@ -184,7 +184,7 @@ describe('HomeInputAction', () => {const { result } = renderHook(() => useSessionStore());await act(async () => {- await result.current.sendAsAgent('Test message');+ await result.current.sendAsAgent({ message: 'Test message' });});expect(mockSendMessage).toHaveBeenCalledWith({@@ -201,7 +201,7 @@ describe('HomeInputAction', () => {});await act(async () => {- await result.current.sendAsAgent('Test');+ await result.current.sendAsAgent({ message: 'Test' });});expect(result.current.inputActiveMode).toBeNull();@@ -212,7 +212,7 @@ describe('HomeInputAction', () => {let agentId: string | undefined;await act(async () => {- agentId = await result.current.sendAsAgent('Test');+ agentId = await result.current.sendAsAgent({ message: 'Test' });});expect(agentId).toBe('new-agent-id');@@ -222,7 +222,7 @@ describe('HomeInputAction', () => {const { result } = renderHook(() => useSessionStore());await act(async () => {- await result.current.sendAsAgent('Test');+ await result.current.sendAsAgent({ message: 'Test' });});expect(result.current.homeInputLoading).toBe(false);@@ -234,7 +234,7 @@ describe('HomeInputAction', () => {await act(async () => {try {- await result.current.sendAsAgent('Test');+ await result.current.sendAsAgent({ message: 'Test' });} catch {// Expected error}@@ -252,7 +252,7 @@ describe('HomeInputAction', () => {await expect(act(async () => {- await result.current.sendAsAgent('Test');+ await result.current.sendAsAgent({ message: 'Test' });}),).resolves.not.toThrow();});@@ -269,7 +269,7 @@ describe('HomeInputAction', () => {const { result } = renderHook(() => useSessionStore());await act(async () => {- await result.current.sendAsWrite('Document content');+ await result.current.sendAsWrite({ message: 'Document content' });});expect(documentService.createDocument).toHaveBeenCalledWith({@@ -283,7 +283,7 @@ describe('HomeInputAction', () => {const longMessage = 'B'.repeat(100);await act(async () => {- await result.current.sendAsWrite(longMessage);+ await result.current.sendAsWrite({ message: longMessage });});expect(documentService.createDocument).toHaveBeenCalledWith({@@ -296,7 +296,7 @@ describe('HomeInputAction', () => {const { result } = renderHook(() => useSessionStore());await act(async () => {- await result.current.sendAsWrite('Content');+ await result.current.sendAsWrite({ message: 'Content' });});expect(mockNavigate).toHaveBeenCalledWith('/page/new-doc-id');@@ -306,7 +306,7 @@ describe('HomeInputAction', () => {const { result } = renderHook(() => useSessionStore());await act(async () => {- await result.current.sendAsWrite('Content');+ await result.current.sendAsWrite({ message: 'Content' });});expect(mockSendMessage).toHaveBeenCalledWith({@@ -326,7 +326,7 @@ describe('HomeInputAction', () => {});await act(async () => {- await result.current.sendAsWrite('Content');+ await result.current.sendAsWrite({ message: 'Content' });});expect(result.current.inputActiveMode).toBeNull();@@ -337,7 +337,7 @@ describe('HomeInputAction', () => {let docId: string | undefined;await act(async () => {- docId = await result.current.sendAsWrite('Content');+ docId = await result.current.sendAsWrite({ message: 'Content' });});expect(docId).toBe('new-doc-id');@@ -347,7 +347,7 @@ describe('HomeInputAction', () => {const { result } = renderHook(() => useSessionStore());await act(async () => {- await result.current.sendAsWrite('Content');+ await result.current.sendAsWrite({ message: 'Content' });});expect(result.current.homeInputLoading).toBe(false);@@ -359,7 +359,7 @@ describe('HomeInputAction', () => {await act(async () => {try {- await result.current.sendAsWrite('Content');+ await result.current.sendAsWrite({ message: 'Content' });} catch {// Expected error}diff --git a/src/store/session/slices/homeInput/action.ts b/src/store/session/slices/homeInput/action.tsindex 34755b3270d..777918f75c8 100644--- a/src/store/session/slices/homeInput/action.ts+++ b/src/store/session/slices/homeInput/action.ts@@ -9,6 +9,11 @@ import { type StarterMode } from './initialState';const n = setNamespace('homeInput');+interface SendMessageWithEditorParams {+ editorData?: Record<string, any>;+ message: string;+}+type Setter = StoreSetter<SessionStore>;export const createHomeInputSlice = (set: Setter, get: () => SessionStore, _api?: unknown) =>new HomeInputActionImpl(set, get, _api);@@ -27,7 +32,7 @@ export class HomeInputActionImpl {this.#set({ inputActiveMode: null }, false, n('clearInputMode'));};- sendAsAgent = async (message: string): Promise<string> => {+ sendAsAgent = async ({ editorData, message }: SendMessageWithEditorParams): Promise<string> => {this.#set({ homeInputLoading: true }, false, n('sendAsAgent/start'));try {@@ -50,6 +55,7 @@ export class HomeInputActionImpl {const { sendMessage } = useChatStore.getState();await sendMessage({context: { agentId: newAgentId, scope: 'agent_builder' },+ editorData,message,});@@ -81,7 +87,7 @@ export class HomeInputActionImpl {this.#set({ inputActiveMode: null }, false, n('sendAsResearch'));};- sendAsWrite = async (message: string): Promise<string> => {+ sendAsWrite = async ({ editorData, message }: SendMessageWithEditorParams): Promise<string> => {this.#set({ homeInputLoading: true }, false, n('sendAsWrite/start'));try {@@ -104,6 +110,7 @@ export class HomeInputActionImpl {agentId: newDoc.id,scope: 'page',},+ editorData,message,});diff --git a/src/utils/webOnboardingToolResult.test.ts b/src/utils/webOnboardingToolResult.test.tsindex bca64aeed45..ad75db80dc4 100644--- a/src/utils/webOnboardingToolResult.test.ts+++ b/src/utils/webOnboardingToolResult.test.ts@@ -33,7 +33,7 @@ describe('web onboarding tool result helpers', () => {expect(message).toContain('Structured fields still needed: interests.');expect(message).toContain('Phase: Discovery');expect(message).toContain(- 'Questioning rule: use lobe-user-interaction askUserQuestion for structured collection or explicit UI input. For natural exploratory questions, plain text is allowed.',+ 'Questioning rule: use `lobe-user-interaction________builtin` tool for structured collection or explicit UI input. For natural exploratory questions, plain text is allowed.',);});