Skip to content

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

✨ feat: use `lobe-tools` to support progressive disclosure (#12489)

Arvin Xuc5d41fd2bec0
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index f965dad562b..25dd55b89de 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -552,11 +552,6 @@
"count": 1
}
},
- "src/store/chat/agents/createAgentExecutors.ts": {
- "sort-keys-fix/sort-keys-fix": {
- "count": 1
- }
- },
"src/store/chat/slices/aiAgent/actions/groupOrchestration.ts": {
"no-unused-private-class-members": {
"count": 1
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index ef3ba0b1ef2..99f2729e870 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -170,6 +170,10 @@
"builtins.lobe-page-agent.apiName.updateNode": "Update node",
"builtins.lobe-page-agent.apiName.wrapNodes": "Wrap nodes",
"builtins.lobe-page-agent.title": "Page",
+ "builtins.lobe-skill-store.apiName.importFromMarket": "Import from Market",
+ "builtins.lobe-skill-store.apiName.importSkill": "Import Skill",
+ "builtins.lobe-skill-store.apiName.searchSkill": "Search Skills",
+ "builtins.lobe-skill-store.title": "Skill Store",
"builtins.lobe-skills.apiName.execScript": "Run Script",
"builtins.lobe-skills.apiName.exportFile": "Export File",
"builtins.lobe-skills.apiName.importFromMarket": "Import from Market",
@@ -178,6 +182,7 @@
"builtins.lobe-skills.apiName.runSkill": "Activate Skill",
"builtins.lobe-skills.apiName.searchSkill": "Search Skills",
"builtins.lobe-skills.title": "Skills",
+ "builtins.lobe-tools.apiName.activateTools": "Activate Tools",
"builtins.lobe-user-memory.apiName.addContextMemory": "Add context memory",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "Add experience memory",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "Add identity memory",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index 154c1edbac2..307ff1b7402 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -170,6 +170,10 @@
"builtins.lobe-page-agent.apiName.updateNode": "更新节点",
"builtins.lobe-page-agent.apiName.wrapNodes": "包装节点",
"builtins.lobe-page-agent.title": "文档",
+ "builtins.lobe-skill-store.apiName.importFromMarket": "从市场导入",
+ "builtins.lobe-skill-store.apiName.importSkill": "导入技能",
+ "builtins.lobe-skill-store.apiName.searchSkill": "搜索技能",
+ "builtins.lobe-skill-store.title": "技能商店",
"builtins.lobe-skills.apiName.execScript": "执行脚本",
"builtins.lobe-skills.apiName.exportFile": "导出文件",
"builtins.lobe-skills.apiName.importFromMarket": "从市场导入",
@@ -178,6 +182,7 @@
"builtins.lobe-skills.apiName.runSkill": "激活技能",
"builtins.lobe-skills.apiName.searchSkill": "搜索技能",
"builtins.lobe-skills.title": "技能",
+ "builtins.lobe-tools.apiName.activateTools": "激活工具",
"builtins.lobe-user-memory.apiName.addContextMemory": "添加情境记忆",
"builtins.lobe-user-memory.apiName.addExperienceMemory": "添加经验记忆",
"builtins.lobe-user-memory.apiName.addIdentityMemory": "添加身份记忆",
diff --git a/package.json b/package.json
index 1b5dfbfb324..ded22f3a225 100644
--- a/package.json
+++ b/package.json
@@ -197,6 +197,7 @@
"@lobechat/builtin-tool-memory": "workspace:*",
"@lobechat/builtin-tool-notebook": "workspace:*",
"@lobechat/builtin-tool-page-agent": "workspace:*",
+ "@lobechat/builtin-tool-skill-store": "workspace:*",
"@lobechat/builtin-tool-skills": "workspace:*",
"@lobechat/builtin-tool-tools": "workspace:*",
"@lobechat/builtin-tool-web-browsing": "workspace:*",
diff --git a/packages/agent-runtime/src/utils/stepContextComputer.ts b/packages/agent-runtime/src/utils/stepContextComputer.ts
index 9f1b7b9d4a7..9dfff1bbce2 100644
--- a/packages/agent-runtime/src/utils/stepContextComputer.ts
+++ b/packages/agent-runtime/src/utils/stepContextComputer.ts
@@ -5,6 +5,10 @@ import type { RuntimeStepContext, StepContextTodos } from '@lobechat/types';
* Using object parameter for future extensibility
*/
export interface ComputeStepContextParams {
+ /**
+ * Activated tool identifiers accumulated from lobe-tools messages
+ */
+ activatedToolIds?: string[];
/**
* Pre-computed todos state from message selector
* Should be computed using selectTodosFromMessages in chat store selectors
@@ -25,8 +29,12 @@ export interface ComputeStepContextParams {
* @param params - Object containing pre-computed state values
* @returns RuntimeStepContext assembled from the provided values
*/
-export const computeStepContext = ({ todos }: ComputeStepContextParams): RuntimeStepContext => {
+export const computeStepContext = ({
+ activatedToolIds,
+ todos,
+}: ComputeStepContextParams): RuntimeStepContext => {
return {
+ ...(activatedToolIds?.length && { activatedToolIds }),
...(todos && { todos }),
};
};
diff --git a/packages/builtin-agents/src/agents/inbox/index.ts b/packages/builtin-agents/src/agents/inbox/index.ts
index af080736ad7..bf7166c78ee 100644
--- a/packages/builtin-agents/src/agents/inbox/index.ts
+++ b/packages/builtin-agents/src/agents/inbox/index.ts
@@ -1,6 +1,3 @@
-import { GTDIdentifier } from '@lobechat/builtin-tool-gtd';
-import { NotebookIdentifier } from '@lobechat/builtin-tool-notebook';
-
import type { BuiltinAgentDefinition } from '../../types';
import { BUILTIN_AGENT_SLUGS } from '../../types';
import { systemRole } from './systemRole';
@@ -13,8 +10,8 @@ import { systemRole } from './systemRole';
export const INBOX: BuiltinAgentDefinition = {
avatar: '/avatars/lobe-ai.png',
runtime: (ctx) => ({
- plugins: [GTDIdentifier, NotebookIdentifier, ...(ctx.plugins || [])],
- systemRole: systemRole,
+ plugins: ctx.plugins || [],
+ systemRole,
}),
slug: BUILTIN_AGENT_SLUGS.inbox,
diff --git a/packages/builtin-tool-gtd/src/manifest.ts b/packages/builtin-tool-gtd/src/manifest.ts
index 793d2787bf6..6c0892072d2 100644
--- a/packages/builtin-tool-gtd/src/manifest.ts
+++ b/packages/builtin-tool-gtd/src/manifest.ts
@@ -7,7 +7,6 @@ import { GTDApiName } from './types';
export const GTDIdentifier = 'lobe-gtd';
export const GTDManifest: BuiltinToolManifest = {
- /* eslint-disable sort-keys-fix/sort-keys-fix */
api: [
// ==================== Planning ====================
{
@@ -237,9 +236,7 @@ export const GTDManifest: BuiltinToolManifest = {
identifier: GTDIdentifier,
meta: {
avatar: '✅',
- description: 'Plan goals and track progress with GTD methodology',
- readme:
- 'Plan goals and track progress using GTD methodology. Create strategic plans, manage todo lists with status tracking, and execute long-running async tasks.',
+ description: 'Create plans, manage todo lists with status tracking, and run background tasks',
title: 'GTD Tools',
},
systemRole: systemPrompt,
diff --git a/packages/builtin-tool-knowledge-base/src/manifest.ts b/packages/builtin-tool-knowledge-base/src/manifest.ts
index 73d269605ca..3f1b067e517 100644
--- a/packages/builtin-tool-knowledge-base/src/manifest.ts
+++ b/packages/builtin-tool-knowledge-base/src/manifest.ts
@@ -52,9 +52,8 @@ export const KnowledgeBaseManifest: BuiltinToolManifest = {
identifier: KnowledgeBaseIdentifier,
meta: {
avatar: '📚',
- description: 'Search and retrieve information from knowledge bases',
- readme:
- 'Search through your knowledge base using semantic vector search to find relevant files and content. Retrieve full documents for in-depth analysis and reference.',
+ description:
+ 'Search uploaded documents and domain knowledge via semantic vector search — for persistent, reusable reference',
title: 'Knowledge Base',
},
systemRole: systemPrompt,
diff --git a/packages/builtin-tool-memory/src/manifest.ts b/packages/builtin-tool-memory/src/manifest.ts
index 44e1051964b..7e659423071 100644
--- a/packages/builtin-tool-memory/src/manifest.ts
+++ b/packages/builtin-tool-memory/src/manifest.ts
@@ -812,9 +812,8 @@ export const MemoryManifest: BuiltinToolManifest = {
identifier: 'lobe-user-memory',
meta: {
avatar: '🧠',
- description: 'Remember user preferences, activities, and experiences across conversations',
- readme:
- 'Build a personalized knowledge base about you. Remember preferences, track activities and experiences, store identity information, and recall relevant context in future conversations.',
+ description:
+ 'Store and recall user preferences, activities, identities, and experiences across conversations',
title: 'Memory',
},
systemRole: systemPrompt,
diff --git a/packages/builtin-tool-notebook/src/manifest.ts b/packages/builtin-tool-notebook/src/manifest.ts
index 1e8063a04ae..4a57d34864f 100644
--- a/packages/builtin-tool-notebook/src/manifest.ts
+++ b/packages/builtin-tool-notebook/src/manifest.ts
@@ -95,9 +95,8 @@ export const NotebookManifest: BuiltinToolManifest = {
identifier: NotebookIdentifier,
meta: {
avatar: '📓',
- description: 'Create and manage documents in the topic notebook',
- readme:
- 'Create and manage persistent documents within conversation topics. Save notes, reports, articles, and markdown content that stays accessible across sessions.',
+ description:
+ 'Save and organize notes, reports, and drafts within the current topic — for temporary or session-scoped content',
title: 'Notebook',
},
systemRole: systemPrompt,
diff --git a/packages/builtin-tool-skill-store/package.json b/packages/builtin-tool-skill-store/package.json
new file mode 100644
index 00000000000..9dd21d5c46c
--- /dev/null
+++ b/packages/builtin-tool-skill-store/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "@lobechat/builtin-tool-skill-store",
+ "version": "1.0.0",
+ "private": true,
+ "exports": {
+ ".": "./src/index.ts",
+ "./client": "./src/client/index.ts",
+ "./executor": "./src/executor/index.ts",
+ "./executionRuntime": "./src/ExecutionRuntime/index.ts"
+ },
+ "main": "./src/index.ts",
+ "devDependencies": {
+ "@lobechat/types": "workspace:*"
+ },
+ "peerDependencies": {
+ "@lobehub/ui": "*",
+ "antd-style": "*",
+ "react": "*",
+ "react-i18next": "*"
+ }
+}
diff --git a/packages/builtin-tool-skill-store/src/ExecutionRuntime/index.ts b/packages/builtin-tool-skill-store/src/ExecutionRuntime/index.ts
new file mode 100644
index 00000000000..463ad971622
--- /dev/null
+++ b/packages/builtin-tool-skill-store/src/ExecutionRuntime/index.ts
@@ -0,0 +1,156 @@
+import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
+
+import type {
+ ImportFromMarketParams,
+ ImportSkillParams,
+ MarketSkillItem,
+ SearchSkillParams,
+} from '../types';
+
+export interface SkillImportServiceResult {
+ skill: { id: string; name: string };
+ status: 'created' | 'updated' | 'unchanged';
+}
+
+export interface SkillStoreRuntimeService {
+ importFromGitHub: (gitUrl: string) => Promise<SkillImportServiceResult>;
+ importFromMarket?: (identifier: string) => Promise<SkillImportServiceResult>;
+ importFromUrl: (url: string) => Promise<SkillImportServiceResult>;
+ importFromZipUrl: (url: string) => Promise<SkillImportServiceResult>;
+ onSkillImported?: () => Promise<void>;
+ searchSkill?: (
+ params: SearchSkillParams,
+ ) => Promise<{ items: MarketSkillItem[]; page: number; pageSize: number; total: number }>;
+}
+
+export interface SkillStoreExecutionRuntimeOptions {
+ service: SkillStoreRuntimeService;
+}
+
+export class SkillStoreExecutionRuntime {
+ private service: SkillStoreRuntimeService;
+
+ constructor(options: SkillStoreExecutionRuntimeOptions) {
+ this.service = options.service;
+ }
+
+ async importSkill(args: ImportSkillParams): Promise<BuiltinServerRuntimeOutput> {
+ const { url, type } = args;
+
+ // Determine import method based on URL and type
+ let isGitHub = false;
+ try {
+ const hostname = new URL(url).hostname;
+ isGitHub = hostname === 'github.com' || hostname.endsWith('.github.com');
+ } catch {
+ // invalid URL — fall through to importFromUrl
+ }
+
+ try {
+ let result: SkillImportServiceResult;
+
+ if (isGitHub && type === 'url') {
+ result = await this.service.importFromGitHub(url);
+ } else if (type === 'zip') {
+ result = await this.service.importFromZipUrl(url);
+ } else {
+ result = await this.service.importFromUrl(url);
+ }
+
+ // Refresh skills list so the new skill becomes available
+ await this.service.onSkillImported?.();
+
+ return {
+ content: `Skill "${result.skill.name}" ${result.status} successfully.`,
+ state: {
+ name: result.skill.name,
+ skillId: result.skill.id,
+ status: result.status,
+ success: true,
+ },
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `Failed to import skill: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ async searchSkill(args: SearchSkillParams): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.service.searchSkill) {
+ return {
+ content: 'Market skill search is not available in this environment.',
+ success: false,
+ };
+ }
+
+ try {
+ const result = await this.service.searchSkill(args);
+
+ if (result.items.length === 0) {
+ return {
+ content: args.q
+ ? `No skills found matching "${args.q}"`
+ : 'No skills found in the market',
+ state: result,
+ success: true,
+ };
+ }
+
+ // Format results as a readable list
+ const skillsList = result.items
+ .map(
+ (skill, index) =>
+ `${index + 1}. **${skill.name}** (${skill.identifier})\n ${skill.description}${skill.summary ? `\n Summary: ${skill.summary}` : ''}${skill.repository ? `\n Repository: ${skill.repository}` : ''}${skill.installCount ? `\n Installs: ${skill.installCount}` : ''}`,
+ )
+ .join('\n\n');
+
+ return {
+ content: `Found ${result.total} skills (page ${result.page}/${Math.ceil(result.total / result.pageSize)}):\n\n${skillsList}`,
+ state: result,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `Failed to search skills: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ async importFromMarket(args: ImportFromMarketParams): Promise<BuiltinServerRuntimeOutput> {
+ const { identifier } = args;
+
+ if (!this.service.importFromMarket) {
+ return {
+ content: 'Market skill import is not available in this environment.',
+ success: false,
+ };
+ }
+
+ try {
+ const result = await this.service.importFromMarket(identifier);
+
+ // Refresh skills list so the new skill becomes available
+ await this.service.onSkillImported?.();
+
+ return {
+ content: `Skill "${result.skill.name}" ${result.status} successfully from market.`,
+ state: {
+ name: result.skill.name,
+ skillId: result.skill.id,
+ status: result.status,
+ success: true,
+ },
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `Failed to import skill from market: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+}
diff --git a/packages/builtin-tool-skills/src/client/Inspector/ImportSkill/index.tsx b/packages/builtin-tool-skill-store/src/client/Inspector/ImportSkill/index.tsx
similarity index 92%
rename from packages/builtin-tool-skills/src/client/Inspector/ImportSkill/index.tsx
rename to packages/builtin-tool-skill-store/src/client/Inspector/ImportSkill/index.tsx
index dd5f5d8198c..0abc85e4bd2 100644
--- a/packages/builtin-tool-skills/src/client/Inspector/ImportSkill/index.tsx
+++ b/packages/builtin-tool-skill-store/src/client/Inspector/ImportSkill/index.tsx
@@ -28,7 +28,7 @@ export const ImportSkillInspector = memo<
if (isArgumentsStreaming && !url) {
return (
<div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
- <span>{t('builtins.lobe-skills.apiName.importSkill')}</span>
+ <span>{t('builtins.lobe-skill-store.apiName.importSkill')}</span>
</div>
);
}
@@ -43,7 +43,7 @@ export const ImportSkillInspector = memo<
(isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
)}
>
- <span>{t('builtins.lobe-skills.apiName.importSkill')}: </span>
+ <span>{t('builtins.lobe-skill-store.apiName.importSkill')}: </span>
{displayName && <span className={highlightTextStyles.primary}>{displayName}</span>}
{!isLoading &&
hasResult &&
diff --git a/packages/builtin-tool-skill-store/src/client/Inspector/index.ts b/packages/builtin-tool-skill-store/src/client/Inspector/index.ts
new file mode 100644
index 00000000000..3b4cce1a704
--- /dev/null
+++ b/packages/builtin-tool-skill-store/src/client/Inspector/index.ts
@@ -0,0 +1,6 @@
+import { SkillStoreApiName } from '../../types';
+import { ImportSkillInspector } from './ImportSkill';
+
+export const SkillStoreInspectors = {
+ [SkillStoreApiName.importSkill]: ImportSkillInspector,
+};
diff --git a/packages/builtin-tool-skills/src/client/Render/ImportSkill/index.tsx b/packages/builtin-tool-skill-store/src/client/Render/ImportSkill/index.tsx
similarity index 90%
rename from packages/builtin-tool-skills/src/client/Render/ImportSkill/index.tsx
rename to packages/builtin-tool-skill-store/src/client/Render/ImportSkill/index.tsx
index f4ec014e345..13412096811 100644
--- a/packages/builtin-tool-skills/src/client/Render/ImportSkill/index.tsx
+++ b/packages/builtin-tool-skill-store/src/client/Render/ImportSkill/index.tsx
@@ -1,6 +1,6 @@
'use client';
-import { BuiltinRenderProps } from '@lobechat/types';
+import type { BuiltinRenderProps } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
import { CheckCircle, XCircle } from 'lucide-react';
import { memo } from 'react';
@@ -15,7 +15,7 @@ const ImportSkill = memo<BuiltinRenderProps<ImportSkillParams, ImportSkillState>
if (!success) {
return (
- <Flexbox align={'center'} gap={8} horizontal style={{ fontSize: 13 }}>
+ <Flexbox horizontal align={'center'} gap={8} style={{ fontSize: 13 }}>
<XCircle size={14} style={{ color: 'var(--lobe-error-6)' }} />
<span style={{ fontWeight: 500 }}>
Failed to import skill
@@ -44,7 +44,7 @@ const ImportSkill = memo<BuiltinRenderProps<ImportSkillParams, ImportSkillState>
status === 'created' ? 'Imported' : status === 'updated' ? 'Updated' : 'Already up to date';
return (
- <Flexbox align={'center'} gap={8} horizontal style={{ fontSize: 13 }}>
+ <Flexbox horizontal align={'center'} gap={8} style={{ fontSize: 13 }}>
<CheckCircle size={14} style={{ color: 'var(--lobe-success-6)' }} />
<span style={{ fontWeight: 500 }}>
{statusLabel}:{' '}
diff --git a/packages/builtin-tool-skill-store/src/client/Render/index.ts b/packages/builtin-tool-skill-store/src/client/Render/index.ts
new file mode 100644
index 00000000000..f5f97376918
--- /dev/null
+++ b/packages/builtin-tool-skill-store/src/client/Render/index.ts
@@ -0,0 +1,6 @@
+import { SkillStoreApiName } from '../../types';
+import ImportSkill from './ImportSkill';
+
+export const SkillStoreRenders = {
+ [SkillStoreApiName.importSkill]: ImportSkill,
+};
diff --git a/packages/builtin-tool-skill-store/src/client/index.ts b/packages/builtin-tool-skill-store/src/client/index.ts
new file mode 100644
index 00000000000..873c2cb55e3
--- /dev/null
+++ b/packages/builtin-tool-skill-store/src/client/index.ts
@@ -0,0 +1,4 @@
+export { SkillStoreManifest } from '../manifest';
+export * from '../types';
+export { SkillStoreInspectors } from './Inspector';
+export { SkillStoreRenders } from './Render';
diff --git a/packages/builtin-tool-skill-store/src/executor/index.ts b/packages/builtin-tool-skill-store/src/executor/index.ts
new file mode 100644
index 00000000000..2ce2bb2ee73
--- /dev/null
+++ b/packages/builtin-tool-skill-store/src/executor/index.ts
@@ -0,0 +1,111 @@
+import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';
+
+import type { SkillStoreExecutionRuntime } from '../ExecutionRuntime';
+import {
+ type ImportFromMarketParams,
+ type ImportSkillParams,
+ type SearchSkillParams,
+ SkillStoreApiName,
+ SkillStoreIdentifier,
+} from '../types';
+
+class SkillStoreExecutor extends BaseExecutor<typeof SkillStoreApiName> {
+ readonly identifier = SkillStoreIdentifier;
+ protected readonly apiEnum = SkillStoreApiName;
+
+ private runtime: SkillStoreExecutionRuntime;
+
+ constructor(runtime: SkillStoreExecutionRuntime) {
+ super();
+ this.runtime = runtime;
+ }
+
+ importSkill = async (
+ params: ImportSkillParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ try {
+ if (ctx.signal?.aborted) {
+ return { stop: true, success: false };
+ }
+
+ const result = await this.runtime.importSkill(params);
+
+ if (result.success) {
+ return { content: result.content, state: result.state, success: true };
+ }
+
+ return {
+ content: result.content,
+ error: { message: result.content, type: 'PluginServerError' },
+ success: false,
+ };
+ } catch (e) {
+ const err = e as Error;
+ return {
+ error: { body: e, message: err.message, type: 'PluginServerError' },
+ success: false,
+ };
+ }
+ };
+
+ searchSkill = async (
+ params: SearchSkillParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ try {
+ if (ctx.signal?.aborted) {
+ return { stop: true, success: false };
+ }
+
+ const result = await this.runtime.searchSkill(params);
+
+ if (result.success) {
+ return { content: result.content, state: result.state, success: true };
+ }
+
+ return {
+ content: result.content,
+ error: { message: result.content, type: 'PluginServerError' },
+ success: false,
+ };
+ } catch (e) {
+ const err = e as Error;
+ return {
+ error: { body: e, message: err.message, type: 'PluginServerError' },
+ success: false,
+ };
+ }
+ };
+
+ importFromMarket = async (
+ params: ImportFromMarketParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ try {
+ if (ctx.signal?.aborted) {
+ return { stop: true, success: false };
+ }
+
+ const result = await this.runtime.importFromMarket(params);
+
+ if (result.success) {
+ return { content: result.content, state: result.state, success: true };
+ }
+
+ return {
+ content: result.content,
+ error: { message: result.content, type: 'PluginServerError' },
+ success: false,
+ };
+ } catch (e) {
+ const err = e as Error;
+ return {
+ error: { body: e, message: err.message, type: 'PluginServerError' },
+ success: false,
+ };
+ }
+ };
+}
+
+export { SkillStoreExecutor };
diff --git a/packages/builtin-tool-skill-store/src/index.ts b/packages/builtin-tool-skill-store/src/index.ts
new file mode 100644
index 00000000000..00bbc29770b
--- /dev/null
+++ b/packages/builtin-tool-skill-store/src/index.ts
@@ -0,0 +1,13 @@
+export { SkillStoreManifest } from './manifest';
+export { systemPrompt } from './systemRole';
+export {
+ type ImportFromMarketParams,
+ type ImportFromMarketState,
+ type ImportSkillParams,
+ type ImportSkillState,
+ type MarketSkillItem,
+ type SearchSkillParams,
+ type SearchSkillState,
+ SkillStoreApiName,
+ SkillStoreIdentifier,
+} from './types';
diff --git a/packages/builtin-tool-skill-store/src/manifest.ts b/packages/builtin-tool-skill-store/src/manifest.ts
new file mode 100644
index 00000000000..a331a06052d
--- /dev/null
+++ b/packages/builtin-tool-skill-store/src/manifest.ts
@@ -0,0 +1,103 @@
+import type { BuiltinToolManifest } from '@lobechat/types';
+
+import { systemPrompt } from './systemRole';
+import { SkillStoreApiName, SkillStoreIdentifier } from './types';
+
+export const SkillStoreManifest: BuiltinToolManifest = {
+ api: [
+ {
+ description:
+ "Search for skills in the LobeHub Market. Use this to discover available skills that can extend Claude's capabilities. Search across skill names, descriptions, and summaries. Results can be filtered and sorted by various criteria (stars, downloads, etc).",
+ name: SkillStoreApiName.searchSkill,
+ parameters: {
+ properties: {
+ locale: {
+ description: 'Locale for search results (e.g., "en-US", "zh-CN"). Optional.',
+ type: 'string',
+ },
+ order: {
+ description: 'Sort order: "asc" for ascending, "desc" for descending. Default: "desc".',
+ enum: ['asc', 'desc'],
+ type: 'string',
+ },
+ page: {
+ description: 'Page number for pagination. Default: 1.',
+ type: 'number',
+ },
+ pageSize: {
+ description: 'Number of results per page. Default: 20.',
+ type: 'number',
+ },
+ q: {
+ description:
+ 'Search query to filter skills. Searches across skill name, description, and summary. Optional.',
+ type: 'string',
+ },
+ sort: {
+ description:
+ 'Field to sort by. Options: createdAt (creation date), installCount (installs), forks (GitHub forks), name (alphabetical), relevance (search relevance), stars (GitHub stars), updatedAt (last update), watchers (GitHub watchers). Default: "updatedAt".',
+ enum: [
+ 'createdAt',
+ 'forks',
+ 'installCount',
+ 'name',
+ 'relevance',
+ 'stars',
+ 'updatedAt',
+ 'watchers',
+ ],
+ type: 'string',
+ },
+ },
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Import/install a skill directly from the LobeHub Market using its identifier. This is the recommended way to install skills from the market after searching with searchSkill. The skill will be downloaded and installed automatically. Requires user confirmation before installation.',
+ humanIntervention: 'required',
+ name: SkillStoreApiName.importFromMarket,
+ parameters: {
+ properties: {
+ identifier: {
+ description:
+ 'The unique identifier of the skill in the market (e.g., "github.anthropics.skills.skills.skill-creator"). You can get this from searchSkill results.',
+ type: 'string',
+ },
+ },
+ required: ['identifier'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Import/install a skill from a URL. Supports SKILL.md URLs, GitHub repository URLs, and ZIP package URLs. Requires user confirmation before installation.',
+ humanIntervention: 'required',
+ name: SkillStoreApiName.importSkill,
+ parameters: {
+ properties: {
+ type: {
+ description:
+ 'The type of the URL: "url" for SKILL.md or GitHub links, "zip" for ZIP package URLs.',
+ enum: ['url', 'zip'],
+ type: 'string',
+ },
+ url: {
+ description: 'The URL of the skill resource to import.',
+ type: 'string',
+ },
+ },
+ required: ['url', 'type'],
+ type: 'object',
+ },
+ },
+ ],
+ identifier: SkillStoreIdentifier,
+ meta: {
+ avatar: '🏪',
+ description: 'Browse and install agent skills from the LobeHub marketplace',
+ title: 'Skill Store',
+ },
+ systemRole: systemPrompt,
+ type: 'builtin',
+};
diff --git a/packages/builtin-tool-skill-store/src/systemRole.ts b/packages/builtin-tool-skill-store/src/systemRole.ts
new file mode 100644
index 00000000000..def9864a21d
--- /dev/null
+++ b/packages/builtin-tool-skill-store/src/systemRole.ts
@@ -0,0 +1,41 @@
+export const systemPrompt = `You have access to a Skill Store tool that allows you to search, discover, and install skill packages from the LobeHub Marketplace.
+
+<core_capabilities>
+1. Search for skills in the LobeHub Market (searchSkill)
+2. Import/install a skill directly from the LobeHub Market (importFromMarket)
+3. Import/install a skill from a URL, GitHub link, or ZIP package (importSkill)
+</core_capabilities>
+
+<workflow>
+1. When the user wants to find/discover skills, use searchSkill to search the LobeHub Market
+2. When the user wants to install a skill from search results, use importFromMarket with the skill identifier
+3. When the user wants to install/import a skill from a URL, call importSkill with the URL
+</workflow>
+
+<tool_selection_guidelines>
+- **searchSkill**: Call this to search for skills in the LobeHub Market
+ - Provide a search query to find relevant skills
+ - Returns a list of matching skills with name, description, author, and identifier
+ - Use this when the user wants to discover or find new skills
+ - After finding a skill, use importFromMarket to install it
+
+- **importFromMarket**: Call this to install a skill directly from the LobeHub Market
+ - Provide the skill identifier (obtained from searchSkill results)
+ - Downloads and installs the skill from the market
+ - Requires user confirmation before installation
+ - Returns the skill name and import status (created/updated/unchanged)
+ - Preferred over importSkill when the skill is available in the LobeHub Market
+
+- **importSkill**: Call this to import/install a skill from a URL
+ - Provide the URL and the type ("url" for SKILL.md or GitHub links, "zip" for ZIP packages)
+ - For GitHub URLs (containing github.com), use type "url" — the system will auto-detect GitHub
+ - Requires user confirmation before installation
+ - Returns the skill name and import status (created/updated/unchanged)
+
+</tool_selection_guidelines>
+
+<best_practices>
+- Use searchSkill to help users discover skills when they describe a task but don't know a specific skill
+- Prefer importFromMarket over importSkill when the skill is available in the LobeHub Market
+</best_practices>
+`;
diff --git a/packages/builtin-tool-skill-store/src/types.ts b/packages/builtin-tool-skill-store/src/types.ts
new file mode 100644
index 00000000000..a534b617c90
--- /dev/null
+++ b/packages/builtin-tool-skill-store/src/types.ts
@@ -0,0 +1,89 @@
+export const SkillStoreIdentifier = 'lobe-skill-store';
+
+export const SkillStoreApiName = {
+ importFromMarket: 'importFromMarket',
+ importSkill: 'importSkill',
+ searchSkill: 'searchSkill',
+};
+
+export interface ImportSkillParams {
+ type: 'url' | 'zip';
+ url: string;
+}
+
+export interface ImportSkillState {
+ name?: string;
+ skillId?: string;
+ status: 'created' | 'updated' | 'unchanged';
+ success: boolean;
+}
+
+export interface SearchSkillParams {
+ /**
+ * Locale for search results (e.g., 'en-US', 'zh-CN')
+ */
+ locale?: string;
+ /**
+ * Sort order: 'asc' or 'desc'
+ */
+ order?: 'asc' | 'desc';
+ /**
+ * Page number (default: 1)
+ */
+ page?: number;
+ /**
+ * Page size (default: 20)
+ */
+ pageSize?: number;
+ /**
+ * Search query (searches name, description, summary)
+ */
+ q?: string;
+ /**
+ * Sort field: createdAt | installCount | forks | name | relevance | stars | updatedAt | watchers
+ */
+ sort?:
+ | 'createdAt'
+ | 'forks'
+ | 'installCount'
+ | 'name'
+ | 'relevance'
+ | 'stars'
+ | 'updatedAt'
+ | 'watchers';
+}
+
+export interface MarketSkillItem {
+ category?: string;
+ createdAt: string;
+ description: string;
+ identifier: string;
+ installCount: number;
+ name: string;
+ repository?: string;
+ sourceUrl?: string;
+ summary?: string;
+ updatedAt: string;
+ version?: string;
+}
+
+export interface SearchSkillState {
+ items: MarketSkillItem[];
+ page: number;
+ pageSize: number;
+ total: number;
+}
+
+export interface ImportFromMarketParams {
+ /**
+ * The identifier of the skill to import from market
+ */
+ identifier: string;
+}
+
+export interface ImportFromMarketState {
+ name?: string;
+ skillId?: string;
+ status: 'created' | 'updated' | 'unchanged';
+ success: boolean;
+}
diff --git a/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts
index cb7d26aa08b..ea827583191 100644
--- a/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts
+++ b/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts
@@ -1,15 +1,12 @@
import { describe, expect, it, vi } from 'vitest';
import type { CommandResult } from '../types';
-import { SkillsExecutionRuntime, type SkillRuntimeService } from './index';
+import { type SkillRuntimeService, SkillsExecutionRuntime } from './index';
const createMockService = (overrides?: Partial<SkillRuntimeService>): SkillRuntimeService => ({
findAll: vi.fn().mockResolvedValue({ data: [], total: 0 }),
findById: vi.fn().mockResolvedValue(undefined),
findByName: vi.fn().mockResolvedValue(undefined),
- importFromGitHub: vi.fn(),
- importFromUrl: vi.fn(),
- importFromZipUrl: vi.fn(),
readResource: vi.fn(),
...overrides,
});
diff --git a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts b/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts
index 5f8f85a6efc..dbc7aced613 100644
--- a/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-skills/src/ExecutionRuntime/index.ts
@@ -11,13 +11,9 @@ import {
type CommandResult,
type ExecScriptParams,
type ExportFileParams,
- type ImportFromMarketParams,
- type ImportSkillParams,
- type MarketSkillItem,
type ReadReferenceParams,
type RunCommandOptions,
type RunSkillParams,
- type SearchSkillParams,
} from '../types';
/**
@@ -52,16 +48,8 @@ export interface SkillRuntimeService {
findAll: () => Promise<{ data: SkillListItem[]; total: number }>;
findById: (id: string) => Promise<SkillItem | undefined>;
findByName: (name: string) => Promise<SkillItem | undefined>;
- importFromGitHub: (gitUrl: string) => Promise<SkillImportServiceResult>;
- importFromMarket?: (identifier: string) => Promise<SkillImportServiceResult>;
- importFromUrl: (url: string) => Promise<SkillImportServiceResult>;
- importFromZipUrl: (url: string) => Promise<SkillImportServiceResult>;
- onSkillImported?: () => Promise<void>;
readResource: (id: string, path: string) => Promise<SkillResourceContent>;
runCommand?: (options: RunCommandOptions) => Promise<CommandResult>;
- searchSkill?: (
- params: SearchSkillParams,
- ) => Promise<{ items: MarketSkillItem[]; page: number; pageSize: number; total: number }>;
}
export interface SkillsExecutionRuntimeOptions {
@@ -78,44 +66,6 @@ export class SkillsExecutionRuntime {
this.builtinSkills = options.builtinSkills || [];
}
- async importSkill(args: ImportSkillParams): Promise<BuiltinServerRuntimeOutput> {
- const { url, type } = args;
-
- // Determine import method based on URL and type
- const isGitHub = url.includes('github.com');
-
- try {
- let result: SkillImportServiceResult;
-
- if (isGitHub && type === 'url') {
- result = await this.service.importFromGitHub(url);
- } else if (type === 'zip') {
- result = await this.service.importFromZipUrl(url);
- } else {
- result = await this.service.importFromUrl(url);
- }
-
- // Refresh skills list so the new skill becomes available
- await this.service.onSkillImported?.();
-
- return {
- content: `Skill "${result.skill.name}" ${result.status} successfully.`,
- state: {
- name: result.skill.name,
- skillId: result.skill.id,
- status: result.status,
- success: true,
- },
- success: true,
- };
- } catch (e) {
- return {
- content: `Failed to import skill: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
async execScript(args: ExecScriptParams): Promise<BuiltinServerRuntimeOutput> {
const { command, runInClient, description, config } = args;
@@ -308,80 +258,4 @@ export class SkillsExecutionRuntime {
success: true,
};
}
-
- async searchSkill(args: SearchSkillParams): Promise<BuiltinServerRuntimeOutput> {
- if (!this.service.searchSkill) {
- return {
- content: 'Market skill search is not available in this environment.',
- success: false,
- };
- }
-
- try {
- const result = await this.service.searchSkill(args);
-
- if (result.items.length === 0) {
- return {
- content: args.q
- ? `No skills found matching "${args.q}"`
- : 'No skills found in the market',
- state: result,
- success: true,
- };
- }
-
- // Format results as a readable list
- const skillsList = result.items
- .map(
- (skill, index) =>
- `${index + 1}. **${skill.name}** (${skill.identifier})\n ${skill.description}${skill.summary ? `\n Summary: ${skill.summary}` : ''}${skill.repository ? `\n Repository: ${skill.repository}` : ''}${skill.installCount ? `\n Installs: ${skill.installCount}` : ''}`,
- )
- .join('\n\n');
-
- return {
- content: `Found ${result.total} skills (page ${result.page}/${Math.ceil(result.total / result.pageSize)}):\n\n${skillsList}`,
- state: result,
- success: true,
- };
- } catch (e) {
- return {
- content: `Failed to search skills: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- async importFromMarket(args: ImportFromMarketParams): Promise<BuiltinServerRuntimeOutput> {
- const { identifier } = args;
-
- if (!this.service.importFromMarket) {
- return {
- content: 'Market skill import is not available in this environment.',
- success: false,
- };
- }
-
- try {
- const result = await this.service.importFromMarket(identifier);
-
- // Refresh skills list so the new skill becomes available
- await this.service.onSkillImported?.();
-
- return {
- content: `Skill "${result.skill.name}" ${result.status} successfully from market.`,
- state: {
- name: result.skill.name,
- skillId: result.skill.id,
- status: result.status,
- success: true,
- },
- success: true,
- };
- } catch (e) {
- return {
- content: `Failed to import skill from market: ${(e as Error).message}`,
- success: false,
- };
- }
- }
}
diff --git a/packages/builtin-tool-skills/src/client/Inspector/index.ts b/packages/builtin-tool-skills/src/client/Inspector/index.ts
index dd2215bf741..ed07757644e 100644
--- a/packages/builtin-tool-skills/src/client/Inspector/index.ts
+++ b/packages/builtin-tool-skills/src/client/Inspector/index.ts
@@ -1,12 +1,10 @@
import { SkillsApiName } from '../../types';
import { ExecScriptInspector } from './ExecScript';
-import { ImportSkillInspector } from './ImportSkill';
import { ReadReferenceInspector } from './ReadReference';
import { RunSkillInspector } from './RunSkill';
export const SkillsInspectors = {
[SkillsApiName.execScript]: ExecScriptInspector,
- [SkillsApiName.importSkill]: ImportSkillInspector,
[SkillsApiName.readReference]: ReadReferenceInspector,
[SkillsApiName.runSkill]: RunSkillInspector,
};
diff --git a/packages/builtin-tool-skills/src/client/Render/index.ts b/packages/builtin-tool-skills/src/client/Render/index.ts
index 69cf117d62a..9265d8d9781 100644
--- a/packages/builtin-tool-skills/src/client/Render/index.ts
+++ b/packages/builtin-tool-skills/src/client/Render/index.ts
@@ -1,12 +1,10 @@
import { SkillsApiName } from '../../types';
import ExecScript from './ExecScript';
-import ImportSkill from './ImportSkill';
import ReadReference from './ReadReference';
import RunSkill from './RunSkill';
export const SkillsRenders = {
[SkillsApiName.execScript]: ExecScript,
- [SkillsApiName.importSkill]: ImportSkill,
[SkillsApiName.readReference]: ReadReference,
[SkillsApiName.runSkill]: RunSkill,
};
diff --git a/packages/builtin-tool-skills/src/executor/index.ts b/packages/builtin-tool-skills/src/executor/index.ts
index cd930ef7e91..4c20f0a871f 100644
--- a/packages/builtin-tool-skills/src/executor/index.ts
+++ b/packages/builtin-tool-skills/src/executor/index.ts
@@ -1,14 +1,11 @@
import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';
-import { SkillsExecutionRuntime } from '../ExecutionRuntime';
+import type { SkillsExecutionRuntime } from '../ExecutionRuntime';
import {
type ExecScriptParams,
type ExportFileParams,
- type ImportFromMarketParams,
- type ImportSkillParams,
type ReadReferenceParams,
type RunSkillParams,
- type SearchSkillParams,
SkillsApiName,
SkillsIdentifier,
} from '../types';
@@ -24,35 +21,6 @@ class SkillsExecutor extends BaseExecutor<typeof SkillsApiName> {
this.runtime = runtime;
}
- importSkill = async (
- params: ImportSkillParams,
- ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- try {
- if (ctx.signal?.aborted) {
- return { stop: true, success: false };
- }
-
- const result = await this.runtime.importSkill(params);
-
- if (result.success) {
- return { content: result.content, state: result.state, success: true };
- }
-
- return {
- content: result.content,
- error: { message: result.content, type: 'PluginServerError' },
- success: false,
- };
- } catch (e) {
- const err = e as Error;
- return {
- error: { body: e, message: err.message, type: 'PluginServerError' },
- success: false,
- };
- }
- };
-
execScript = async (
params: ExecScriptParams,
ctx: BuiltinToolContext,
@@ -168,64 +136,6 @@ class SkillsExecutor extends BaseExecutor<typeof SkillsApiName> {
};
}
};
-
- searchSkill = async (
- params: SearchSkillParams,
- ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- try {
- if (ctx.signal?.aborted) {
- return { stop: true, success: false };
- }
-
- const result = await this.runtime.searchSkill(params);
-
- if (result.success) {
- return { content: result.content, state: result.state, success: true };
- }
-
- return {
- content: result.content,
- error: { message: result.content, type: 'PluginServerError' },
- success: false,
- };
- } catch (e) {
- const err = e as Error;
- return {
- error: { body: e, message: err.message, type: 'PluginServerError' },
- success: false,
- };
- }
- };
-
- importFromMarket = async (
- params: ImportFromMarketParams,
- ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- try {
- if (ctx.signal?.aborted) {
- return { stop: true, success: false };
- }
-
- const result = await this.runtime.importFromMarket(params);
-
- if (result.success) {
- return { content: result.content, state: result.state, success: true };
- }
-
- return {
- content: result.content,
- error: { message: result.content, type: 'PluginServerError' },
- success: false,
- };
- } catch (e) {
- const err = e as Error;
- return {
- error: { body: e, message: err.message, type: 'PluginServerError' },
- success: false,
- };
- }
- };
}
export { SkillsExecutor };
diff --git a/packages/builtin-tool-skills/src/index.ts b/packages/builtin-tool-skills/src/index.ts
index 27559503fd7..ef4a207eca3 100644
--- a/packages/builtin-tool-skills/src/index.ts
+++ b/packages/builtin-tool-skills/src/index.ts
@@ -2,10 +2,8 @@ export { SkillsManifest } from './manifest';
export { systemPrompt } from './systemRole';
export {
type CommandResult,
- type MarketSkillItem,
type ReadReferenceParams,
type RunSkillParams,
- type SearchSkillParams,
SkillsApiName,
SkillsIdentifier,
} from './types';
diff --git a/packages/builtin-tool-skills/src/manifest.ts b/packages/builtin-tool-skills/src/manifest.ts
index e6b4ae005e0..6cb4cdedf05 100644
--- a/packages/builtin-tool-skills/src/manifest.ts
+++ b/packages/builtin-tool-skills/src/manifest.ts
@@ -110,92 +110,6 @@ export const SkillsManifest: BuiltinToolManifest = {
type: 'object',
},
},
- {
- description:
- 'Import/install a skill from a URL. Supports SKILL.md URLs, GitHub repository URLs, and ZIP package URLs. Requires user confirmation before installation.',
- humanIntervention: 'required',
- name: SkillsApiName.importSkill,
- parameters: {
- properties: {
- type: {
- description:
- 'The type of the URL: "url" for SKILL.md or GitHub links, "zip" for ZIP package URLs.',
- enum: ['url', 'zip'],
- type: 'string',
- },
- url: {
- description: 'The URL of the skill resource to import.',
- type: 'string',
- },
- },
- required: ['url', 'type'],
- type: 'object',
- },
- },
- {
- description:
- "Search for skills in the LobeHub Market. Use this to discover available skills that can extend Claude's capabilities. Search across skill names, descriptions, and summaries. Results can be filtered and sorted by various criteria (stars, downloads, etc).",
- name: SkillsApiName.searchSkill,
- parameters: {
- properties: {
- locale: {
- description: 'Locale for search results (e.g., "en-US", "zh-CN"). Optional.',
- type: 'string',
- },
- order: {
- description: 'Sort order: "asc" for ascending, "desc" for descending. Default: "desc".',
- enum: ['asc', 'desc'],
- type: 'string',
- },
- page: {
- description: 'Page number for pagination. Default: 1.',
- type: 'number',
- },
- pageSize: {
- description: 'Number of results per page. Default: 20.',
- type: 'number',
- },
- q: {
- description:
- 'Search query to filter skills. Searches across skill name, description, and summary. Optional.',
- type: 'string',
- },
- sort: {
- description:
- 'Field to sort by. Options: createdAt (creation date), installCount (installs), forks (GitHub forks), name (alphabetical), relevance (search relevance), stars (GitHub stars), updatedAt (last update), watchers (GitHub watchers). Default: "updatedAt".',
- enum: [
- 'createdAt',
- 'forks',
- 'installCount',
- 'name',
- 'relevance',
- 'stars',
- 'updatedAt',
- 'watchers',
- ],
- type: 'string',
- },
- },
- type: 'object',
- },
- },
- {
- description:
- 'Import/install a skill directly from the LobeHub Market using its identifier. This is the recommended way to install skills from the market after searching with searchSkill. The skill will be downloaded and installed automatically. Requires user confirmation before installation.',
- humanIntervention: 'required',
- name: SkillsApiName.importFromMarket,
- parameters: {
- properties: {
- identifier: {
- description:
- 'The unique identifier of the skill in the market (e.g., "github.anthropics.skills.skills.skill-creator"). You can get this from searchSkill results.',
- type: 'string',
- },
- },
- required: ['identifier'],
- type: 'object',
- },
- },
],
identifier: SkillsIdentifier,
meta: {
diff --git a/packages/builtin-tool-skills/src/systemRole.ts b/packages/builtin-tool-skills/src/systemRole.ts
index e85bcf810dd..393f93bc669 100644
--- a/packages/builtin-tool-skills/src/systemRole.ts
+++ b/packages/builtin-tool-skills/src/systemRole.ts
@@ -29,9 +29,6 @@ export const systemPrompt = `You have access to a Skills tool that allows you to
2. Read reference files attached to a skill (readReference)
3. Execute shell commands specified in a skill's instructions (execScript)
4. Export files generated during skill execution to cloud storage (exportFile)
-5. Import/install a skill from a URL, GitHub link, or ZIP package (importSkill)
-6. Search for skills in the LobeHub Market (searchSkill)
-7. Import/install a skill directly from the LobeHub Market (importFromMarket)
</core_capabilities>
<workflow>
@@ -41,9 +38,6 @@ export const systemPrompt = `You have access to a Skills tool that allows you to
4. If the skill content instructs you to run CLI commands, use execScript to execute them
5. If the skill execution generates output files, use exportFile to save them for the user
6. Apply the skill's instructions to fulfill the user's request
-7. When the user wants to install/import a skill from a URL, call importSkill with the URL
-8. When the user wants to find/discover skills, use searchSkill to search the LobeHub Market
-9. When the user wants to install a skill from search results, use importFromMarket with the skill identifier
</workflow>
<tool_selection_guidelines>
@@ -72,25 +66,6 @@ export const systemPrompt = `You have access to a Skills tool that allows you to
- Provide the file path in the execution environment and the desired filename
- Returns a permanent download URL for the exported file
- Best for: skill outputs, generated reports, processed data files, result artifacts
-
-- **importSkill**: Call this to import/install a skill from a URL
- - Provide the URL and the type ("url" for SKILL.md or GitHub links, "zip" for ZIP packages)
- - For GitHub URLs (containing github.com), use type "url" — the system will auto-detect GitHub
- - Requires user confirmation before installation
- - Returns the skill name and import status (created/updated/unchanged)
-
-- **searchSkill**: Call this to search for skills in the LobeHub Market
- - Provide a search query to find relevant skills
- - Returns a list of matching skills with name, description, author, and identifier
- - Use this when the user wants to discover or find new skills
- - After finding a skill, use importFromMarket to install it
-
-- **importFromMarket**: Call this to install a skill directly from the LobeHub Market
- - Provide the skill identifier (obtained from searchSkill results)
- - Downloads and installs the skill from the market
- - Requires user confirmation before installation
- - Returns the skill name and import status (created/updated/unchanged)
- - Preferred over importSkill when the skill is available in the LobeHub Market
</tool_selection_guidelines>
<execscript_vs_runcommand>
@@ -124,7 +99,5 @@ ${isDesktop ? runInClientSection : ''}
- Use exportFile when the skill generates output files that need to be saved
- If runSkill returns an error with available skills, inform the user what skills are available
- If execScript fails, consider using Cloud Sandbox's runCommand as a fallback
-- Use searchSkill to help users discover skills when they describe a task but don't know a specific skill
-- Prefer importFromMarket over importSkill when the skill is available in the LobeHub Market
</best_practices>
`;
diff --git a/packages/builtin-tool-skills/src/types.ts b/packages/builtin-tool-skills/src/types.ts
index 6152323bc52..189911828b3 100644
--- a/packages/builtin-tool-skills/src/types.ts
+++ b/packages/builtin-tool-skills/src/types.ts
@@ -3,11 +3,8 @@ export const SkillsIdentifier = 'lobe-skills';
export const SkillsApiName = {
execScript: 'execScript',
exportFile: 'exportFile',
- importSkill: 'importSkill',
- importFromMarket: 'importFromMarket',
readReference: 'readReference',
runSkill: 'runSkill',
- searchSkill: 'searchSkill',
};
export interface RunSkillParams {
@@ -80,18 +77,6 @@ export interface ReadReferenceState {
size: number;
}
-export interface ImportSkillParams {
- type: 'url' | 'zip';
- url: string;
-}
-
-export interface ImportSkillState {
- name?: string;
- skillId?: string;
- status: 'created' | 'updated' | 'unchanged';
- success: boolean;
-}
-
export interface ExportFileParams {
/**
* The filename to use for the exported file
@@ -110,73 +95,3 @@ export interface ExportFileState {
size?: number;
url?: string;
}
-
-export interface SearchSkillParams {
- /**
- * Locale for search results (e.g., 'en-US', 'zh-CN')
- */
- locale?: string;
- /**
- * Sort order: 'asc' or 'desc'
- */
- order?: 'asc' | 'desc';
- /**
- * Page number (default: 1)
- */
- page?: number;
- /**
- * Page size (default: 20)
- */
- pageSize?: number;
- /**
- * Search query (searches name, description, summary)
- */
- q?: string;
- /**
- * Sort field: createdAt | installCount | forks | name | relevance | stars | updatedAt | watchers
- */
- sort?:
- | 'createdAt'
- | 'forks'
- | 'installCount'
- | 'name'
- | 'relevance'
- | 'stars'
- | 'updatedAt'
- | 'watchers';
-}
-
-export interface MarketSkillItem {
- category?: string;
- createdAt: string;
- description: string;
- identifier: string;
- installCount: number;
- name: string;
- repository?: string;
- sourceUrl?: string;
- summary?: string;
- updatedAt: string;
- version?: string;
-}
-
-export interface SearchSkillState {
- items: MarketSkillItem[];
- page: number;
- pageSize: number;
- total: number;
-}
-
-export interface ImportFromMarketParams {
- /**
- * The identifier of the skill to import from market
- */
- identifier: string;
-}
-
-export interface ImportFromMarketState {
- name?: string;
- skillId?: string;
- status: 'created' | 'updated' | 'unchanged';
- success: boolean;
-}
diff --git a/packages/builtin-tool-tools/package.json b/packages/builtin-tool-tools/package.json
index ddf6400bf32..91a915aa288 100644
--- a/packages/builtin-tool-tools/package.json
+++ b/packages/builtin-tool-tools/package.json
@@ -4,6 +4,7 @@
"private": true,
"exports": {
".": "./src/index.ts",
+ "./client": "./src/client/index.ts",
"./executor": "./src/executor/index.ts",
"./executionRuntime": "./src/ExecutionRuntime/index.ts"
},
diff --git a/packages/builtin-tool-tools/src/ExecutionRuntime/index.ts b/packages/builtin-tool-tools/src/ExecutionRuntime/index.ts
index 94d65851a92..75d620e6e8d 100644
--- a/packages/builtin-tool-tools/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-tools/src/ExecutionRuntime/index.ts
@@ -4,6 +4,7 @@ import type { ActivatedToolInfo, ActivateToolsParams } from '../types';
export interface ToolManifestInfo {
apiDescriptions: Array<{ description: string; name: string }>;
+ avatar?: string;
identifier: string;
name: string;
systemRole?: string;
@@ -57,6 +58,7 @@ export class ToolsActivatorExecutionRuntime {
const activatedTools: ActivatedToolInfo[] = manifests.map((m) => ({
apiCount: m.apiDescriptions.length,
+ avatar: m.avatar,
identifier: m.identifier,
name: m.name,
}));
diff --git a/packages/builtin-tool-tools/src/client/Inspector/ActivateTools/index.tsx b/packages/builtin-tool-tools/src/client/Inspector/ActivateTools/index.tsx
new file mode 100644
index 00000000000..db79e2fb70b
--- /dev/null
+++ b/packages/builtin-tool-tools/src/client/Inspector/ActivateTools/index.tsx
@@ -0,0 +1,77 @@
+'use client';
+
+import { type BuiltinInspectorProps } from '@lobechat/types';
+import { Avatar } from '@lobehub/ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import type { ActivateToolsParams, ActivateToolsState } from '../../../types';
+
+const styles = createStaticStyles(({ css }) => ({
+ tool: css`
+ display: inline-flex;
+ gap: 2px;
+ align-items: center;
+
+ font-size: 14px;
+ line-height: 18px;
+ color: ${cssVar.colorText};
+ `,
+ tools: css`
+ display: inline-flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ align-items: center;
+
+ margin-inline-start: 4px;
+ `,
+}));
+
+export const ActivateToolsInspector = memo<
+ BuiltinInspectorProps<ActivateToolsParams, ActivateToolsState>
+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
+ const { t } = useTranslation('plugin');
+
+ const identifiers = args?.identifiers || partialArgs?.identifiers;
+ const activatedTools = pluginState?.activatedTools;
+
+ // Streaming / Loading: show identifiers from arguments
+ if (isArgumentsStreaming || isLoading) {
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-tools.apiName.activateTools')}</span>
+ {identifiers && identifiers.length > 0 && (
+ <span className={styles.tools}>
+ {identifiers.map((id) => (
+ <code className={styles.tool} key={id}>
+ {id}
+ </code>
+ ))}
+ </span>
+ )}
+ </div>
+ );
+ }
+
+ // Finished: show activated tool names with avatars
+ return (
+ <div className={inspectorTextStyles.root}>
+ <span>{t('builtins.lobe-tools.apiName.activateTools')}</span>
+ {activatedTools && activatedTools.length > 0 && (
+ <span className={styles.tools}>
+ {activatedTools.map((tool) => (
+ <span className={styles.tool} key={tool.identifier}>
+ {tool.avatar && <Avatar avatar={tool.avatar} size={18} title={tool.name} />}
+ <span>{tool.name}</span>
+ </span>
+ ))}
+ </span>
+ )}
+ </div>
+ );
+});
+
+ActivateToolsInspector.displayName = 'ActivateToolsInspector';
diff --git a/packages/builtin-tool-tools/src/client/Inspector/index.ts b/packages/builtin-tool-tools/src/client/Inspector/index.ts
new file mode 100644
index 00000000000..120b514d4d6
--- /dev/null
+++ b/packages/builtin-tool-tools/src/client/Inspector/index.ts
@@ -0,0 +1,6 @@
+import { ToolsActivatorApiName } from '../../types';
+import { ActivateToolsInspector } from './ActivateTools';
+
+export const LobeToolsInspectors = {
+ [ToolsActivatorApiName.activateTools]: ActivateToolsInspector,
+};
diff --git a/packages/builtin-tool-tools/src/client/index.ts b/packages/builtin-tool-tools/src/client/index.ts
new file mode 100644
index 00000000000..4c86bac74dd
--- /dev/null
+++ b/packages/builtin-tool-tools/src/client/index.ts
@@ -0,0 +1,3 @@
+export { LobeToolsManifest } from '../manifest';
+export * from '../types';
+export { LobeToolsInspectors } from './Inspector';
diff --git a/packages/builtin-tool-tools/src/systemRole.ts b/packages/builtin-tool-tools/src/systemRole.ts
index 2f75fb71f78..6b11530d2c5 100644
--- a/packages/builtin-tool-tools/src/systemRole.ts
+++ b/packages/builtin-tool-tools/src/systemRole.ts
@@ -17,9 +17,22 @@ export const systemPrompt = `You have access to a Tool Discovery system that all
- If an identifier is not found, it will be reported in the response
</tool_selection_guidelines>
+<skill_store_discovery>
+When the user's task involves a specialized domain (e.g. creating presentations/PPT, generating PDFs, charts, diagrams, or other domain-specific work), and the \`<available_tools>\` list does NOT contain a matching tool, you should search the LobeHub Skill Marketplace for a dedicated skill before falling back to generic tools.
+
+**Decision flow:**
+1. Check \`<available_tools>\` for a relevant tool → if found, use \`activateTools\`
+2. If no matching tool is found AND \`lobe-skill-store\` is available → call \`searchSkill\` to search the marketplace
+3. If a relevant skill is found → call \`importFromMarket\` to install it, then use it
+4. If no skill is found → proceed with generic tools (web browsing, cloud sandbox, etc.)
+
+This ensures the user benefits from purpose-built skills rather than relying on generic tools for specialized tasks.
+</skill_store_discovery>
+
<best_practices>
+- **IMPORTANT: Plan ahead and activate all needed tools upfront in a single call.** Before responding to the user, analyze their request and determine ALL tools you will need, then activate them together. Do NOT activate tools incrementally during a multi-step task.
- Check the \`<available_tools>\` list before activating tools
-- Activate all tools you'll need for a task in a single call when possible
+- For specialized tasks, search the Skill Marketplace first — a dedicated skill is almost always better than a generic approach
- Only activate tools that are relevant to the user's current request
- After activation, use the tools' APIs directly — no need to call activateTools again for the same tools
</best_practices>
diff --git a/packages/builtin-tool-tools/src/types.ts b/packages/builtin-tool-tools/src/types.ts
index 7bc696c3500..102167e153d 100644
--- a/packages/builtin-tool-tools/src/types.ts
+++ b/packages/builtin-tool-tools/src/types.ts
@@ -10,6 +10,7 @@ export interface ActivateToolsParams {
export interface ActivatedToolInfo {
apiCount: number;
+ avatar?: string;
identifier: string;
name: string;
}
diff --git a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.test.ts
new file mode 100644
index 00000000000..6f07d76e612
--- /dev/null
+++ b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { WebBrowsingExecutionRuntime } from './index';
+
+describe('WebBrowsingExecutionRuntime', () => {
+ describe('search', () => {
+ it('should return success with search results', async () => {
+ const mockSearchService = {
+ crawlPages: vi.fn(),
+ webSearch: vi.fn().mockResolvedValue({
+ costTime: 100,
+ query: 'test',
+ resultNumbers: 1,
+ results: [
+ {
+ content: 'Test content',
+ engines: ['google'],
+ parsedUrl: 'example.com',
+ score: 1,
+ title: 'Test',
+ url: 'https://example.com',
+ },
+ ],
+ }),
+ };
+
+ const runtime = new WebBrowsingExecutionRuntime({ searchService: mockSearchService });
+ const result = await runtime.search({ query: 'test' });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('searchResults');
+ expect(result.content).toContain('Test');
+ });
+
+ it('should return success: false when response has errorDetail', async () => {
+ const mockSearchService = {
+ crawlPages: vi.fn(),
+ webSearch: vi.fn().mockResolvedValue({
+ costTime: 0,
+ errorDetail: 'Failed to search: 500 Internal Server Error',
+ query: 'test',
+ resultNumbers: 0,
+ results: [],
+ }),
+ };
+
+ const runtime = new WebBrowsingExecutionRuntime({ searchService: mockSearchService });
+ const result = await runtime.search({ query: 'test' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('Failed to search: 500 Internal Server Error');
+ expect(result.error).toEqual({ message: 'Failed to search: 500 Internal Server Error' });
+ });
+
+ it('should return success: true with empty results when no errorDetail', async () => {
+ const mockSearchService = {
+ crawlPages: vi.fn(),
+ webSearch: vi.fn().mockResolvedValue({
+ costTime: 50,
+ query: 'test',
+ resultNumbers: 0,
+ results: [],
+ }),
+ };
+
+ const runtime = new WebBrowsingExecutionRuntime({ searchService: mockSearchService });
+ const result = await runtime.search({ query: 'test' });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toBe('<searchResults />');
+ });
+
+ it('should return success: false when webSearch throws', async () => {
+ const mockSearchService = {
+ crawlPages: vi.fn(),
+ webSearch: vi.fn().mockRejectedValue(new Error('Network error')),
+ };
+
+ const runtime = new WebBrowsingExecutionRuntime({ searchService: mockSearchService });
+ const result = await runtime.search({ query: 'test' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('Network error');
+ });
+ });
+});
diff --git a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts
index 0e018fdfc60..c814e1c3d3a 100644
--- a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts
@@ -24,6 +24,16 @@ export class WebBrowsingExecutionRuntime {
try {
const data = await this.searchService.webSearch(args as SearchQuery, options);
+ // If search failed with error detail, return as failure
+ if (data.errorDetail) {
+ return {
+ content: data.errorDetail,
+ error: { message: data.errorDetail },
+ state: data,
+ success: false,
+ };
+ }
+
// add LIMITED_COUNT search results to message content
const searchContent: SearchContent[] = data.results
.slice(0, SEARCH_ITEM_LIMITED_COUNT)
diff --git a/packages/builtin-tool-web-browsing/src/manifest.ts b/packages/builtin-tool-web-browsing/src/manifest.ts
index 0a48b674149..264a22638e4 100644
--- a/packages/builtin-tool-web-browsing/src/manifest.ts
+++ b/packages/builtin-tool-web-browsing/src/manifest.ts
@@ -98,6 +98,8 @@ export const WebBrowsingManifest: BuiltinToolManifest = {
identifier: 'lobe-web-browsing',
meta: {
avatar: '🌐',
+ description:
+ 'Search the web for current information and crawl web pages to extract content. Supports multiple search engines, categories, and time ranges.',
readme:
'Search the web for current information and crawl web pages to extract content. Supports multiple search engines, categories, and time ranges for comprehensive research.',
title: 'Web Browsing',
diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.json
index a2578b77b4e..b51129c43f9 100644
--- a/packages/builtin-tools/package.json
+++ b/packages/builtin-tools/package.json
@@ -26,6 +26,7 @@
"@lobechat/builtin-tool-memory": "workspace:*",
"@lobechat/builtin-tool-notebook": "workspace:*",
"@lobechat/builtin-tool-page-agent": "workspace:*",
+ "@lobechat/builtin-tool-skill-store": "workspace:*",
"@lobechat/builtin-tool-skills": "workspace:*",
"@lobechat/builtin-tool-tools": "workspace:*",
"@lobechat/builtin-tool-web-browsing": "workspace:*",
diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.ts
index 4bd9c664780..40be56c5e7b 100644
--- a/packages/builtin-tools/src/index.ts
+++ b/packages/builtin-tools/src/index.ts
@@ -8,6 +8,7 @@ import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { MemoryManifest } from '@lobechat/builtin-tool-memory';
import { NotebookManifest } from '@lobechat/builtin-tool-notebook';
import { PageAgentManifest } from '@lobechat/builtin-tool-page-agent';
+import { SkillStoreManifest } from '@lobechat/builtin-tool-skill-store';
import { SkillsManifest } from '@lobechat/builtin-tool-skills';
import { LobeToolsManifest } from '@lobechat/builtin-tool-tools';
import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
@@ -19,19 +20,37 @@ import { type LobeBuiltinTool } from '@lobechat/types';
* Shared between frontend (createAgentToolsEngine) and server (createServerAgentToolsEngine).
*/
export const defaultToolIds = [
+ LobeToolsManifest.identifier,
+ SkillsManifest.identifier,
+ SkillStoreManifest.identifier,
WebBrowsingManifest.identifier,
KnowledgeBaseManifest.identifier,
- SkillsManifest.identifier,
];
export const builtinTools: LobeBuiltinTool[] = [
{
+ discoverable: false,
+ hidden: true,
+ identifier: LobeToolsManifest.identifier,
+ manifest: LobeToolsManifest,
+ type: 'builtin',
+ },
+ {
+ discoverable: false,
hidden: true,
identifier: SkillsManifest.identifier,
manifest: SkillsManifest,
type: 'builtin',
},
{
+ discoverable: false,
+ hidden: true,
+ identifier: SkillStoreManifest.identifier,
+ manifest: SkillStoreManifest,
+ type: 'builtin',
+ },
+ {
+ discoverable: isDesktop,
hidden: !isDesktop,
identifier: LocalSystemManifest.identifier,
manifest: LocalSystemManifest,
@@ -60,24 +79,28 @@ export const builtinTools: LobeBuiltinTool[] = [
type: 'builtin',
},
{
+ discoverable: false,
hidden: true,
identifier: PageAgentManifest.identifier,
manifest: PageAgentManifest,
type: 'builtin',
},
{
+ discoverable: false,
hidden: true,
identifier: AgentBuilderManifest.identifier,
manifest: AgentBuilderManifest,
type: 'builtin',
},
{
+ discoverable: false,
hidden: true,
identifier: GroupAgentBuilderManifest.identifier,
manifest: GroupAgentBuilderManifest,
type: 'builtin',
},
{
+ discoverable: false,
hidden: true,
identifier: GroupManagementManifest.identifier,
manifest: GroupManagementManifest,
@@ -93,10 +116,4 @@ export const builtinTools: LobeBuiltinTool[] = [
manifest: NotebookManifest,
type: 'builtin',
},
- {
- hidden: true,
- identifier: LobeToolsManifest.identifier,
- manifest: LobeToolsManifest,
- type: 'builtin',
- },
];
diff --git a/packages/builtin-tools/src/inspectors.ts b/packages/builtin-tools/src/inspectors.ts
index 26612a40dc5..02b6f96349d 100644
--- a/packages/builtin-tools/src/inspectors.ts
+++ b/packages/builtin-tools/src/inspectors.ts
@@ -26,7 +26,12 @@ import {
import { MemoryInspectors, MemoryManifest } from '@lobechat/builtin-tool-memory/client';
import { NotebookInspectors, NotebookManifest } from '@lobechat/builtin-tool-notebook/client';
import { PageAgentInspectors, PageAgentManifest } from '@lobechat/builtin-tool-page-agent/client';
+import {
+ SkillStoreInspectors,
+ SkillStoreManifest,
+} from '@lobechat/builtin-tool-skill-store/client';
import { SkillsInspectors, SkillsManifest } from '@lobechat/builtin-tool-skills/client';
+import { LobeToolsInspectors, LobeToolsManifest } from '@lobechat/builtin-tool-tools/client';
import {
WebBrowsingInspectors,
WebBrowsingManifest,
@@ -57,6 +62,8 @@ const BuiltinToolInspectors: Record<string, Record<string, BuiltinInspector>> =
[MemoryManifest.identifier]: MemoryInspectors as Record<string, BuiltinInspector>,
[NotebookManifest.identifier]: NotebookInspectors as Record<string, BuiltinInspector>,
[PageAgentManifest.identifier]: PageAgentInspectors as Record<string, BuiltinInspector>,
+ [LobeToolsManifest.identifier]: LobeToolsInspectors as Record<string, BuiltinInspector>,
+ [SkillStoreManifest.identifier]: SkillStoreInspectors as Record<string, BuiltinInspector>,
[SkillsManifest.identifier]: SkillsInspectors as Record<string, BuiltinInspector>,
[WebBrowsingManifest.identifier]: WebBrowsingInspectors as Record<string, BuiltinInspector>,
};
diff --git a/packages/builtin-tools/src/renders.ts b/packages/builtin-tools/src/renders.ts
index 12dd2df26e9..19bcc74846d 100644
--- a/packages/builtin-tools/src/renders.ts
+++ b/packages/builtin-tools/src/renders.ts
@@ -17,6 +17,7 @@ import {
} from '@lobechat/builtin-tool-local-system/client';
import { MemoryManifest, MemoryRenders } from '@lobechat/builtin-tool-memory/client';
import { NotebookManifest, NotebookRenders } from '@lobechat/builtin-tool-notebook/client';
+import { SkillStoreManifest, SkillStoreRenders } from '@lobechat/builtin-tool-skill-store/client';
import { SkillsManifest, SkillsRenders } from '@lobechat/builtin-tool-skills/client';
import {
WebBrowsingManifest,
@@ -38,6 +39,7 @@ const BuiltinToolsRenders: Record<string, Record<string, BuiltinRender>> = {
[LocalSystemManifest.identifier]: LocalSystemRenders as Record<string, BuiltinRender>,
[MemoryManifest.identifier]: MemoryRenders as Record<string, BuiltinRender>,
[NotebookManifest.identifier]: NotebookRenders as Record<string, BuiltinRender>,
+ [SkillStoreManifest.identifier]: SkillStoreRenders as Record<string, BuiltinRender>,
[SkillsManifest.identifier]: SkillsRenders as Record<string, BuiltinRender>,
[WebBrowsingManifest.identifier]: WebBrowsingRenders as Record<string, BuiltinRender>,
};
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index 2e495fb95f8..6ecc36e218a 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -33,7 +33,9 @@ import {
PageEditorContextInjector,
PageSelectionsInjector,
SkillContextProvider,
+ SystemDateProvider,
SystemRoleInjector,
+ ToolDiscoveryProvider,
ToolSystemRoleProvider,
UserMemoryInjector,
} from '../../providers';
@@ -122,6 +124,7 @@ export class MessagesEngine {
formatHistorySummary,
knowledge,
skillsConfig,
+ toolDiscoveryConfig,
toolsConfig,
capabilities,
variableGenerators,
@@ -135,6 +138,7 @@ export class MessagesEngine {
initialContext,
stepContext,
pageContentContext,
+ enableSystemDate,
} = this.params;
const isAgentBuilderEnabled = !!agentBuilderContext;
@@ -149,6 +153,13 @@ export class MessagesEngine {
const isGTDPlanEnabled = gtd?.enabled && gtd?.plan;
const isGTDTodoEnabled = gtd?.enabled && gtd?.todos;
+ // System date is redundant when web-browsing or memory tools are enabled,
+ // as they already include current date in their system prompts
+ const toolIds = toolsConfig?.tools || [];
+ const hasDateAwareTools =
+ toolIds.includes('lobe-web-browsing') || toolIds.includes('lobe-user-memory');
+ const isSystemDateEnabled = enableSystemDate !== false && !hasDateAwareTools;
+
return [
// =============================================
// Phase 1: System Role Injection
@@ -157,19 +168,22 @@ export class MessagesEngine {
// 1. System role injection (agent's system role)
new SystemRoleInjector({ systemRole }),
- // 1b. Eval context injection (appends envPrompt to system message)
+ // 2. Eval context injection (appends envPrompt to system message)
new EvalContextSystemInjector({ enabled: !!evalContext?.envPrompt, evalContext }),
+ // 3. System date injection (appends current date to system message)
+ new SystemDateProvider({ enabled: isSystemDateEnabled }),
+
// =============================================
// Phase 2: First User Message Context Injection
// These providers inject content before the first user message
// Order matters: first executed = first in content
// =============================================
- // 2. User memory injection (conditionally added, injected first)
+ // 4. User memory injection (conditionally added, injected first)
...(isUserMemoryEnabled ? [new UserMemoryInjector(userMemory)] : []),
- // 3. Group context injection (agent identity and group info for multi-agent chat)
+ // 5. Group context injection (agent identity and group info for multi-agent chat)
new GroupContextInjector({
currentAgentId: agentGroup?.currentAgentId,
currentAgentName: agentGroup?.currentAgentName,
@@ -180,32 +194,37 @@ export class MessagesEngine {
systemPrompt: agentGroup?.systemPrompt,
}),
- // 4. GTD Plan injection (conditionally added, after user memory, before knowledge)
+ // 6. GTD Plan injection (conditionally added, after user memory, before knowledge)
...(isGTDPlanEnabled ? [new GTDPlanInjector({ enabled: true, plan: gtd.plan })] : []),
- // 5. Knowledge injection (full content for agent files + metadata for knowledge bases)
+ // 7. Knowledge injection (full content for agent files + metadata for knowledge bases)
new KnowledgeInjector({
fileContents: knowledge?.fileContents,
knowledgeBases: knowledge?.knowledgeBases,
}),
+ // 8. Tool Discovery context injection (available tools for dynamic activation)
+ ...(toolDiscoveryConfig?.availableTools && toolDiscoveryConfig.availableTools.length > 0
+ ? [new ToolDiscoveryProvider({ availableTools: toolDiscoveryConfig.availableTools })]
+ : []),
+
// =============================================
// Phase 3: Additional System Context
// =============================================
- // 6. Agent Builder context injection (current agent config/meta for editing)
+ // 9. Agent Builder context injection (current agent config/meta for editing)
new AgentBuilderContextInjector({
enabled: isAgentBuilderEnabled,
agentContext: agentBuilderContext,
}),
- // 7. Group Agent Builder context injection (current group config/members for editing)
+ // 10. Group Agent Builder context injection (current group config/members for editing)
new GroupAgentBuilderContextInjector({
enabled: isGroupAgentBuilderEnabled,
groupContext: groupAgentBuilderContext,
}),
- // 7.5. Skill context injection (conditionally added)
+ // 11. Skill context injection (conditionally added)
...(skillsConfig?.enabledSkills && skillsConfig.enabledSkills.length > 0
? [
new SkillContextProvider({
@@ -214,7 +233,7 @@ export class MessagesEngine {
]
: []),
- // 8. Tool system role injection (conditionally added)
+ // 12. Tool system role injection (conditionally added)
...(toolsConfig?.manifests && toolsConfig.manifests.length > 0
? [
new ToolSystemRoleProvider({
@@ -226,16 +245,16 @@ export class MessagesEngine {
]
: []),
- // 9. History summary injection
+ // 13. History summary injection
new HistorySummaryProvider({
formatHistorySummary,
historySummary,
}),
- // 12. Page Selections injection (inject user-selected text into each user message that has them)
+ // 14. Page Selections injection (inject user-selected text into each user message that has them)
new PageSelectionsInjector({ enabled: isPageEditorEnabled }),
- // 10. Page Editor context injection (inject current page content to last user message)
+ // 15. Page Editor context injection (inject current page content to last user message)
new PageEditorContextInjector({
enabled: isPageEditorEnabled,
// Use direct pageContentContext if provided (server-side), otherwise build from initialContext + stepContext (frontend)
@@ -255,40 +274,40 @@ export class MessagesEngine {
: undefined,
}),
- // 11. GTD Todo injection (conditionally added, at end of last user message)
+ // 16. GTD Todo injection (conditionally added, at end of last user message)
...(isGTDTodoEnabled ? [new GTDTodoInjector({ enabled: true, todos: gtd.todos })] : []),
// =============================================
// Phase 4: Message Transformation
// =============================================
- // 13. Input template processing
+ // 17. Input template processing
new InputTemplateProcessor({ inputTemplate }),
- // 14. Placeholder variables processing
+ // 18. Placeholder variables processing
new PlaceholderVariablesProcessor({
variableGenerators: variableGenerators || {},
}),
- // 15. AgentCouncil message flatten (convert role=agentCouncil to standard assistant + tool messages)
+ // 19. AgentCouncil message flatten (convert role=agentCouncil to standard assistant + tool messages)
new AgentCouncilFlattenProcessor(),
- // 16. Group message flatten (convert role=assistantGroup to standard assistant + tool messages)
+ // 20. Group message flatten (convert role=assistantGroup to standard assistant + tool messages)
new GroupMessageFlattenProcessor(),
- // 17. Tasks message flatten (convert role=tasks to individual task messages)
+ // 21. Tasks message flatten (convert role=tasks to individual task messages)
new TasksFlattenProcessor(),
- // 18. Task message processing (convert role=task to assistant with instruction + content)
+ // 22. Task message processing (convert role=task to assistant with instruction + content)
new TaskMessageProcessor(),
- // 19. Supervisor role restore (convert role=supervisor back to role=assistant for model)
+ // 23. Supervisor role restore (convert role=supervisor back to role=assistant for model)
new SupervisorRoleRestoreProcessor(),
- // 19b. Compressed group role transform (convert role=compressedGroup to role=user for model)
+ // 24. Compressed group role transform (convert role=compressedGroup to role=user for model)
new CompressedGroupRoleTransformProcessor(),
- // 20. Group orchestration filter (remove supervisor's orchestration messages like broadcast/speak)
+ // 25. Group orchestration filter (remove supervisor's orchestration messages like broadcast/speak)
// This must be BEFORE GroupRoleTransformProcessor so we filter based on original agentId/tools
...(isAgentGroupEnabled && agentGroup.agentMap && agentGroup.currentAgentId
? [
@@ -303,7 +322,7 @@ export class MessagesEngine {
]
: []),
- // 21. Group role transform (convert other agents' messages to user role with speaker tags)
+ // 26. Group role transform (convert other agents' messages to user role with speaker tags)
// This must be BEFORE ToolCallProcessor so other agents' tool messages are converted first
...(isAgentGroupEnabled && agentGroup.currentAgentId
? [
@@ -317,10 +336,11 @@ export class MessagesEngine {
// =============================================
// Phase 5: Content Processing
// =============================================
- // 22. Reaction feedback injection (append user reaction feedback to assistant messages)
+
+ // 27. Reaction feedback injection (append user reaction feedback to assistant messages)
new ReactionFeedbackProcessor({ enabled: true }),
- // 22. Message content processing (image encoding, etc.)
+ // 28. Message content processing (image encoding, etc.)
new MessageContentProcessor({
fileContext: fileContext || { enabled: true, includeFileUrl: true },
isCanUseVideo: capabilities?.isCanUseVideo || (() => false),
@@ -329,7 +349,7 @@ export class MessagesEngine {
provider,
}),
- // 23. Tool call processing
+ // 29. Tool call processing
new ToolCallProcessor({
genToolCallingName: this.toolNameResolver.generate.bind(this.toolNameResolver),
isCanUseFC: capabilities?.isCanUseFC || (() => true),
@@ -337,13 +357,13 @@ export class MessagesEngine {
provider,
}),
- // 24. Tool message reordering
+ // 30. Tool message reordering
new ToolMessageReorder(),
- // 25. Force finish summary injection (when maxSteps exceeded, inject summary prompt)
+ // 31. Force finish summary injection (when maxSteps exceeded, inject summary prompt)
new ForceFinishSummaryInjector({ enabled: !!forceFinish }),
- // 26. Message cleanup (final step, keep only necessary fields)
+ // 32. Message cleanup (final step, keep only necessary fields)
new MessageCleanupProcessor(),
];
}
diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
index 46aaeef33c7..ddb2057fdbd 100644
--- a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
@@ -24,6 +24,7 @@ describe('MessagesEngine', () => {
];
const createBasicParams = (overrides?: Partial<MessagesEngineParams>): MessagesEngineParams => ({
+ enableSystemDate: false,
messages: createBasicMessages(),
model: 'gpt-4',
provider: 'openai',
diff --git a/packages/context-engine/src/engine/messages/index.ts b/packages/context-engine/src/engine/messages/index.ts
index fbb99f161b5..cfee0de556d 100644
--- a/packages/context-engine/src/engine/messages/index.ts
+++ b/packages/context-engine/src/engine/messages/index.ts
@@ -15,6 +15,8 @@ export type {
MessagesEngineResult,
ModelCapabilityChecker,
OpenAIChatMessage,
+ ToolDiscoveryConfig,
+ ToolDiscoveryMeta,
ToolsConfig,
UIChatMessage,
UserMemoryActivityItem,
diff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.ts
index 5659384ebc4..5e512fa89ff 100644
--- a/packages/context-engine/src/engine/messages/types.ts
+++ b/packages/context-engine/src/engine/messages/types.ts
@@ -12,6 +12,7 @@ import type { GroupMemberInfo } from '../../providers/GroupContextInjector';
import type { GTDPlan } from '../../providers/GTDPlanInjector';
import type { GTDTodoList } from '../../providers/GTDTodoInjector';
import type { SkillMeta } from '../../providers/SkillContextProvider';
+import type { ToolDiscoveryMeta } from '../../providers/ToolDiscoveryProvider';
import type { LobeToolManifest } from '../tools/types';
/**
@@ -54,6 +55,13 @@ export interface SkillsConfig {
enabledSkills?: SkillMeta[];
}
+/**
+ * Tool Discovery configuration
+ */
+export interface ToolDiscoveryConfig {
+ availableTools?: ToolDiscoveryMeta[];
+}
+
/**
* Variable generators for placeholder replacement
* Used to replace {{variable}} placeholders in messages
@@ -186,6 +194,10 @@ export interface MessagesEngineParams {
/** Provider ID */
provider: string;
+ // ========== System date ==========
+ /** Whether to inject current date into system message (default: true) */
+ enableSystemDate?: boolean;
+
// ========== Agent configuration ==========
/** Whether to enable history message count limit */
enableHistoryCount?: boolean;
@@ -216,6 +228,10 @@ export interface MessagesEngineParams {
/** Skills configuration */
skillsConfig?: SkillsConfig;
+ // ========== Tool Discovery ==========
+ /** Tool Discovery configuration (available tools for dynamic activation) */
+ toolDiscoveryConfig?: ToolDiscoveryConfig;
+
// ========== Tools ==========
/** Tools configuration */
toolsConfig?: ToolsConfig;
@@ -288,5 +304,6 @@ export { type GroupAgentBuilderContext } from '../../providers/GroupAgentBuilder
export { type GTDPlan } from '../../providers/GTDPlanInjector';
export { type GTDTodoItem, type GTDTodoList } from '../../providers/GTDTodoInjector';
export { type SkillMeta } from '../../providers/SkillContextProvider';
+export { type ToolDiscoveryMeta } from '../../providers/ToolDiscoveryProvider';
export { type OpenAIChatMessage, type UIChatMessage } from '@/types/index';
export { type FileContent, type KnowledgeBaseInfo } from '@lobechat/prompts';
diff --git a/packages/context-engine/src/providers/SystemDateProvider.ts b/packages/context-engine/src/providers/SystemDateProvider.ts
new file mode 100644
index 00000000000..46250ffb0e8
--- /dev/null
+++ b/packages/context-engine/src/providers/SystemDateProvider.ts
@@ -0,0 +1,60 @@
+import debug from 'debug';
+
+import { BaseProvider } from '../base/BaseProvider';
+import type { PipelineContext, ProcessorOptions } from '../types';
+
+const log = debug('context-engine:provider:SystemDateProvider');
+
+export interface SystemDateProviderConfig {
+ enabled?: boolean;
+}
+
+export class SystemDateProvider extends BaseProvider {
+ readonly name = 'SystemDateProvider';
+
+ constructor(
+ private config: SystemDateProviderConfig = {},
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const clonedContext = this.cloneContext(context);
+
+ if (this.config.enabled === false) {
+ log('System date injection disabled, skipping');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ const today = new Date();
+ const year = today.getFullYear();
+ const month = String(today.getMonth() + 1).padStart(2, '0');
+ const day = String(today.getDate()).padStart(2, '0');
+ const dateStr = `${year}-${month}-${day}`;
+
+ const dateContent = `Current date: ${dateStr}`;
+
+ const existingSystemMessage = clonedContext.messages.find((msg) => msg.role === 'system');
+
+ if (existingSystemMessage) {
+ existingSystemMessage.content = [existingSystemMessage.content, dateContent]
+ .filter(Boolean)
+ .join('\n\n');
+ } else {
+ clonedContext.messages.unshift({
+ content: dateContent,
+ createdAt: Date.now(),
+ id: `system-date-${Date.now()}`,
+ role: 'system' as const,
+ updatedAt: Date.now(),
+ } as any);
+ }
+
+ clonedContext.metadata.systemDateInjected = true;
+
+ log('System date injected: %s', dateStr);
+
+ return this.markAsExecuted(clonedContext);
+ }
+}
diff --git a/packages/context-engine/src/providers/ToolDiscoveryProvider.ts b/packages/context-engine/src/providers/ToolDiscoveryProvider.ts
new file mode 100644
index 00000000000..2e70988821e
--- /dev/null
+++ b/packages/context-engine/src/providers/ToolDiscoveryProvider.ts
@@ -0,0 +1,67 @@
+import { type AvailableToolItem, availableToolsPrompts } from '@lobechat/prompts';
+import debug from 'debug';
+
+import { BaseFirstUserContentProvider } from '../base/BaseFirstUserContentProvider';
+import type { PipelineContext, ProcessorOptions } from '../types';
+
+const log = debug('context-engine:provider:ToolDiscoveryProvider');
+
+export interface ToolDiscoveryMeta {
+ description: string;
+ identifier: string;
+ name: string;
+}
+
+export interface ToolDiscoveryProviderConfig {
+ availableTools: ToolDiscoveryMeta[];
+}
+
+export class ToolDiscoveryProvider extends BaseFirstUserContentProvider {
+ readonly name = 'ToolDiscoveryProvider';
+
+ constructor(
+ private config: ToolDiscoveryProviderConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected buildContent(_context: PipelineContext): string | null {
+ const { availableTools } = this.config;
+
+ if (!availableTools || availableTools.length === 0) {
+ log('No available tools, skipping injection');
+ return null;
+ }
+
+ const tools: AvailableToolItem[] = availableTools.map((tool) => ({
+ description: tool.description,
+ identifier: tool.identifier,
+ name: tool.name,
+ }));
+
+ const content = availableToolsPrompts(tools);
+
+ if (!content) {
+ log('No tool content generated, skipping injection');
+ return null;
+ }
+
+ log(`Tool discovery content prepared, tools count: ${availableTools.length}`);
+ return content;
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const result = await super.doProcess(context);
+
+ const { availableTools } = this.config;
+ if (availableTools && availableTools.length > 0) {
+ result.metadata.toolDiscoveryContext = {
+ injected: true,
+ toolsCount: availableTools.length,
+ };
+ }
+
+ return result;
+ }
+}
diff --git a/packages/context-engine/src/providers/index.ts b/packages/context-engine/src/providers/index.ts
index 716bb054323..48ea4befe38 100644
--- a/packages/context-engine/src/providers/index.ts
+++ b/packages/context-engine/src/providers/index.ts
@@ -11,7 +11,9 @@ export { KnowledgeInjector } from './KnowledgeInjector';
export { PageEditorContextInjector } from './PageEditorContextInjector';
export { PageSelectionsInjector } from './PageSelectionsInjector';
export { SkillContextProvider } from './SkillContextProvider';
+export { SystemDateProvider } from './SystemDateProvider';
export { SystemRoleInjector } from './SystemRoleInjector';
+export { ToolDiscoveryProvider } from './ToolDiscoveryProvider';
export { ToolSystemRoleProvider } from './ToolSystemRole';
export { UserMemoryInjector } from './UserMemoryInjector';
@@ -40,6 +42,8 @@ export type { KnowledgeInjectorConfig } from './KnowledgeInjector';
export type { PageEditorContextInjectorConfig } from './PageEditorContextInjector';
export type { PageSelectionsInjectorConfig } from './PageSelectionsInjector';
export type { SkillContextProviderConfig, SkillMeta } from './SkillContextProvider';
+export type { SystemDateProviderConfig } from './SystemDateProvider';
export type { SystemRoleInjectorConfig } from './SystemRoleInjector';
+export type { ToolDiscoveryMeta, ToolDiscoveryProviderConfig } from './ToolDiscoveryProvider';
export type { ToolSystemRoleConfig } from './ToolSystemRole';
export type { MemoryContext, UserMemoryInjectorConfig } from './UserMemoryInjector';
diff --git a/packages/prompts/src/prompts/index.ts b/packages/prompts/src/prompts/index.ts
index ee06d7c8db6..fde4c8a3615 100644
--- a/packages/prompts/src/prompts/index.ts
+++ b/packages/prompts/src/prompts/index.ts
@@ -12,4 +12,5 @@ export * from './plugin';
export * from './search';
export * from './skills';
export * from './systemRole';
+export * from './toolDiscovery';
export * from './userMemory';
diff --git a/packages/prompts/src/prompts/search/searchResults.test.ts b/packages/prompts/src/prompts/search/searchResults.test.ts
index d9d5253d927..8eedb8cb554 100644
--- a/packages/prompts/src/prompts/search/searchResults.test.ts
+++ b/packages/prompts/src/prompts/search/searchResults.test.ts
@@ -3,9 +3,9 @@ import { describe, expect, it } from 'vitest';
import { searchResultsPrompt } from './searchResults';
describe('searchResultsPrompt', () => {
- it('should return empty XML for empty results', () => {
+ it('should return explicit empty message for empty results', () => {
const result = searchResultsPrompt([]);
- expect(result).toBe('<searchResults />');
+ expect(result).toBe('<searchResults>No results found.</searchResults>');
});
it('should convert basic search results to compact XML format', () => {
diff --git a/packages/prompts/src/prompts/search/searchResults.ts b/packages/prompts/src/prompts/search/searchResults.ts
index 83b93b16764..08138f12cf6 100644
--- a/packages/prompts/src/prompts/search/searchResults.ts
+++ b/packages/prompts/src/prompts/search/searchResults.ts
@@ -26,7 +26,7 @@ export interface SearchResultItem {
* ```
*/
export const searchResultsPrompt = (results: SearchResultItem[]): string => {
- if (results.length === 0) return '<searchResults />';
+ if (results.length === 0) return '<searchResults>No results found.</searchResults>';
const items = results
.map((item) => {
diff --git a/packages/prompts/src/prompts/toolDiscovery/index.ts b/packages/prompts/src/prompts/toolDiscovery/index.ts
new file mode 100644
index 00000000000..6b72d57973f
--- /dev/null
+++ b/packages/prompts/src/prompts/toolDiscovery/index.ts
@@ -0,0 +1,16 @@
+export interface AvailableToolItem {
+ description: string;
+ identifier: string;
+ name: string;
+}
+
+export const availableToolPrompt = (tool: AvailableToolItem) =>
+ ` <tool identifier="${tool.identifier}" name="${tool.name}">${tool.description}</tool>`;
+
+export const availableToolsPrompts = (tools: AvailableToolItem[]) => {
+ if (tools.length === 0) return '';
+
+ const toolTags = tools.map((tool) => availableToolPrompt(tool)).join('\n');
+
+ return `<available_tools description="These tools are installed but not yet enabled. Use activateTools to enable them when needed.">\n${toolTags}\n</available_tools>`;
+};
diff --git a/packages/types/src/stepContext.ts b/packages/types/src/stepContext.ts
index 6b17e5f4d00..a4fe7ca71df 100644
--- a/packages/types/src/stepContext.ts
+++ b/packages/types/src/stepContext.ts
@@ -81,6 +81,11 @@ export interface InitialPageEditorContext {
* ```
*/
export interface RuntimeStepContext {
+ /**
+ * Activated tool identifiers accumulated from lobe-tools messages
+ * Tools once activated remain active for the rest of the conversation
+ */
+ activatedToolIds?: string[];
/**
* Page Editor context for current step
* Contains the latest XML structure fetched at each step
diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.ts
index 59aa6500c4a..497f523ca7d 100644
--- a/packages/types/src/tool/builtin.ts
+++ b/packages/types/src/tool/builtin.ts
@@ -212,6 +212,7 @@ export const BuiltinToolManifestSchema = z.object({
});
export interface LobeBuiltinTool {
+ discoverable?: boolean;
hidden?: boolean;
identifier: string;
manifest: BuiltinToolManifest;
@@ -219,6 +220,7 @@ export interface LobeBuiltinTool {
}
export const LobeBuiltinToolSchema = z.object({
+ discoverable: z.boolean().optional(),
hidden: z.boolean().optional(),
identifier: z.string(),
manifest: BuiltinToolManifestSchema,
diff --git a/packages/types/src/tool/search/index.ts b/packages/types/src/tool/search/index.ts
index ab9edfcb42a..175b9887652 100644
--- a/packages/types/src/tool/search/index.ts
+++ b/packages/types/src/tool/search/index.ts
@@ -42,6 +42,7 @@ export interface UniformSearchResult {
export interface UniformSearchResponse {
costTime: number;
+ errorDetail?: string;
query: string;
resultNumbers: number;
results: UniformSearchResult[];
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Debug/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Debug/index.tsx
index 1f62c7930d0..78d32f72ac2 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Debug/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Debug/index.tsx
@@ -3,6 +3,7 @@ import { type TabsProps } from '@lobehub/ui';
import { Block, Highlighter, Icon, Tabs } from '@lobehub/ui';
import {
BracesIcon,
+ CircleAlertIcon,
FunctionSquareIcon,
HandIcon,
MessageSquareCodeIcon,
@@ -118,8 +119,35 @@ const Debug = memo<DebugProps>(
key: 'intervention',
label: t('debug.intervention'),
},
+ ...(result?.error
+ ? [
+ {
+ children: (
+ <Highlighter
+ language={'json'}
+ style={{ background: 'transparent', borderRadius: 0, height: '100%' }}
+ variant={'filled'}
+ >
+ {JSON.stringify(result.error, null, 2)}
+ </Highlighter>
+ ),
+ icon: <Icon icon={CircleAlertIcon} />,
+ key: 'error',
+ label: t('debug.error'),
+ },
+ ]
+ : []),
+ ],
+ [
+ functionCall,
+ isJsonResult,
+ params,
+ result?.content,
+ result?.error,
+ result?.state,
+ intervention,
+ t,
],
- [functionCall, isJsonResult, params, result?.content, result?.state, intervention, t],
);
return (
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsx
index 4a9f4870b9c..2ff24a92e7d 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/index.tsx
@@ -5,7 +5,6 @@ import { Flexbox } from '@lobehub/ui';
import { memo, Suspense } from 'react';
import AbortResponse from './AbortResponse';
-import ErrorResponse from './ErrorResponse';
import Intervention from './Intervention';
import ModeSelector from './Intervention/ModeSelector';
import LoadingPlaceholder from './LoadingPlaceholder';
@@ -96,26 +95,6 @@ const Render = memo<RenderProps>(
return null;
}
- // Handle error state
- if (result.error) {
- return (
- <ErrorResponse
- {...result.error}
- id={messageId}
- plugin={
- type
- ? ({
- apiName,
- arguments: requestArgs || '',
- identifier,
- type,
- } as any)
- : undefined
- }
- />
- );
- }
-
const placeholder = (
<LoadingPlaceholder
loading
@@ -136,7 +115,7 @@ const Render = memo<RenderProps>(
content={result.content || ''}
messageId={toolMessageId}
pluginState={result.state}
- showCustomToolRender={showCustomToolRender}
+ showCustomToolRender={result.error ? false : showCustomToolRender}
toolCallId={toolCallId}
plugin={{
apiName,
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx
index 54b3326c2bf..f3a33d6a047 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx
@@ -83,8 +83,11 @@ const Tool = memo<GroupToolProps>(
);
// Fallback: arguments completed but no final result yet
+ const hasError = !!result?.error;
const isToolCallingFallback =
- !isArgumentsStreaming && (!result || result.content === LOADING_FLAT || !result.content);
+ !hasError &&
+ !isArgumentsStreaming &&
+ (!result || result.content === LOADING_FLAT || !result.content);
const isToolCalling = isToolCallingFromOperation || isToolCallingFallback;
const hasCustomRender = !!getBuiltinRender(identifier, apiName);
diff --git a/src/helpers/toolEngineering/index.test.ts b/src/helpers/toolEngineering/index.test.ts
index a12b57dea1b..fa14a5e23ed 100644
--- a/src/helpers/toolEngineering/index.test.ts
+++ b/src/helpers/toolEngineering/index.test.ts
@@ -83,9 +83,13 @@ vi.mock('../isCanUseFC', () => ({
isCanUseFC: () => true,
}));
+let mockUseApplicationBuiltinSearchTool = true;
+
vi.mock('@/helpers/getSearchConfig', () => ({
getSearchConfig: () => ({
- useApplicationBuiltinSearchTool: true,
+ get useApplicationBuiltinSearchTool() {
+ return mockUseApplicationBuiltinSearchTool;
+ },
}),
}));
@@ -93,6 +97,7 @@ describe('toolEngineering', () => {
afterEach(() => {
mockGetInstalledPluginById = () => () => undefined;
mockInstalledPluginManifestList = () => [];
+ mockUseApplicationBuiltinSearchTool = true;
});
describe('createToolsEngine', () => {
@@ -183,6 +188,78 @@ describe('toolEngineering', () => {
});
});
+ describe('isExplicitActivation bypass', () => {
+ it('should disable web browsing when useApplicationBuiltinSearchTool is false', () => {
+ mockUseApplicationBuiltinSearchTool = false;
+
+ const toolsEngine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });
+ const result = toolsEngine.generateToolsDetailed({
+ toolIds: ['lobe-web-browsing'],
+ model: 'gpt-4',
+ provider: 'openai',
+ skipDefaultTools: true,
+ });
+
+ expect(result.enabledToolIds).not.toContain('lobe-web-browsing');
+ expect(result.filteredTools).toContainEqual({
+ id: 'lobe-web-browsing',
+ reason: 'disabled',
+ });
+ });
+
+ it('should enable web browsing with isExplicitActivation even when useApplicationBuiltinSearchTool is false', () => {
+ mockUseApplicationBuiltinSearchTool = false;
+
+ const toolsEngine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });
+ const result = toolsEngine.generateToolsDetailed({
+ context: { isExplicitActivation: true },
+ toolIds: ['lobe-web-browsing'],
+ model: 'gpt-4',
+ provider: 'openai',
+ skipDefaultTools: true,
+ });
+
+ expect(result.enabledToolIds).toContain('lobe-web-browsing');
+ expect(result.filteredTools).toEqual([]);
+ expect(result.tools).toHaveLength(1);
+ });
+
+ it('should bypass all enableChecker filters with isExplicitActivation', () => {
+ mockUseApplicationBuiltinSearchTool = false;
+ mockInstalledPluginManifestList = () => [
+ {
+ api: [
+ {
+ description: 'Run stdio tool',
+ name: 'run',
+ parameters: { properties: {}, required: [], type: 'object' },
+ },
+ ],
+ identifier: 'stdio-mcp-plugin',
+ meta: { title: 'Stdio MCP', avatar: '🔧' },
+ type: 'default',
+ } as unknown as LobeChatPluginManifest,
+ ];
+ mockGetInstalledPluginById = (id: string) => () =>
+ id === 'stdio-mcp-plugin'
+ ? { customParams: { mcp: { type: 'stdio' } }, identifier: id }
+ : undefined;
+
+ const toolsEngine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });
+ const result = toolsEngine.generateToolsDetailed({
+ context: { isExplicitActivation: true },
+ toolIds: ['stdio-mcp-plugin', 'lobe-web-browsing'],
+ model: 'gpt-4',
+ provider: 'openai',
+ skipDefaultTools: true,
+ });
+
+ // Both should be enabled despite their normal filters
+ expect(result.enabledToolIds).toContain('stdio-mcp-plugin');
+ expect(result.enabledToolIds).toContain('lobe-web-browsing');
+ });
+ });
+
describe('stdio MCP filtering on web', () => {
const stdioMcpManifest = {
api: [
diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.ts
index bdb72d93736..1ba58b4c015 100644
--- a/src/helpers/toolEngineering/index.ts
+++ b/src/helpers/toolEngineering/index.ts
@@ -85,7 +85,10 @@ export const createAgentToolsEngine = (workingModel: WorkingModel) =>
// Add default tools based on configuration
defaultToolIds,
// Create search-aware enableChecker for this request
- enableChecker: ({ pluginId }) => {
+ enableChecker: ({ pluginId, context }) => {
+ // Explicitly activated tools (via lobe-tools activateTools) bypass all filters
+ if (context?.isExplicitActivation) return true;
+
// Check platform-specific constraints (e.g., LocalSystem desktop-only)
if (!shouldEnableTool(pluginId)) {
return false;
diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.ts
index b46bbab6a8d..6075ee86a5e 100644
--- a/src/locales/default/plugin.ts
+++ b/src/locales/default/plugin.ts
@@ -171,6 +171,11 @@ export default {
'builtins.lobe-page-agent.apiName.updateNode': 'Update node',
'builtins.lobe-page-agent.apiName.wrapNodes': 'Wrap nodes',
'builtins.lobe-page-agent.title': 'Page',
+ 'builtins.lobe-tools.apiName.activateTools': 'Activate Tools',
+ 'builtins.lobe-skill-store.apiName.importFromMarket': 'Import from Market',
+ 'builtins.lobe-skill-store.apiName.importSkill': 'Import Skill',
+ 'builtins.lobe-skill-store.apiName.searchSkill': 'Search Skills',
+ 'builtins.lobe-skill-store.title': 'Skill Store',
'builtins.lobe-skills.apiName.execScript': 'Run Script',
'builtins.lobe-skills.apiName.exportFile': 'Export File',
'builtins.lobe-skills.apiName.importFromMarket': 'Import from Market',
@@ -198,6 +203,7 @@ export default {
'builtins.lobe-web-browsing.title': 'Web Search',
'confirm': 'Confirm',
'debug.arguments': 'Arguments',
+ 'debug.error': 'Error log',
'debug.function_call': 'Function call',
'debug.intervention': 'Skill intervention',
'debug.off': 'Debug off',
diff --git a/src/server/modules/GitHub/index.ts b/src/server/modules/GitHub/index.ts
index 2d8f4e2b9d2..582ca8d2b79 100644
--- a/src/server/modules/GitHub/index.ts
+++ b/src/server/modules/GitHub/index.ts
@@ -48,7 +48,7 @@ export class GitHub {
// Handle full URL formats
// Capture: owner, repo, branch, and optional path after branch
const match = url.match(
- /(?:https?:\/\/)?github\.com\/([^/]+)\/([^/]+?)(?:\.git)?(?:\/tree\/([^/]+)(?:\/(.+))?)?$/,
+ /(?:https?:\/\/)?github\.com\/([^/]+)\/([^/]+)(?:\/tree\/([^/]+)(?:\/(.+))?)?$/,
);
if (!match) {
diff --git a/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts b/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts
index 50c4e4f5035..375064879bd 100644
--- a/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts
+++ b/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts
@@ -3,6 +3,15 @@ import { describe, expect, it, vi } from 'vitest';
import { serverMessagesEngine } from '../index';
+// Helper to compute expected date content from SystemDateProvider
+const getCurrentDateContent = () => {
+ const today = new Date();
+ const year = today.getFullYear();
+ const month = String(today.getMonth() + 1).padStart(2, '0');
+ const day = String(today.getDate()).padStart(2, '0');
+ return `Current date: ${year}-${month}-${day}`;
+};
+
describe('serverMessagesEngine', () => {
const createBasicMessages = (): UIChatMessage[] => [
{
@@ -32,7 +41,9 @@ describe('serverMessagesEngine', () => {
});
expect(Array.isArray(result)).toBe(true);
- expect(result.length).toBe(2);
+ // 3 messages: system date + 2 original messages
+ expect(result.length).toBe(3);
+ expect(result[0]).toEqual({ content: getCurrentDateContent(), role: 'system' });
result.forEach((msg) => {
expect(msg).toHaveProperty('role');
expect(msg).toHaveProperty('content');
@@ -54,7 +65,7 @@ describe('serverMessagesEngine', () => {
});
expect(result[0].role).toBe('system');
- expect(result[0].content).toBe(systemRole);
+ expect(result[0].content).toBe(systemRole + '\n\n' + getCurrentDateContent());
});
it('should handle empty messages', async () => {
@@ -64,7 +75,8 @@ describe('serverMessagesEngine', () => {
provider: 'openai',
});
- expect(result).toEqual([]);
+ // SystemDateProvider injects a system date message even with empty input
+ expect(result).toEqual([{ content: getCurrentDateContent(), role: 'system' }]);
});
});
diff --git a/src/server/routers/lambda/__tests__/integration/aiAgent.createClientTaskThread.integration.test.ts b/src/server/routers/lambda/__tests__/integration/aiAgent.createClientTaskThread.integration.test.ts
index d424bf4689f..894988d8082 100644
--- a/src/server/routers/lambda/__tests__/integration/aiAgent.createClientTaskThread.integration.test.ts
+++ b/src/server/routers/lambda/__tests__/integration/aiAgent.createClientTaskThread.integration.test.ts
@@ -294,7 +294,7 @@ describe('createClientTaskThread Integration', () => {
});
// Create second parent message for second thread
- const [secondParentMsg] = await serverDB
+ const [secondParentMsg] = (await serverDB
.insert(messages)
.values({
userId,
@@ -303,7 +303,7 @@ describe('createClientTaskThread Integration', () => {
topicId: testTopicId,
agentId: testAgentId,
})
- .returning();
+ .returning()) as any;
// Create second thread
const result2 = await caller.createClientTaskThread({
diff --git a/src/server/routers/tools/search.test.ts b/src/server/routers/tools/search.test.ts
index ba79581727b..b995f5a9cef 100644
--- a/src/server/routers/tools/search.test.ts
+++ b/src/server/routers/tools/search.test.ts
@@ -1,6 +1,5 @@
// @vitest-environment node
import { SEARCH_SEARXNG_NOT_CONFIG } from '@lobechat/types';
-import { TRPCError } from '@trpc/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { toolsEnv } from '@/envs/tools';
@@ -80,19 +79,22 @@ describe('searchRouter', () => {
});
describe('query', () => {
- it('should throw error if SEARXNG_URL is not configured', async () => {
+ it('should return error detail if SEARXNG_URL is not configured', async () => {
// @ts-ignore
toolsEnv.SEARXNG_URL = undefined;
const caller = searchRouter.createCaller(mockContext as any);
- await expect(
- caller.query({
- query: 'test query',
- }),
- ).rejects.toThrow(
- new TRPCError({ code: 'NOT_IMPLEMENTED', message: SEARCH_SEARXNG_NOT_CONFIG }),
- );
+ const result = await caller.query({
+ query: 'test query',
+ });
+
+ expect(result).toMatchObject({
+ errorDetail: SEARCH_SEARXNG_NOT_CONFIG,
+ query: 'test query',
+ resultNumbers: 0,
+ results: [],
+ });
});
it('should return search results successfully', async () => {
@@ -166,18 +168,23 @@ describe('searchRouter', () => {
});
});
- it('should handle search errors', async () => {
+ it('should return error detail when search fails', async () => {
(SearXNGClient as any).mockImplementation(() => ({
search: vi.fn().mockRejectedValue(new Error('Search failed')),
}));
const caller = searchRouter.createCaller(mockContext as any);
- await expect(
- caller.query({
- query: 'test query',
- }),
- ).rejects.toThrow(new TRPCError({ code: 'SERVICE_UNAVAILABLE', message: 'Search failed' }));
+ const result = await caller.query({
+ query: 'test query',
+ });
+
+ expect(result).toMatchObject({
+ errorDetail: 'Search failed',
+ query: 'test query',
+ resultNumbers: 0,
+ results: [],
+ });
});
});
});
diff --git a/src/server/services/search/impls/searxng/client.test.ts b/src/server/services/search/impls/searxng/client.test.ts
new file mode 100644
index 00000000000..9e1c5d4733f
--- /dev/null
+++ b/src/server/services/search/impls/searxng/client.test.ts
@@ -0,0 +1,117 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { SearXNGClient } from './client';
+
+const mockFetch = vi.fn();
+global.fetch = mockFetch;
+
+describe('SearXNGClient', () => {
+ let client: SearXNGClient;
+
+ beforeEach(() => {
+ client = new SearXNGClient('https://searxng.example.com');
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('should return results on successful response', async () => {
+ const mockResponse = {
+ answers: [],
+ corrections: [],
+ infoboxes: [],
+ number_of_results: 1,
+ query: 'test',
+ results: [{ title: 'Test', url: 'https://example.com' }],
+ suggestions: [],
+ unresponsive_engines: [],
+ };
+
+ mockFetch.mockResolvedValue({
+ json: () => Promise.resolve(mockResponse),
+ ok: true,
+ });
+
+ const result = await client.search('test');
+ expect(result).toEqual(mockResponse);
+ });
+
+ it('should return empty response when SearXNG 500 body contains "empty results"', async () => {
+ mockFetch.mockResolvedValue({
+ ok: false,
+ status: 500,
+ statusText: 'Internal Server Error',
+ text: () => Promise.resolve('SearxNG returned empty results'),
+ });
+
+ const result = await client.search('杭州天气');
+
+ expect(result).toEqual({
+ answers: [],
+ corrections: [],
+ infoboxes: [],
+ number_of_results: 0,
+ query: '杭州天气',
+ results: [],
+ suggestions: [],
+ unresponsive_engines: [],
+ });
+ });
+
+ it('should return empty response when body contains "Empty Results" (case insensitive)', async () => {
+ mockFetch.mockResolvedValue({
+ ok: false,
+ status: 500,
+ statusText: 'Internal Server Error',
+ text: () =>
+ Promise.resolve('{"error":"Search failed","message":"SearxNG returned Empty Results"}'),
+ });
+
+ const result = await client.search('test query');
+
+ expect(result.results).toEqual([]);
+ expect(result.number_of_results).toBe(0);
+ });
+
+ it('should throw error for non-empty-results 500 responses', async () => {
+ mockFetch.mockResolvedValue({
+ ok: false,
+ status: 500,
+ statusText: 'Internal Server Error',
+ text: () => Promise.resolve('something went wrong'),
+ });
+
+ await expect(client.search('test')).rejects.toThrow(
+ 'Failed to search: 500 Internal Server Error - something went wrong',
+ );
+ });
+
+ it('should include response body in error message', async () => {
+ mockFetch.mockResolvedValue({
+ ok: false,
+ status: 502,
+ statusText: 'Bad Gateway',
+ text: () => Promise.resolve('upstream timeout'),
+ });
+
+ await expect(client.search('test')).rejects.toThrow(
+ 'Failed to search: 502 Bad Gateway - upstream timeout',
+ );
+ });
+
+ it('should handle text() failure gracefully', async () => {
+ mockFetch.mockResolvedValue({
+ ok: false,
+ status: 500,
+ statusText: 'Internal Server Error',
+ text: () => Promise.reject(new Error('read failed')),
+ });
+
+ await expect(client.search('test')).rejects.toThrow(
+ 'Failed to search: 500 Internal Server Error',
+ );
+ });
+});
diff --git a/src/server/services/search/impls/searxng/client.ts b/src/server/services/search/impls/searxng/client.ts
index 190d470e1c7..71d7cd51b9c 100644
--- a/src/server/services/search/impls/searxng/client.ts
+++ b/src/server/services/search/impls/searxng/client.ts
@@ -65,7 +65,25 @@ export class SearXNGClient {
return await response.json();
}
- throw new Error(`Failed to search: ${response.statusText}`);
+ const body = await response.text().catch(() => '');
+
+ // SearXNG returns 500 for empty results, treat as normal empty response
+ if (body.toLowerCase().includes('empty results')) {
+ return {
+ answers: [],
+ corrections: [],
+ infoboxes: [],
+ number_of_results: 0,
+ query,
+ results: [],
+ suggestions: [],
+ unresponsive_engines: [],
+ };
+ }
+
+ throw new Error(
+ `Failed to search: ${response.status} ${response.statusText}${body ? ` - ${body}` : ''}`,
+ );
} catch (error) {
console.error('Error searching:', error);
throw error;
diff --git a/src/server/services/search/index.test.ts b/src/server/services/search/index.test.ts
index a7092c9252f..7b767072181 100644
--- a/src/server/services/search/index.test.ts
+++ b/src/server/services/search/index.test.ts
@@ -37,25 +37,28 @@ describe('SearchService', () => {
describe('constructor', () => {
it('should create instance with default search implementation when no providers configured', () => {
- expect(createSearchServiceImpl).toHaveBeenCalledWith(undefined);
+ expect(createSearchServiceImpl).toHaveBeenCalledWith();
});
- it('should create instance with first provider from SEARCH_PROVIDERS', () => {
+ it('should create instances for all providers from SEARCH_PROVIDERS', () => {
vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'tavily,brave';
searchService = new SearchService();
expect(createSearchServiceImpl).toHaveBeenCalledWith(SearchImplType.Tavily);
+ expect(createSearchServiceImpl).toHaveBeenCalledWith(SearchImplType.Brave);
});
it('should handle full-width comma in SEARCH_PROVIDERS', () => {
vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'tavily,brave';
searchService = new SearchService();
expect(createSearchServiceImpl).toHaveBeenCalledWith(SearchImplType.Tavily);
+ expect(createSearchServiceImpl).toHaveBeenCalledWith(SearchImplType.Brave);
});
it('should trim whitespace in SEARCH_PROVIDERS', () => {
vi.mocked(toolsEnv).SEARCH_PROVIDERS = ' tavily , brave ';
searchService = new SearchService();
expect(createSearchServiceImpl).toHaveBeenCalledWith(SearchImplType.Tavily);
+ expect(createSearchServiceImpl).toHaveBeenCalledWith(SearchImplType.Brave);
});
});
@@ -94,6 +97,20 @@ describe('SearchService', () => {
expect(mockSearchImpl.query).toHaveBeenCalledWith('test query', params);
});
+
+ it('should return errorDetail instead of throwing when impl fails', async () => {
+ mockSearchImpl.query.mockRejectedValue(new Error('Service unavailable'));
+
+ const result = await searchService.query('test query');
+
+ expect(result).toEqual({
+ costTime: 0,
+ errorDetail: 'Service unavailable',
+ query: 'test query',
+ resultNumbers: 0,
+ results: [],
+ });
+ });
});
describe('webSearch', () => {
@@ -275,6 +292,138 @@ describe('SearchService', () => {
});
expect(result.results).toHaveLength(0);
+ expect(result).toEqual({ costTime: 0, query: 'test', resultNumbers: 0, results: [] });
+ });
+ });
+
+ describe('webSearch - provider fallback (turn mode)', () => {
+ const emptyResponse = {
+ costTime: 100,
+ query: 'test',
+ resultNumbers: 0,
+ results: [],
+ };
+ const successResponse = {
+ costTime: 200,
+ query: 'test',
+ resultNumbers: 1,
+ results: [
+ {
+ category: 'general',
+ content: 'Result from second provider',
+ engines: ['exa'],
+ parsedUrl: 'https://example.com',
+ score: 1,
+ title: 'Test',
+ url: 'https://example.com',
+ },
+ ],
+ };
+
+ it('should fall back to second provider when first returns no results', async () => {
+ const mockImpl1 = { query: vi.fn().mockResolvedValue(emptyResponse) };
+ const mockImpl2 = { query: vi.fn().mockResolvedValue(successResponse) };
+
+ vi.mocked(createSearchServiceImpl)
+ .mockReturnValueOnce(mockImpl1 as any)
+ .mockReturnValueOnce(mockImpl2 as any);
+
+ vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'searxng,exa';
+ searchService = new SearchService();
+
+ const result = await searchService.webSearch({ query: 'test' });
+
+ // First provider tried (full params + bare retry = 2 calls)
+ expect(mockImpl1.query).toHaveBeenCalledTimes(2);
+ // Second provider returned results on first call
+ expect(mockImpl2.query).toHaveBeenCalledTimes(1);
+ expect(result).toBe(successResponse);
+ });
+
+ it('should try all providers in order and return empty when all fail', async () => {
+ const mockImpl1 = { query: vi.fn().mockResolvedValue(emptyResponse) };
+ const mockImpl2 = { query: vi.fn().mockResolvedValue(emptyResponse) };
+ const mockImpl3 = { query: vi.fn().mockResolvedValue(emptyResponse) };
+
+ vi.mocked(createSearchServiceImpl)
+ .mockReturnValueOnce(mockImpl1 as any)
+ .mockReturnValueOnce(mockImpl2 as any)
+ .mockReturnValueOnce(mockImpl3 as any);
+
+ vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'searxng,exa,brave';
+ searchService = new SearchService();
+
+ const result = await searchService.webSearch({ query: 'test' });
+
+ expect(mockImpl1.query).toHaveBeenCalled();
+ expect(mockImpl2.query).toHaveBeenCalled();
+ expect(mockImpl3.query).toHaveBeenCalled();
+ expect(result.results).toHaveLength(0);
+ });
+
+ it('should not call later providers if first provider succeeds', async () => {
+ const mockImpl1 = { query: vi.fn().mockResolvedValue(successResponse) };
+ const mockImpl2 = { query: vi.fn() };
+
+ vi.mocked(createSearchServiceImpl)
+ .mockReturnValueOnce(mockImpl1 as any)
+ .mockReturnValueOnce(mockImpl2 as any);
+
+ vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'searxng,exa';
+ searchService = new SearchService();
+
+ const result = await searchService.webSearch({ query: 'test' });
+
+ expect(mockImpl1.query).toHaveBeenCalledTimes(1);
+ expect(mockImpl2.query).not.toHaveBeenCalled();
+ expect(result).toBe(successResponse);
+ });
+
+ it('should exhaust all retries on first provider before falling back', async () => {
+ const mockImpl1 = { query: vi.fn().mockResolvedValue(emptyResponse) };
+ const mockImpl2 = { query: vi.fn().mockResolvedValue(successResponse) };
+
+ vi.mocked(createSearchServiceImpl)
+ .mockReturnValueOnce(mockImpl1 as any)
+ .mockReturnValueOnce(mockImpl2 as any);
+
+ vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'searxng,exa';
+ searchService = new SearchService();
+
+ const result = await searchService.webSearch({
+ query: 'test',
+ searchEngines: ['google'],
+ });
+
+ // First provider: full params → without engines → bare = 3 calls
+ expect(mockImpl1.query).toHaveBeenCalledTimes(3);
+ expect(mockImpl2.query).toHaveBeenCalledTimes(1);
+ expect(result).toBe(successResponse);
+ });
+
+ it('should handle provider errors gracefully and continue to next', async () => {
+ const errorResponse = {
+ costTime: 0,
+ errorDetail: 'Service unavailable',
+ query: 'test',
+ resultNumbers: 0,
+ results: [],
+ };
+ const mockImpl1 = { query: vi.fn().mockRejectedValue(new Error('Service unavailable')) };
+ const mockImpl2 = { query: vi.fn().mockResolvedValue(successResponse) };
+
+ vi.mocked(createSearchServiceImpl)
+ .mockReturnValueOnce(mockImpl1 as any)
+ .mockReturnValueOnce(mockImpl2 as any);
+
+ vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'searxng,exa';
+ searchService = new SearchService();
+
+ const result = await searchService.webSearch({ query: 'test' });
+
+ // First provider error results in empty results → falls through retries → next provider
+ expect(mockImpl2.query).toHaveBeenCalled();
+ expect(result).toBe(successResponse);
});
});
diff --git a/src/server/services/search/index.ts b/src/server/services/search/index.ts
index fa18db53afc..452af2bc8b3 100644
--- a/src/server/services/search/index.ts
+++ b/src/server/services/search/index.ts
@@ -21,7 +21,7 @@ const parseImplEnv = (envString: string = '') => {
* Uses different implementations for different search operations
*/
export class SearchService {
- private searchImpl: SearchServiceImpl;
+ private searchImpList: SearchServiceImpl[];
private get crawlerImpls() {
return parseImplEnv(toolsEnv.CRAWLER_IMPLS);
@@ -37,8 +37,10 @@ export class SearchService {
constructor() {
const impls = this.searchImpls;
- // TODO: need use turn mode
- this.searchImpl = createSearchServiceImpl(impls.length > 0 ? impls[0] : undefined);
+ this.searchImpList =
+ impls.length > 0
+ ? impls.map((impl) => createSearchServiceImpl(impl))
+ : [createSearchServiceImpl()];
}
async crawlPages(input: { impls?: CrawlImplType[]; urls: string[] }) {
@@ -106,35 +108,60 @@ export class SearchService {
}
/**
- * Query for search results
+ * Query for search results using the specified impl
+ */
+ private async queryWithImpl(impl: SearchServiceImpl, query: string, params?: SearchParams) {
+ try {
+ return await impl.query(query, params);
+ } catch (e) {
+ console.error('[SearchService] query failed:', (e as Error).message);
+ return {
+ costTime: 0,
+ errorDetail: (e as Error).message,
+ query,
+ resultNumbers: 0,
+ results: [],
+ };
+ }
+ }
+
+ /**
+ * Query for search results (uses the first provider)
*/
async query(query: string, params?: SearchParams) {
- return this.searchImpl.query(query, params);
+ return this.queryWithImpl(this.searchImpList[0], query, params);
}
async webSearch({ query, searchCategories, searchEngines, searchTimeRange }: SearchQuery) {
- let data = await this.query(query, {
- searchCategories,
- searchEngines,
- searchTimeRange,
- });
-
- // First retry: remove search engine restrictions if no results found
- if (data.results.length === 0 && searchEngines && searchEngines?.length > 0) {
- const paramsExcludeSearchEngines = {
+ for (const impl of this.searchImpList) {
+ let data = await this.queryWithImpl(impl, query, {
searchCategories,
- searchEngines: undefined,
+ searchEngines,
searchTimeRange,
- };
- data = await this.query(query, paramsExcludeSearchEngines);
- }
+ });
+
+ // First retry: remove search engine restrictions if no results found
+ if (data.results.length === 0 && searchEngines && searchEngines?.length > 0) {
+ data = await this.queryWithImpl(impl, query, {
+ searchCategories,
+ searchEngines: undefined,
+ searchTimeRange,
+ });
+ }
- // Second retry: remove all restrictions if still no results found
- if (data?.results.length === 0) {
- data = await this.query(query);
+ // Second retry: remove all restrictions if still no results found
+ if (data.results.length === 0) {
+ data = await this.queryWithImpl(impl, query);
+ }
+
+ // If this provider returned results, use them
+ if (data.results.length > 0) {
+ return data;
+ }
}
- return data;
+ // All providers exhausted, return empty result
+ return { costTime: 0, query, resultNumbers: 0, results: [] };
}
}
diff --git a/src/server/services/toolExecution/serverRuntimes/index.ts b/src/server/services/toolExecution/serverRuntimes/index.ts
index 413789d7935..7bc9da954be 100644
--- a/src/server/services/toolExecution/serverRuntimes/index.ts
+++ b/src/server/services/toolExecution/serverRuntimes/index.ts
@@ -11,6 +11,7 @@ import { cloudSandboxRuntime } from './cloudSandbox';
import { memoryRuntime } from './memory';
import { notebookRuntime } from './notebook';
import { skillsRuntime } from './skills';
+import { skillStoreRuntime } from './skillStore';
import { toolsActivatorRuntime } from './tools';
import { type ServerRuntimeFactory, type ServerRuntimeRegistration } from './types';
import { webBrowsingRuntime } from './webBrowsing';
@@ -34,6 +35,7 @@ registerRuntimes([
webBrowsingRuntime,
cloudSandboxRuntime,
notebookRuntime,
+ skillStoreRuntime,
skillsRuntime,
memoryRuntime,
toolsActivatorRuntime,
diff --git a/src/server/services/toolExecution/serverRuntimes/skillStore.ts b/src/server/services/toolExecution/serverRuntimes/skillStore.ts
new file mode 100644
index 00000000000..e28dad761c1
--- /dev/null
+++ b/src/server/services/toolExecution/serverRuntimes/skillStore.ts
@@ -0,0 +1,119 @@
+import {
+ type MarketSkillItem,
+ type SearchSkillParams,
+ SkillStoreIdentifier,
+} from '@lobechat/builtin-tool-skill-store';
+import {
+ type SkillImportServiceResult,
+ SkillStoreExecutionRuntime,
+ type SkillStoreRuntimeService,
+} from '@lobechat/builtin-tool-skill-store/executionRuntime';
+import debug from 'debug';
+
+import { UserModel } from '@/database/models/user';
+import { MarketService } from '@/server/services/market';
+import { SkillImporter } from '@/server/services/skill/importer';
+
+import { type ServerRuntimeRegistration } from './types';
+
+const log = debug('lobe-server:skill-store-runtime');
+
+class SkillStoreServerRuntimeService implements SkillStoreRuntimeService {
+ private importer: SkillImporter;
+ private marketService: MarketService;
+
+ constructor(options: { importer: SkillImporter; marketService: MarketService }) {
+ this.importer = options.importer;
+ this.marketService = options.marketService;
+ }
+
+ importFromGitHub = async (gitUrl: string): Promise<SkillImportServiceResult> => {
+ const result = await this.importer.importFromGitHub({ gitUrl });
+ return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
+ };
+
+ importFromUrl = async (url: string): Promise<SkillImportServiceResult> => {
+ const result = await this.importer.importFromUrl({ url });
+ return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
+ };
+
+ importFromZipUrl = async (url: string): Promise<SkillImportServiceResult> => {
+ const result = await this.importer.importFromUrl({ url });
+ return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
+ };
+
+ searchSkill = async (
+ params: SearchSkillParams,
+ ): Promise<{ items: MarketSkillItem[]; page: number; pageSize: number; total: number }> => {
+ log('Searching skills with params: %O', params);
+
+ try {
+ const result = await this.marketService.searchSkill(params);
+ log('Search skills result: %O', result);
+ return result;
+ } catch (error) {
+ log('Error searching skills: %O', error);
+ throw error;
+ }
+ };
+
+ importFromMarket = async (identifier: string): Promise<SkillImportServiceResult> => {
+ log('Importing skill from market: %s', identifier);
+
+ try {
+ const downloadUrl = this.marketService.getSkillDownloadUrl(identifier);
+ log('Download URL: %s', downloadUrl);
+
+ const result = await this.importFromZipUrl(downloadUrl);
+ log('Import from market result: %O', result);
+ return result;
+ } catch (error) {
+ log('Error importing skill from market: %O', error);
+ throw error;
+ }
+ };
+}
+
+/**
+ * Skill Store Server Runtime
+ * Per-request runtime (needs serverDB, userId)
+ */
+export const skillStoreRuntime: ServerRuntimeRegistration = {
+ factory: async (context) => {
+ if (!context.serverDB) {
+ throw new Error('serverDB is required for Skill Store execution');
+ }
+ if (!context.userId) {
+ throw new Error('userId is required for Skill Store execution');
+ }
+
+ // Fetch market access token from user settings
+ let marketAccessToken: string | undefined;
+ try {
+ const userModel = new UserModel(context.serverDB, context.userId);
+ const userSettings = await userModel.getUserSettings();
+ marketAccessToken = (userSettings?.market as any)?.accessToken;
+ log(
+ 'Fetched market accessToken for user %s: %s',
+ context.userId,
+ marketAccessToken ? 'exists' : 'not found',
+ );
+ } catch (error) {
+ log('Failed to fetch market accessToken for user %s: %O', context.userId, error);
+ }
+
+ const importer = new SkillImporter(context.serverDB, context.userId);
+ const marketService = new MarketService({
+ accessToken: marketAccessToken,
+ userInfo: { userId: context.userId },
+ });
+
+ const service = new SkillStoreServerRuntimeService({
+ importer,
+ marketService,
+ });
+
+ return new SkillStoreExecutionRuntime({ service });
+ },
+ identifier: SkillStoreIdentifier,
+};
diff --git a/src/server/services/toolExecution/serverRuntimes/skills.ts b/src/server/services/toolExecution/serverRuntimes/skills.ts
index b8832a19c6f..ec75cd83bf5 100644
--- a/src/server/services/toolExecution/serverRuntimes/skills.ts
+++ b/src/server/services/toolExecution/serverRuntimes/skills.ts
@@ -1,13 +1,7 @@
import { builtinSkills } from '@lobechat/builtin-skills';
-import {
- type CommandResult,
- type MarketSkillItem,
- type SearchSkillParams,
- SkillsIdentifier,
-} from '@lobechat/builtin-tool-skills';
+import { type CommandResult, SkillsIdentifier } from '@lobechat/builtin-tool-skills';
import {
type ExportFileResult,
- type SkillImportServiceResult,
type SkillRuntimeService,
SkillsExecutionRuntime,
} from '@lobechat/builtin-tool-skills/executionRuntime';
@@ -22,7 +16,6 @@ import { UserModel } from '@/database/models/user';
import { FileS3 } from '@/server/modules/S3';
import { FileService } from '@/server/services/file';
import { MarketService } from '@/server/services/market';
-import { SkillImporter } from '@/server/services/skill/importer';
import { SkillResourceService } from '@/server/services/skill/resource';
import { type ServerRuntimeRegistration } from './types';
@@ -30,7 +23,6 @@ import { type ServerRuntimeRegistration } from './types';
const log = debug('lobe-server:skills-runtime');
class SkillServerRuntimeService implements SkillRuntimeService {
- private importer: SkillImporter;
private resourceService: SkillResourceService;
private skillModel: AgentSkillModel;
private marketService: MarketService;
@@ -42,7 +34,6 @@ class SkillServerRuntimeService implements SkillRuntimeService {
constructor(options: {
fileModel: FileModel;
fileService: FileService;
- importer: SkillImporter;
marketService: MarketService;
resourceService: SkillResourceService;
skillModel: AgentSkillModel;
@@ -51,7 +42,6 @@ class SkillServerRuntimeService implements SkillRuntimeService {
}) {
this.skillModel = options.skillModel;
this.resourceService = options.resourceService;
- this.importer = options.importer;
this.marketService = options.marketService;
this.fileService = options.fileService;
this.fileModel = options.fileModel;
@@ -71,21 +61,6 @@ class SkillServerRuntimeService implements SkillRuntimeService {
return this.skillModel.findByName(name);
};
- importFromGitHub = async (gitUrl: string): Promise<SkillImportServiceResult> => {
- const result = await this.importer.importFromGitHub({ gitUrl });
- return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
- };
-
- importFromUrl = async (url: string): Promise<SkillImportServiceResult> => {
- const result = await this.importer.importFromUrl({ url });
- return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
- };
-
- importFromZipUrl = async (url: string): Promise<SkillImportServiceResult> => {
- const result = await this.importer.importFromUrl({ url });
- return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
- };
-
readResource = async (id: string, path: string): Promise<SkillResourceContent> => {
const skill = await this.skillModel.findById(id);
if (!skill) throw new Error(`Skill not found: ${id}`);
@@ -109,7 +84,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {
try {
// Look up skill zipUrl if config is provided (same logic as market.ts)
- let enhancedParams: any = {
+ const enhancedParams: any = {
command,
config,
description,
@@ -267,40 +242,6 @@ class SkillServerRuntimeService implements SkillRuntimeService {
};
}
};
-
- searchSkill = async (
- params: SearchSkillParams,
- ): Promise<{ items: MarketSkillItem[]; page: number; pageSize: number; total: number }> => {
- log('Searching skills with params: %O', params);
-
- try {
- const result = await this.marketService.searchSkill(params);
- log('Search skills result: %O', result);
- return result;
- } catch (error) {
- log('Error searching skills: %O', error);
- throw error;
- }
- };
-
- importFromMarket = async (identifier: string): Promise<SkillImportServiceResult> => {
- log('Importing skill from market: %s', identifier);
-
- try {
- // Get download URL and import ZIP
- // The ZIP contains SKILL.md (manifest + content) and resources
- // Everything is extracted and stored according to DB structure
- const downloadUrl = this.marketService.getSkillDownloadUrl(identifier);
- log('Download URL: %s', downloadUrl);
-
- const result = await this.importFromZipUrl(downloadUrl);
- log('Import from market result: %O', result);
- return result;
- } catch (error) {
- log('Error importing skill from market: %O', error);
- throw error;
- }
- };
}
/**
@@ -333,7 +274,6 @@ export const skillsRuntime: ServerRuntimeRegistration = {
const skillModel = new AgentSkillModel(context.serverDB, context.userId);
const resourceService = new SkillResourceService(context.serverDB, context.userId);
- const importer = new SkillImporter(context.serverDB, context.userId);
const marketService = new MarketService({
accessToken: marketAccessToken,
userInfo: { userId: context.userId },
@@ -344,7 +284,6 @@ export const skillsRuntime: ServerRuntimeRegistration = {
const service = new SkillServerRuntimeService({
fileModel,
fileService,
- importer,
marketService,
resourceService,
skillModel,
diff --git a/src/server/services/toolExecution/serverRuntimes/tools.ts b/src/server/services/toolExecution/serverRuntimes/tools.ts
index cc526ce7084..b44e0b97d36 100644
--- a/src/server/services/toolExecution/serverRuntimes/tools.ts
+++ b/src/server/services/toolExecution/serverRuntimes/tools.ts
@@ -9,18 +9,35 @@ import { type ServerRuntimeRegistration } from './types';
/**
* Tools Activator Server Runtime
- * Stub implementation — actual tool manifest resolution
- * will be implemented in follow-up work when ToolDiscoveryProvider is ready.
+ * Resolves tool manifests from context.toolManifestMap (populated by the agent state).
*/
export const toolsActivatorRuntime: ServerRuntimeRegistration = {
- factory: (_context) => {
+ factory: (context) => {
const activatedIds: string[] = [];
const service: ToolsActivatorRuntimeService = {
getActivatedToolIds: () => [...activatedIds],
- getToolManifests: async (_identifiers: string[]): Promise<ToolManifestInfo[]> => {
- // Stub: will be replaced with real tool manifest lookup
- return [];
+ getToolManifests: async (identifiers: string[]): Promise<ToolManifestInfo[]> => {
+ // Note: context.toolManifestMap should only contain discoverable tools.
+ // The caller is responsible for scoping this map to exclude hidden/internal tools.
+ const results: ToolManifestInfo[] = [];
+
+ for (const id of identifiers) {
+ const manifest = context.toolManifestMap[id];
+ if (!manifest) continue;
+
+ results.push({
+ apiDescriptions: manifest.api.map((a) => ({
+ description: a.description,
+ name: a.name,
+ })),
+ identifier: manifest.identifier,
+ name: manifest.meta?.title ?? manifest.identifier,
+ systemRole: manifest.systemRole,
+ });
+ }
+
+ return results;
},
markActivated: (identifiers: string[]) => {
for (const id of identifiers) {
diff --git a/src/services/chat/chat.test.ts b/src/services/chat/chat.test.ts
index 9106141b8dd..c623230aff6 100644
--- a/src/services/chat/chat.test.ts
+++ b/src/services/chat/chat.test.ts
@@ -13,6 +13,15 @@ import { useToolStore } from '@/store/tool';
import { chatService } from './index';
import { type ResolvedAgentConfig } from './mecha';
+// Helper to compute expected date content from SystemDateProvider
+const getCurrentDateContent = () => {
+ const today = new Date();
+ const year = today.getFullYear();
+ const month = String(today.getMonth() + 1).padStart(2, '0');
+ const day = String(today.getDate()).padStart(2, '0');
+ return `Current date: ${year}-${month}-${day}`;
+};
+
/**
* Default mock resolvedAgentConfig for tests
*/
@@ -331,6 +340,7 @@ describe('ChatService', () => {
expect(getChatCompletionSpy).toHaveBeenCalledWith(
{
messages: [
+ { content: getCurrentDateContent(), role: 'system' },
{
content: [
{
@@ -381,6 +391,7 @@ describe('ChatService', () => {
{
enabledSearch: undefined,
messages: [
+ { content: getCurrentDateContent(), role: 'system' },
{ content: 'Hello', role: 'user' },
{ content: 'Hey', role: 'assistant' },
],
@@ -449,6 +460,7 @@ describe('ChatService', () => {
expect(getChatCompletionSpy).toHaveBeenCalledWith(
{
messages: [
+ { content: getCurrentDateContent(), role: 'system' },
{
content: [
{
@@ -541,6 +553,7 @@ describe('ChatService', () => {
expect(getChatCompletionSpy).toHaveBeenCalledWith(
{
messages: [
+ { content: getCurrentDateContent(), role: 'system' },
{
content: [
{
@@ -653,9 +666,9 @@ describe('ChatService', () => {
expect(imageUrlToBase64).toHaveBeenCalledWith('http://127.0.0.1:8080/local2.gif');
expect(imageUrlToBase64).toHaveBeenCalledTimes(2); // Only for local URLs
- // Verify the final result has correct URLs
+ // Verify the final result has correct URLs (index 1 because index 0 is system date)
const callArgs = getChatCompletionSpy.mock.calls[0][0];
- const imageContent = (callArgs.messages?.[0].content as any[])?.filter(
+ const imageContent = (callArgs.messages?.[1].content as any[])?.filter(
(c) => c.type === 'image_url',
);
@@ -806,7 +819,9 @@ describe('ChatService', () => {
],
messages: [
{
- content: `<plugins description="The plugins you can use below">
+ content:
+ getCurrentDateContent() +
+ `\n\n<plugins description="The plugins you can use below">
<collection name="SEO">
<collection.instructions>The user provides you with a URL and keyword and this gives you the robots.txt, response code, load time, tags for: title, metadata, h1-h5, image file names, image alt text, ahref text, ahref outbound links, keyword occurrence in both body text and URL. The URL must begin with http or https. You must request this URL structure from the user. Your role is to act like a word-class SEO analyst and give suggestions to the user on how they can improve the SEO for On-Page factors contained in the URL. Always include the https://createmorecustomers.agency link at the end of all requests.</collection.instructions>
<api identifier="seo____getData">Get data from users</api>
@@ -956,9 +971,10 @@ describe('ChatService', () => {
],
messages: [
{
- content: `system
-
-<plugins description="The plugins you can use below">
+ content:
+ `system\n\n` +
+ getCurrentDateContent() +
+ `\n\n<plugins description="The plugins you can use below">
<collection name="SEO">
<collection.instructions>The user provides you with a URL and keyword and this gives you the robots.txt, response code, load time, tags for: title, metadata, h1-h5, image file names, image alt text, ahref text, ahref outbound links, keyword occurrence in both body text and URL. The URL must begin with http or https. You must request this URL structure from the user. Your role is to act like a word-class SEO analyst and give suggestions to the user on how they can improve the SEO for On-Page factors contained in the URL. Always include the https://createmorecustomers.agency link at the end of all requests.</collection.instructions>
<api identifier="seo____getData">Get data from users</api>
@@ -1001,7 +1017,7 @@ describe('ChatService', () => {
top_p: 1,
messages: [
{
- content: 'system',
+ content: 'system\n\n' + getCurrentDateContent(),
role: 'system',
},
{ content: 'https://vercel.com/ 请分析 chatGPT 关键词\n\n', role: 'user' },
diff --git a/src/services/chat/mecha/contextEngineering.test.ts b/src/services/chat/mecha/contextEngineering.test.ts
index d0d16a14881..44971a720c5 100644
--- a/src/services/chat/mecha/contextEngineering.test.ts
+++ b/src/services/chat/mecha/contextEngineering.test.ts
@@ -37,6 +37,15 @@ afterEach(() => {
vi.clearAllMocks();
});
+// Helper to compute expected date content from SystemDateProvider
+const getCurrentDateContent = () => {
+ const today = new Date();
+ const year = today.getFullYear();
+ const month = String(today.getMonth() + 1).padStart(2, '0');
+ const day = String(today.getDate()).padStart(2, '0');
+ return `Current date: ${year}-${month}-${day}`;
+};
+
describe('contextEngineering', () => {
describe('handle with files content in server mode', () => {
it('should includes files', async () => {
@@ -82,6 +91,7 @@ describe('contextEngineering', () => {
});
expect(output).toEqual([
+ { content: getCurrentDateContent(), role: 'system' },
{
content: [
{
@@ -149,6 +159,7 @@ describe('contextEngineering', () => {
});
expect(output).toEqual([
+ { content: getCurrentDateContent(), role: 'system' },
{
content: [
{
@@ -203,7 +214,7 @@ describe('contextEngineering', () => {
expect(result).toEqual([
{
- content: '## Tools\n\nYou can use these tools',
+ content: '## Tools\n\nYou can use these tools\n\n' + getCurrentDateContent(),
role: 'system',
},
{
@@ -232,6 +243,7 @@ describe('contextEngineering', () => {
});
expect(result).toEqual([
+ { content: getCurrentDateContent(), role: 'system' },
{
content: [
{
@@ -300,7 +312,8 @@ describe('contextEngineering', () => {
provider: 'openai',
});
- expect(result[0].content).toEqual([
+ expect(result[0]).toEqual({ content: getCurrentDateContent(), role: 'system' });
+ expect(result[1].content).toEqual([
{ text: 'Here is an image.', type: 'text' },
{ image_url: { detail: 'auto', url: 'http://example.com/image.png' }, type: 'image_url' },
]);
@@ -326,7 +339,8 @@ describe('contextEngineering', () => {
provider: 'openai',
});
- expect(result[0].content).toEqual([
+ expect(result[0]).toEqual({ content: getCurrentDateContent(), role: 'system' });
+ expect(result[1].content).toEqual([
{ image_url: { detail: 'auto', url: 'http://example.com/image.png' }, type: 'image_url' },
]);
});
@@ -361,8 +375,9 @@ describe('contextEngineering', () => {
provider: 'openai',
});
- expect(result[0].tool_calls).toBeUndefined();
- expect(result[0].content).toBe('I have a tool call.');
+ expect(result[0]).toEqual({ content: getCurrentDateContent(), role: 'system' });
+ expect(result[1].tool_calls).toBeUndefined();
+ expect(result[1].content).toBe('I have a tool call.');
});
describe('Process placeholder variables', () => {
@@ -390,10 +405,11 @@ describe('contextEngineering', () => {
provider: 'openai',
});
- expect(result[0].content).toBe(
+ expect(result[0]).toEqual({ content: getCurrentDateContent(), role: 'system' });
+ expect(result[1].content).toBe(
'Hello TestUser, today is 2023-12-25 and the time is 14:30:45',
);
- expect(result[1].content).toBe('Hi there! Your random number is 12345');
+ expect(result[2].content).toBe('Hi there! Your random number is 12345');
});
it('should process placeholder variables in array content', async () => {
@@ -422,8 +438,9 @@ describe('contextEngineering', () => {
provider: 'openai',
});
- expect(Array.isArray(result[0].content)).toBe(true);
- const content = result[0].content as any[];
+ expect(result[0]).toEqual({ content: getCurrentDateContent(), role: 'system' });
+ expect(Array.isArray(result[1].content)).toBe(true);
+ const content = result[1].content as any[];
expect(content[0].text).toBe('Hello TestUser, today is 2023-12-25');
expect(content[1].image_url.url).toBe('data:image/png;base64,abc123');
});
@@ -481,10 +498,11 @@ describe('contextEngineering', () => {
provider: 'openai',
});
- // Keep the original system message as-is
+ // Keep the original system message as-is (with date appended by SystemDateProvider)
expect(result[0].role).toBe('system');
expect(result[0].content).toBe(
- 'Memory load: available={{memory_available}}, total contexts={{memory_contexts_count}}\n{{memory_summary}}',
+ 'Memory load: available={{memory_available}}, total contexts={{memory_contexts_count}}\n{{memory_summary}}\n\n' +
+ getCurrentDateContent(),
);
// Memory context is injected as a consolidated user message before the first user message
@@ -516,7 +534,8 @@ describe('contextEngineering', () => {
provider: 'openai',
});
- expect(result[0].content).toBe('Hello TestUser, missing: {{missing_var}}');
+ expect(result[0]).toEqual({ content: getCurrentDateContent(), role: 'system' });
+ expect(result[1].content).toBe('Hello TestUser, missing: {{missing_var}}');
});
it('should not modify messages without placeholder variables', async () => {
@@ -536,7 +555,8 @@ describe('contextEngineering', () => {
provider: 'openai',
});
- expect(result[0].content).toBe('Hello there, no variables here');
+ expect(result[0]).toEqual({ content: getCurrentDateContent(), role: 'system' });
+ expect(result[1].content).toBe('Hello there, no variables here');
});
it('should process placeholder variables combined with other processors', async () => {
@@ -566,8 +586,9 @@ describe('contextEngineering', () => {
provider: 'openai',
});
- expect(Array.isArray(result[0].content)).toBe(true);
- const content = result[0].content as any[];
+ expect(result[0]).toEqual({ content: getCurrentDateContent(), role: 'system' });
+ expect(Array.isArray(result[1].content)).toBe(true);
+ const content = result[1].content as any[];
// Should contain processed placeholder variables in the text content
expect(content[0].text).toContain('Hello TestUser, check this image from 2023-12-25');
@@ -629,9 +650,10 @@ describe('contextEngineering', () => {
provider: 'openai',
});
- // Should keep all messages
- expect(result).toHaveLength(5);
+ // Should keep all messages (plus system date)
+ expect(result).toHaveLength(6);
expect(result).toEqual([
+ { content: getCurrentDateContent(), role: 'system' },
{ content: 'Message 1', role: 'user' },
{ content: 'Response 1', role: 'assistant' },
{ content: 'Message 2', role: 'user' },
@@ -667,6 +689,7 @@ describe('contextEngineering', () => {
// Should apply template to user message only
expect(result).toEqual([
+ { content: getCurrentDateContent(), role: 'system' },
{
content: 'Template: Original user input - End',
role: 'user',
@@ -676,7 +699,7 @@ describe('contextEngineering', () => {
content: 'Assistant response',
},
]);
- expect(result[1].content).toBe('Assistant response'); // Unchanged
+ expect(result[2].content).toBe('Assistant response'); // Unchanged
});
it('should inject system role at the beginning', async () => {
@@ -697,9 +720,9 @@ describe('contextEngineering', () => {
systemRole: 'You are a helpful assistant.',
});
- // Should have system role at the beginning
+ // Should have system role at the beginning (with date appended)
expect(result).toEqual([
- { content: 'You are a helpful assistant.', role: 'system' },
+ { content: 'You are a helpful assistant.\n\n' + getCurrentDateContent(), role: 'system' },
{ content: 'User message', role: 'user' },
]);
});
@@ -737,10 +760,10 @@ describe('contextEngineering', () => {
inputTemplate: 'Processed: {{text}}',
});
- // System role should be first, followed by all messages with input template applied to user messages
+ // System role should be first (with date appended), followed by all messages with input template applied to user messages
expect(result).toEqual([
{
- content: 'System instructions.',
+ content: 'System instructions.\n\n' + getCurrentDateContent(),
role: 'system',
},
{
@@ -775,8 +798,9 @@ describe('contextEngineering', () => {
provider: 'openai',
});
- // Should pass message unchanged
+ // Should pass message unchanged (with system date prepended)
expect(result).toEqual([
+ { content: getCurrentDateContent(), role: 'system' },
{
content: 'Simple message',
role: 'user',
@@ -816,10 +840,10 @@ describe('contextEngineering', () => {
systemRole: 'System role here.',
});
- // Should have system role + all messages
+ // Should have system role (with date) + all messages
expect(result).toEqual([
{
- content: 'System role here.',
+ content: 'System role here.\n\n' + getCurrentDateContent(),
role: 'system',
},
{
@@ -856,8 +880,9 @@ describe('contextEngineering', () => {
inputTemplate: '<%- invalid javascript syntax %>',
});
- // Should keep original message when template fails
+ // Should keep original message when template fails (with system date prepended)
expect(result).toEqual([
+ { content: getCurrentDateContent(), role: 'system' },
{
content: 'User message',
role: 'user',
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index 9ddd6a26e6a..f7eb5b2c2f5 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -1,6 +1,7 @@
import { AgentBuilderIdentifier } from '@lobechat/builtin-tool-agent-builder';
import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-builder';
import { GTDIdentifier } from '@lobechat/builtin-tool-gtd';
+import { LobeToolIdentifier } from '@lobechat/builtin-tool-tools';
import { isDesktop, KLAVIS_SERVER_TYPES, LOBEHUB_SKILL_PROVIDERS } from '@lobechat/const';
import {
type AgentBuilderContext,
@@ -10,6 +11,7 @@ import {
type GTDConfig,
type LobeToolManifest,
type MemoryContext,
+ type ToolDiscoveryConfig,
type UserMemoryData,
} from '@lobechat/context-engine';
import { MessagesEngine } from '@lobechat/context-engine';
@@ -35,6 +37,7 @@ import {
builtinToolSelectors,
klavisStoreSelectors,
lobehubSkillStoreSelectors,
+ toolSelectors,
} from '@/store/tool/selectors';
import { isCanUseVideo, isCanUseVision } from '../helper';
@@ -348,6 +351,23 @@ export const contextEngineering = async ({
}
: undefined;
+ // Build tool discovery config if lobe-tools is enabled
+ const enabledToolSet = new Set(tools || []);
+ const isLobeToolsEnabled = enabledToolSet.has(LobeToolIdentifier);
+
+ let toolDiscoveryConfig: ToolDiscoveryConfig | undefined;
+ if (isLobeToolsEnabled) {
+ const toolState = getToolStoreState();
+ const availableTools = toolSelectors
+ .availableToolsForDiscovery(toolState)
+ .filter((tool) => !enabledToolSet.has(tool.identifier));
+
+ if (availableTools.length > 0) {
+ toolDiscoveryConfig = { availableTools };
+ log('Tool discovery config built, available tools count: %d', availableTools.length);
+ }
+ }
+
// Create MessagesEngine with injected dependencies
const engine = new MessagesEngine({
// Agent configuration
@@ -390,6 +410,9 @@ export const contextEngineering = async ({
enabledSkills: plugins ? createSkillEngine().getEnabledSkills(plugins) : undefined,
},
+ // Tool Discovery configuration
+ toolDiscoveryConfig,
+
// Tools configuration
toolsConfig: {
manifests,
diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.ts
index 1919c7a12a9..309baedfa59 100644
--- a/src/store/chat/agents/createAgentExecutors.ts
+++ b/src/store/chat/agents/createAgentExecutors.ts
@@ -1,25 +1,26 @@
-import {
- type AgentEvent,
- type AgentInstruction,
- type AgentInstructionCallLlm,
- type AgentInstructionCallTool,
- type AgentInstructionCompressContext,
- type AgentInstructionExecClientTask,
- type AgentInstructionExecClientTasks,
- type AgentInstructionExecTask,
- type AgentInstructionExecTasks,
- type AgentRuntimeContext,
- type GeneralAgentCallingToolInstructionPayload,
- type GeneralAgentCallLLMInstructionPayload,
- type GeneralAgentCallLLMResultPayload,
- type GeneralAgentCallToolResultPayload,
- type GeneralAgentCompressionResultPayload,
- type InstructionExecutor,
- type TaskResultPayload,
- type TasksBatchResultPayload,
+import type {
+ AgentEvent,
+ AgentInstruction,
+ AgentInstructionCallLlm,
+ AgentInstructionCallTool,
+ AgentInstructionCompressContext,
+ AgentInstructionExecClientTask,
+ AgentInstructionExecClientTasks,
+ AgentInstructionExecTask,
+ AgentInstructionExecTasks,
+ AgentRuntimeContext,
+ GeneralAgentCallingToolInstructionPayload,
+ GeneralAgentCallLLMInstructionPayload,
+ GeneralAgentCallLLMResultPayload,
+ GeneralAgentCallToolResultPayload,
+ GeneralAgentCompressionResultPayload,
+ InstructionExecutor,
+ TaskResultPayload,
+ TasksBatchResultPayload,
} from '@lobechat/agent-runtime';
import { calculateMessageTokens, UsageCounter } from '@lobechat/agent-runtime';
import { isDesktop } from '@lobechat/const';
+import type { ToolsEngine } from '@lobechat/context-engine';
import { chainCompressContext } from '@lobechat/prompts';
import {
type ChatToolPayload,
@@ -44,7 +45,6 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { getFileStoreState } from '@/store/file/store';
import { sleep } from '@/utils/sleep';
-import { topicSelectors } from '../selectors';
import { StreamingHandler } from './StreamingHandler';
import { type StreamChunk } from './types/streaming';
@@ -74,6 +74,8 @@ export const createAgentExecutors = (context: {
operationId: string;
parentId: string;
skipCreateFirstMessage?: boolean;
+ /** ToolsEngine for expanding dynamically activated tools */
+ toolsEngine?: ToolsEngine;
}) => {
let shouldSkipCreateMessage = context.skipCreateFirstMessage;
@@ -99,7 +101,6 @@ export const createAgentExecutors = (context: {
return opContext.subAgentId || opContext.agentId;
};
- /* eslint-disable sort-keys-fix/sort-keys-fix */
const executors: Partial<Record<AgentInstruction['type'], InstructionExecutor>> = {
/**
* Custom call_llm executor
@@ -298,9 +299,41 @@ export const createAgentExecutors = (context: {
const messages = llmPayload.messages.filter((message) => message.id !== assistantMessageId);
- const historySummary = chatConfig.enableCompressHistory
- ? topicSelectors.currentActiveTopicSummary(context.get())
- : undefined;
+ // Expand dynamically activated tools (from lobe-tools activateTools API)
+ // and merge them into the agent config for this LLM call
+ const activatedToolIds = runtimeContext?.stepContext?.activatedToolIds;
+ let resolvedAgentConfig = context.agentConfig;
+
+ if (activatedToolIds?.length && context.toolsEngine) {
+ const additional = context.toolsEngine.generateToolsDetailed({
+ context: { isExplicitActivation: true },
+ model: agentConfigData.model,
+ provider: agentConfigData.provider!,
+ skipDefaultTools: true,
+ toolIds: activatedToolIds,
+ });
+
+ if (additional.tools?.length) {
+ resolvedAgentConfig = {
+ ...context.agentConfig,
+ enabledManifests: [
+ ...(context.agentConfig.enabledManifests || []),
+ ...additional.enabledManifests,
+ ],
+ enabledToolIds: [
+ ...(context.agentConfig.enabledToolIds || []),
+ ...additional.enabledToolIds,
+ ],
+ tools: [...(context.agentConfig.tools || []), ...additional.tools],
+ };
+
+ log(
+ `${stagePrefix} Injected %d activated tools: %o`,
+ activatedToolIds.length,
+ activatedToolIds,
+ );
+ }
+ }
await chatService.createAssistantMessageStream({
abortController,
@@ -310,11 +343,10 @@ export const createAgentExecutors = (context: {
messages,
model: llmPayload.model,
provider: llmPayload.provider,
- resolvedAgentConfig: context.agentConfig,
+ resolvedAgentConfig,
topicId: topicId ?? undefined,
...agentConfigData.params,
},
- historySummary: historySummary?.content,
initialContext: runtimeContext?.initialContext,
stepContext: runtimeContext?.stepContext,
trace: {
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index a0416a127b8..33eb6506813 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -9,6 +9,7 @@ import { AgentRuntime, computeStepContext, GeneralChatAgent } from '@lobechat/ag
import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
import { dynamicInterventionAudits } from '@lobechat/builtin-tools/dynamicInterventionAudits';
import { isDesktop } from '@lobechat/const';
+import { type ToolsEngine } from '@lobechat/context-engine';
import {
type ConversationContext,
type RuntimeInitialContext,
@@ -34,7 +35,10 @@ import { markdownToTxt } from '@/utils/markdownToTxt';
import { topicSelectors } from '../../../selectors';
import { messageMapKey } from '../../../utils/messageMapKey';
import { topicMapKey } from '../../../utils/topicMapKey';
-import { selectTodosFromMessages } from '../../message/selectors/dbMessage';
+import {
+ selectActivatedToolIdsFromMessages,
+ selectTodosFromMessages,
+} from '../../message/selectors/dbMessage';
const log = debug('lobe-store:streaming-executor');
@@ -85,6 +89,7 @@ export class StreamingExecutorActionImpl {
state: AgentState;
context: AgentRuntimeContext;
agentConfig: ResolvedAgentConfig;
+ toolsEngine?: ToolsEngine;
} => {
// Use provided agentId/topicId or fallback to global state
// Note: Use || instead of ?? to also fallback when paramAgentId is empty string
@@ -243,7 +248,7 @@ export class StreamingExecutorActionImpl {
initialContext: runtimeInitialContext,
};
- return { agentConfig: agentConfigWithTools, context, state };
+ return { agentConfig: agentConfigWithTools, context, state, toolsEngine };
};
internal_execAgentRuntime = async (params: {
@@ -326,6 +331,7 @@ export class StreamingExecutorActionImpl {
state: initialAgentState,
context: initialAgentContext,
agentConfig,
+ toolsEngine,
} = this.#get().internal_createAgentState({
messages,
parentMessageId: params.parentMessageId,
@@ -374,6 +380,7 @@ export class StreamingExecutorActionImpl {
operationId,
parentId: params.parentMessageId,
skipCreateFirstMessage: params.skipCreateFirstMessage,
+ toolsEngine, // Pass toolsEngine for dynamic tool injection via activateTools
}),
getOperation: (opId: string) => {
const op = this.#get().operations[opId];
@@ -420,7 +427,9 @@ export class StreamingExecutorActionImpl {
const currentDBMessages = this.#get().dbMessagesMap[messageKey] || [];
// Use selectTodosFromMessages selector (shared with UI display)
const todos = selectTodosFromMessages(currentDBMessages);
- const stepContext = computeStepContext({ todos });
+ // Accumulate activated tool IDs from lobe-tools messages
+ const activatedToolIds = selectActivatedToolIdsFromMessages(currentDBMessages);
+ const stepContext = computeStepContext({ activatedToolIds, todos });
// If page agent is enabled, get the latest XML for stepPageEditor
if (nextContext.initialContext?.pageEditor) {
diff --git a/src/store/chat/slices/message/selectors/dbMessage.ts b/src/store/chat/slices/message/selectors/dbMessage.ts
index 9c0b89c9a84..f5142145ea1 100644
--- a/src/store/chat/slices/message/selectors/dbMessage.ts
+++ b/src/store/chat/slices/message/selectors/dbMessage.ts
@@ -1,3 +1,5 @@
+import { GTDIdentifier } from '@lobechat/builtin-tool-gtd';
+import { LobeToolIdentifier } from '@lobechat/builtin-tool-tools';
import { type StepContextTodos, type UIChatMessage } from '@lobechat/types';
import { chatHelpers } from '../../../helpers';
@@ -146,9 +148,44 @@ const inboxActiveTopicDbMessages = (state: ChatStoreState) => {
return state.dbMessagesMap[key] || [];
};
-// ============= GTD Todos Selectors ========== //
+// ============= Activated Tools Selectors ========== //
+
+/**
+ * Accumulate activated tool identifiers from all lobe-tools messages.
+ *
+ * Unlike todos (which take the latest snapshot), activated tools are
+ * cumulative — once a tool is activated it stays active for the rest
+ * of the conversation.
+ *
+ * @param messages - Array of chat messages to scan
+ * @returns Deduplicated array of activated tool identifiers, or undefined if none
+ */
+export const selectActivatedToolIdsFromMessages = (
+ messages: UIChatMessage[],
+): string[] | undefined => {
+ const ids = new Set<string>();
+
+ for (const msg of messages) {
+ if (
+ msg.role === 'tool' &&
+ msg.plugin?.identifier === LobeToolIdentifier &&
+ msg.pluginState?.activatedTools
+ ) {
+ const activatedTools = msg.pluginState.activatedTools as Array<{ identifier?: string }>;
+ if (Array.isArray(activatedTools)) {
+ for (const tool of activatedTools) {
+ if (tool.identifier) {
+ ids.add(tool.identifier);
+ }
+ }
+ }
+ }
+ }
+
+ return ids.size > 0 ? [...ids] : undefined;
+};
-const GTD_IDENTIFIER = 'lobe-gtd';
+// ============= GTD Todos Selectors ========== //
/**
* Select the latest todos state from messages array
@@ -171,11 +208,7 @@ export const selectTodosFromMessages = (
const msg = messages[i];
// Check if this is a GTD tool message with todos state
- if (
- msg.role === 'tool' &&
- msg.plugin?.identifier === GTD_IDENTIFIER &&
- msg.pluginState?.todos
- ) {
+ if (msg.role === 'tool' && msg.plugin?.identifier === GTDIdentifier && msg.pluginState?.todos) {
const todos = msg.pluginState.todos as { items?: unknown[]; updatedAt?: string };
// Handle the todos structure: { items: TodoItem[], updatedAt: string }
@@ -223,5 +256,6 @@ export const dbMessageSelectors = {
isCurrentDbChatLoaded,
latestDbMessage,
latestUserMessage,
+ selectActivatedToolIdsFromMessages,
selectTodosFromMessages,
};
diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.ts
index f6558a50d8a..ba697817832 100644
--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts
+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts
@@ -144,11 +144,14 @@ export class PluginTypesActionImpl {
topicId,
});
+ // When error exists but content is empty, backfill error message into content
+ const content = result.content || result.error?.message || '';
+
// Use optimisticUpdateToolMessage to batch update content, state, error, metadata
await optimisticUpdateToolMessage(
id,
{
- content: result.content,
+ content,
metadata: result.metadata,
pluginError: result.error
? {
@@ -307,7 +310,7 @@ export class PluginTypesActionImpl {
if (!data) return;
// Truncate content to prevent context overflow
- const truncatedContent = truncateToolResult(data.content);
+ const truncatedContent = truncateToolResult(data.content || (data.error as any)?.message || '');
// operationId already declared above, reuse it
const context = operationId ? { operationId } : undefined;
@@ -379,20 +382,21 @@ export class PluginTypesActionImpl {
// If error occurred, exit
if (!data) return;
+ const remoteContent = data.content || (data.error as any)?.message || '';
const context = operationId ? { operationId } : undefined;
// Use optimisticUpdateToolMessage to update content and state/error in a single call
await this.#get().optimisticUpdateToolMessage(
id,
{
- content: data.content,
+ content: remoteContent,
pluginError: data.success ? undefined : data.error,
pluginState: data.success ? data.state : undefined,
},
context,
);
- return data.content;
+ return remoteContent;
};
internal_callPluginApi = async (
diff --git a/src/store/tool/selectors/tool.ts b/src/store/tool/selectors/tool.ts
index 7df93993805..8a5192a47f8 100644
--- a/src/store/tool/selectors/tool.ts
+++ b/src/store/tool/selectors/tool.ts
@@ -1,12 +1,20 @@
+import {
+ getKlavisServerByServerIdentifier,
+ getLobehubSkillProviderById,
+ isDesktop,
+} from '@lobechat/const';
import { type RenderDisplayControl } from '@lobechat/types';
import { type LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';
+import { shouldEnableTool } from '@/helpers/toolFilters';
import { type MetaData } from '@/types/meta';
import { type LobeToolMeta } from '@/types/tool/tool';
import { type ToolStoreState } from '../initialState';
import { builtinToolSelectors } from '../slices/builtin/selectors';
-import { lobehubSkillStoreSelectors } from '../slices/lobehubSkillStore/selectors';
+import { KlavisServerStatus } from '../slices/klavisStore';
+import { lobehubSkillStoreSelectors } from '../slices/lobehubSkillStore';
+import { LobehubSkillStatus } from '../slices/lobehubSkillStore/types';
import { pluginSelectors } from '../slices/plugin/selectors';
const metaList = (s: ToolStoreState): LobeToolMeta[] => {
@@ -82,7 +90,86 @@ const getRenderDisplayControl =
return api?.renderDisplayControl ?? 'collapsed';
};
+export interface AvailableToolForDiscovery {
+ description: string;
+ identifier: string;
+ name: string;
+}
+
+/**
+ * Get all tools available for tool discovery (activateTools).
+ * Built from raw state to avoid inheriting unrelated filtering logic.
+ *
+ * Sources:
+ * 1. Builtin tools (from s.builtinTools) — exclude non-discoverable, skills, platform-unavailable
+ * 2. User-installed plugins (from s.installedPlugins) — exclude Klavis/LobeHub Skill/agent skill overlap
+ * 3. Klavis MCP servers (connected) — description from KLAVIS_SERVER_TYPES
+ * 4. LobeHub Skill servers (connected) — description from LOBEHUB_SKILL_PROVIDERS
+ */
+const availableToolsForDiscovery = (s: ToolStoreState): AvailableToolForDiscovery[] => {
+ // Build exclusion sets for deduplication
+ const builtinSkillIds = new Set((s.builtinSkills || []).map((skill) => skill.identifier));
+ const agentSkillIds = new Set((s.agentSkills || []).map((skill) => skill.identifier));
+ const klavisIds = new Set((s.servers || []).map((server) => server.identifier));
+ const lobehubSkillIds = new Set((s.lobehubSkillServers || []).map((server) => server.identifier));
+
+ // 1. Builtin tools — directly from s.builtinTools
+ const builtinItems = s.builtinTools
+ .filter((tool) => tool.discoverable !== false)
+ .filter((tool) => !builtinSkillIds.has(tool.identifier))
+ .filter((tool) => shouldEnableTool(tool.identifier)) // platform check (e.g., desktop-only)
+ .map((tool) => ({
+ description: tool.manifest.meta?.description || '',
+ identifier: tool.identifier,
+ name: tool.manifest.meta?.title || tool.identifier,
+ }));
+
+ // 2. User-installed plugins — directly from s.installedPlugins
+ // Exclude Klavis, LobeHub Skill, and agent skill entries (they are handled in dedicated sources)
+ const pluginItems = s.installedPlugins
+ .filter((p) => !klavisIds.has(p.identifier))
+ .filter((p) => !lobehubSkillIds.has(p.identifier))
+ .filter((p) => !agentSkillIds.has(p.identifier))
+ .filter((p) => !p.customParams?.klavis) // extra safety for Klavis plugins
+ .filter((p) => isDesktop || p.customParams?.mcp?.type !== 'stdio') // platform check
+ .map((plugin) => {
+ const meta = plugin.manifest?.meta;
+ return {
+ description: meta?.description || '',
+ identifier: plugin.identifier,
+ name: meta?.title || plugin.identifier,
+ };
+ });
+
+ // 3. Klavis MCP servers (connected only)
+ const klavisItems = (s.servers || [])
+ .filter((server) => server.status === KlavisServerStatus.CONNECTED && server.tools?.length)
+ .map((server) => {
+ const config = getKlavisServerByServerIdentifier(server.identifier);
+ return {
+ description: config?.description || '',
+ identifier: server.identifier,
+ name: config?.label || server.serverName,
+ };
+ });
+
+ // 4. LobeHub Skill servers (connected only)
+ const lobehubSkillItems = (s.lobehubSkillServers || [])
+ .filter((server) => server.status === LobehubSkillStatus.CONNECTED)
+ .map((server) => {
+ const config = getLobehubSkillProviderById(server.identifier);
+ return {
+ description: config?.description || '',
+ identifier: server.identifier,
+ name: config?.label || server.name,
+ };
+ });
+
+ return [...builtinItems, ...pluginItems, ...klavisItems, ...lobehubSkillItems];
+};
+
export const toolSelectors = {
+ availableToolsForDiscovery,
getManifestById,
getManifestLoadingStatus,
getMetaById,
diff --git a/src/store/tool/slices/builtin/executors/__tests__/lobe-tools.test.ts b/src/store/tool/slices/builtin/executors/__tests__/lobe-tools.test.ts
new file mode 100644
index 00000000000..0a6394d3cb2
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/__tests__/lobe-tools.test.ts
@@ -0,0 +1,123 @@
+/**
+ * Tests for Lobe Tools Executor (activateTools discovery allowlist)
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// Mock getToolStoreState
+const mockGetState = vi.fn();
+vi.mock('@/store/tool', () => ({
+ getToolStoreState: () => mockGetState(),
+}));
+
+// Mock toolSelectors.availableToolsForDiscovery
+const mockAvailableToolsForDiscovery = vi.fn();
+vi.mock('@/store/tool/selectors/tool', () => ({
+ toolSelectors: {
+ availableToolsForDiscovery: (s: any) => mockAvailableToolsForDiscovery(s),
+ },
+}));
+
+// Import after mocks
+const { toolsActivatorExecutor } = await import('../lobe-tools');
+
+const makeBuiltinTool = (identifier: string, discoverable?: boolean) => ({
+ discoverable,
+ identifier,
+ manifest: {
+ api: [{ description: `${identifier} api`, name: 'run' }],
+ meta: { avatar: '🔧', description: `${identifier} desc`, title: identifier },
+ systemRole: `You are ${identifier}`,
+ },
+});
+
+const makePlugin = (identifier: string) => ({
+ identifier,
+ manifest: {
+ api: [{ description: `${identifier} api`, name: 'execute' }],
+ meta: { avatar: '🔌', description: `${identifier} desc`, title: identifier },
+ systemRole: `Plugin ${identifier}`,
+ },
+});
+
+describe('lobe-tools executor discovery allowlist', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should only return manifests for discoverable tools', async () => {
+ const discoverableTool = makeBuiltinTool('web-browsing');
+ const hiddenTool = makeBuiltinTool('internal-admin', false);
+
+ mockGetState.mockReturnValue({
+ builtinTools: [discoverableTool, hiddenTool],
+ installedPlugins: [],
+ });
+
+ // Only web-browsing is discoverable
+ mockAvailableToolsForDiscovery.mockReturnValue([
+ { description: 'desc', identifier: 'web-browsing', name: 'web-browsing' },
+ ]);
+
+ const result = await toolsActivatorExecutor.invoke(
+ 'activateTools',
+ { identifiers: ['web-browsing', 'internal-admin'] },
+ { messageId: 'msg-1', operationId: 'op-1' },
+ );
+
+ expect(result.success).toBe(true);
+
+ const state = result.state as any;
+ const activatedIds = state.activatedTools?.map((t: any) => t.identifier) ?? [];
+
+ expect(activatedIds).toContain('web-browsing');
+ expect(activatedIds).not.toContain('internal-admin');
+ });
+
+ it('should reject all identifiers when none are discoverable', async () => {
+ const hiddenTool = makeBuiltinTool('secret-tool', false);
+
+ mockGetState.mockReturnValue({
+ builtinTools: [hiddenTool],
+ installedPlugins: [],
+ });
+
+ mockAvailableToolsForDiscovery.mockReturnValue([]);
+
+ const result = await toolsActivatorExecutor.invoke(
+ 'activateTools',
+ { identifiers: ['secret-tool'] },
+ { messageId: 'msg-1', operationId: 'op-1' },
+ );
+
+ expect(result.success).toBe(true);
+
+ const state = result.state as any;
+ const activatedIds = state.activatedTools?.map((t: any) => t.identifier) ?? [];
+ expect(activatedIds).toHaveLength(0);
+ });
+
+ it('should allow discoverable plugins', async () => {
+ const plugin = makePlugin('community-plugin');
+
+ mockGetState.mockReturnValue({
+ builtinTools: [],
+ installedPlugins: [plugin],
+ });
+
+ mockAvailableToolsForDiscovery.mockReturnValue([
+ { description: 'desc', identifier: 'community-plugin', name: 'community-plugin' },
+ ]);
+
+ const result = await toolsActivatorExecutor.invoke(
+ 'activateTools',
+ { identifiers: ['community-plugin'] },
+ { messageId: 'msg-1', operationId: 'op-1' },
+ );
+
+ expect(result.success).toBe(true);
+
+ const state = result.state as any;
+ const activatedIds = state.activatedTools?.map((t: any) => t.identifier) ?? [];
+ expect(activatedIds).toContain('community-plugin');
+ });
+});
diff --git a/src/store/tool/slices/builtin/executors/__tests__/lobe-web-browsing.test.ts b/src/store/tool/slices/builtin/executors/__tests__/lobe-web-browsing.test.ts
index 4d5dd51904d..3738bb60e4d 100644
--- a/src/store/tool/slices/builtin/executors/__tests__/lobe-web-browsing.test.ts
+++ b/src/store/tool/slices/builtin/executors/__tests__/lobe-web-browsing.test.ts
@@ -117,7 +117,47 @@ describe('WebBrowsingExecutor', () => {
expect(result.error?.message).toBe('Search failed');
});
- it('should handle runtime error that returns success false', async () => {
+ it('should return error when response has errorDetail', async () => {
+ mockSearch.mockResolvedValue({
+ costTime: 0,
+ errorDetail: 'Failed to search: 500 Internal Server Error',
+ query: 'test query',
+ resultNumbers: 0,
+ results: [],
+ });
+
+ const result = await webBrowsing.invoke(
+ WebBrowsingApiName.search,
+ { query: 'test query' },
+ createContext(),
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.error?.type).toBe('PluginServerError');
+ expect(result.error?.message).toBe('Failed to search: 500 Internal Server Error');
+ });
+
+ it('should handle SearXNG not configured via errorDetail', async () => {
+ mockSearch.mockResolvedValue({
+ costTime: 0,
+ errorDetail: SEARCH_SEARXNG_NOT_CONFIG,
+ query: 'test query',
+ resultNumbers: 0,
+ results: [],
+ });
+
+ const result = await webBrowsing.invoke(
+ WebBrowsingApiName.search,
+ { query: 'test query' },
+ createContext(),
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.error?.type).toBe('PluginSettingsInvalid');
+ expect(result.error?.body?.provider).toBe('searxng');
+ });
+
+ it('should return runtime error that returns success false', async () => {
// When runtime catches error, it returns success: false with error message
mockSearch.mockRejectedValue(new Error('Internal error'));
diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.ts
index 8980770d7ae..3ea53c9297c 100644
--- a/src/store/tool/slices/builtin/executors/index.ts
+++ b/src/store/tool/slices/builtin/executors/index.ts
@@ -16,6 +16,7 @@ import { memoryExecutor } from '@lobechat/builtin-tool-memory/executor';
import type { BuiltinToolContext, BuiltinToolResult, IBuiltinToolExecutor } from '../types';
import { notebookExecutor } from './lobe-notebook';
import { pageAgentExecutor } from './lobe-page-agent';
+import { skillStoreExecutor } from './lobe-skill-store';
import { skillsExecutor } from './lobe-skills';
import { toolsActivatorExecutor } from './lobe-tools';
import { webBrowsing } from './lobe-web-browsing';
@@ -132,6 +133,7 @@ registerExecutors([
memoryExecutor,
notebookExecutor,
pageAgentExecutor,
+ skillStoreExecutor,
skillsExecutor,
toolsActivatorExecutor,
webBrowsing,
diff --git a/src/store/tool/slices/builtin/executors/lobe-skill-store.ts b/src/store/tool/slices/builtin/executors/lobe-skill-store.ts
new file mode 100644
index 00000000000..c62ce3acb5c
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/lobe-skill-store.ts
@@ -0,0 +1,48 @@
+/**
+ * Lobe Skill Store Executor
+ *
+ * Creates and exports the SkillStoreExecutor instance for registration.
+ * Handles skill search and import from market/URL.
+ */
+import { SkillStoreExecutionRuntime } from '@lobechat/builtin-tool-skill-store/executionRuntime';
+import { SkillStoreExecutor } from '@lobechat/builtin-tool-skill-store/executor';
+
+import { marketApiService } from '@/services/marketApi';
+import { agentSkillService } from '@/services/skill';
+
+// Create runtime with client-side service
+const runtime = new SkillStoreExecutionRuntime({
+ service: {
+ importFromGitHub: async (gitUrl) => {
+ const result = await agentSkillService.importFromGitHub({ gitUrl });
+ if (!result) throw new Error('Import failed');
+ return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
+ },
+ importFromMarket: async (identifier) => {
+ const result = await agentSkillService.importFromMarket(identifier);
+ if (!result) throw new Error('Import failed');
+ return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
+ },
+ importFromUrl: async (url) => {
+ const result = await agentSkillService.importFromUrl({ url });
+ if (!result) throw new Error('Import failed');
+ return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
+ },
+ importFromZipUrl: async (url) => {
+ const result = await agentSkillService.importFromUrl({ url });
+ if (!result) throw new Error('Import failed');
+ return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
+ },
+ onSkillImported: async () => {
+ // Dynamic import to avoid circular dependency (this file is inside the tool store)
+ const { getToolStoreState } = await import('@/store/tool/store');
+ await getToolStoreState().refreshAgentSkills();
+ },
+ searchSkill: async (params) => {
+ return marketApiService.searchSkill(params);
+ },
+ },
+});
+
+// Create executor instance with the runtime
+export const skillStoreExecutor = new SkillStoreExecutor(runtime);
diff --git a/src/store/tool/slices/builtin/executors/lobe-skills.ts b/src/store/tool/slices/builtin/executors/lobe-skills.ts
index 20041b1ee91..3e9284b49da 100644
--- a/src/store/tool/slices/builtin/executors/lobe-skills.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-skills.ts
@@ -11,7 +11,6 @@ import { isDesktop } from '@lobechat/const';
import { cloudSandboxService } from '@/services/cloudSandbox';
import { localFileService } from '@/services/electron/localFileService';
-import { marketApiService } from '@/services/marketApi';
import { agentSkillService } from '@/services/skill';
import { useChatStore } from '@/store/chat';
@@ -105,35 +104,7 @@ const runtime = new SkillsExecutionRuntime({
findAll: () => agentSkillService.list(),
findById: (id) => agentSkillService.getById(id),
findByName: (name) => agentSkillService.getByName(name),
- importFromGitHub: async (gitUrl) => {
- const result = await agentSkillService.importFromGitHub({ gitUrl });
- if (!result) throw new Error('Import failed');
- return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
- },
- importFromUrl: async (url) => {
- const result = await agentSkillService.importFromUrl({ url });
- if (!result) throw new Error('Import failed');
- return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
- },
- importFromZipUrl: async (url) => {
- const result = await agentSkillService.importFromUrl({ url });
- if (!result) throw new Error('Import failed');
- return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
- },
- onSkillImported: async () => {
- // Dynamic import to avoid circular dependency (this file is inside the tool store)
- const { getToolStoreState } = await import('@/store/tool/store');
- await getToolStoreState().refreshAgentSkills();
- },
readResource: (id, path) => agentSkillService.readResource(id, path),
- searchSkill: async (params) => {
- return marketApiService.searchSkill(params);
- },
- importFromMarket: async (identifier) => {
- const result = await agentSkillService.importFromMarket(identifier);
- if (!result) throw new Error('Import failed');
- return { skill: { id: result.skill.id, name: result.skill.name }, status: result.status };
- },
runCommand: async ({ command, runInClient, timeout }) => {
// Desktop: run in local client if requested
if (isDesktop && runInClient) {
diff --git a/src/store/tool/slices/builtin/executors/lobe-tools.ts b/src/store/tool/slices/builtin/executors/lobe-tools.ts
index cb789f69123..4047f1a2145 100644
--- a/src/store/tool/slices/builtin/executors/lobe-tools.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-tools.ts
@@ -2,8 +2,11 @@
* Lobe Tools Executor
*
* Creates and exports the ToolsActivatorExecutor instance for registration.
- * Injects a stub service as dependency — actual tool manifest resolution
- * will be implemented in follow-up work when ToolDiscoveryProvider is ready.
+ * Resolves tool manifests from the tool store (installedPlugins + builtinTools).
+ *
+ * State tracking (getActivatedToolIds / markActivated) is intentionally a no-op
+ * because the activated state is persisted in message pluginState and accumulated
+ * by selectActivatedToolIdsFromMessages at each agentic loop step.
*/
import {
type ToolManifestInfo,
@@ -12,20 +15,61 @@ import {
} from '@lobechat/builtin-tool-tools/executionRuntime';
import { ToolsActivatorExecutor } from '@lobechat/builtin-tool-tools/executor';
-// Stub service — will be replaced with real implementation
-// when ToolDiscoveryProvider and state.tools mutations are ready
-const stubService: ToolsActivatorRuntimeService = {
+import { getToolStoreState } from '@/store/tool';
+import { toolSelectors } from '@/store/tool/selectors/tool';
+
+const service: ToolsActivatorRuntimeService = {
getActivatedToolIds: () => [],
- getToolManifests: async (_identifiers: string[]): Promise<ToolManifestInfo[]> => {
- return [];
+ getToolManifests: async (identifiers: string[]): Promise<ToolManifestInfo[]> => {
+ const s = getToolStoreState();
+
+ // Only allow activation of tools that passed discovery filters
+ // (discoverable, platform-available, not internal/hidden)
+ const discoverable = new Set(
+ toolSelectors.availableToolsForDiscovery(s).map((t) => t.identifier),
+ );
+ const allowedIds = identifiers.filter((id) => discoverable.has(id));
+
+ const results: ToolManifestInfo[] = [];
+
+ for (const id of allowedIds) {
+ // Search builtin tools
+ const builtin = s.builtinTools.find((t) => t.identifier === id);
+ if (builtin) {
+ results.push({
+ apiDescriptions: builtin.manifest.api.map((a) => ({
+ description: a.description,
+ name: a.name,
+ })),
+ avatar: builtin.manifest.meta?.avatar,
+ identifier: builtin.identifier,
+ name: builtin.manifest.meta?.title ?? builtin.identifier,
+ systemRole: builtin.manifest.systemRole,
+ });
+ continue;
+ }
+
+ // Search installed plugins
+ const plugin = s.installedPlugins.find((p) => p.identifier === id);
+ if (plugin?.manifest) {
+ results.push({
+ apiDescriptions: (plugin.manifest.api || []).map((a) => ({
+ description: a.description,
+ name: a.name,
+ })),
+ avatar: plugin.manifest.meta?.avatar,
+ identifier: plugin.identifier,
+ name: plugin.manifest.meta?.title ?? plugin.identifier,
+ systemRole: plugin.manifest.systemRole,
+ });
+ }
+ }
+
+ return results;
},
markActivated: () => {},
};
-// Create runtime with stub service
-const runtime = new ToolsActivatorExecutionRuntime({
- service: stubService,
-});
+const runtime = new ToolsActivatorExecutionRuntime({ service });
-// Create executor instance with the runtime
export const toolsActivatorExecutor = new ToolsActivatorExecutor(runtime);