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.

:recycle: refactor: refactor tool prompt injection

arvinxx6099ac380a05
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index 816420bcd55..f37500a4e61 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -197,14 +197,13 @@ export class MessagesEngine {
}),
// 8. Tool system role injection (conditionally added)
- ...(toolsConfig?.tools && toolsConfig.tools.length > 0
+ ...(toolsConfig?.manifests && toolsConfig.manifests.length > 0
? [
new ToolSystemRoleProvider({
- getToolSystemRoles: toolsConfig.getToolSystemRoles || (() => undefined),
isCanUseFC: capabilities?.isCanUseFC || (() => true),
+ manifests: toolsConfig.manifests,
model,
provider,
- tools: toolsConfig.tools,
}),
]
: []),
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 29c63e5635a..746a8503a6f 100644
--- a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
@@ -57,7 +57,7 @@ describe('MessagesEngine', () => {
},
systemRole: 'You are a helpful assistant',
toolsConfig: {
- getToolSystemRoles: () => undefined,
+ manifests: [],
tools: ['tool1'],
},
variableGenerators: {
@@ -363,21 +363,37 @@ describe('MessagesEngine', () => {
});
describe('tools config', () => {
- it('should handle tools configuration', async () => {
- const getToolSystemRoles = vi.fn().mockReturnValue('Tool system role');
+ it('should handle tools configuration with manifests', async () => {
+ const mockManifests = [
+ {
+ identifier: 'tool1',
+ api: [{ name: 'action', description: 'Tool 1 action', parameters: {} }],
+ meta: { title: 'Tool 1' },
+ type: 'default' as const,
+ },
+ {
+ identifier: 'tool2',
+ api: [{ name: 'action', description: 'Tool 2 action', parameters: {} }],
+ meta: { title: 'Tool 2' },
+ type: 'default' as const,
+ },
+ ];
const params = createBasicParams({
capabilities: { isCanUseFC: () => true },
toolsConfig: {
- getToolSystemRoles,
+ manifests: mockManifests,
tools: ['tool1', 'tool2'],
},
});
const engine = new MessagesEngine(params);
- await engine.process();
+ const result = await engine.process();
- expect(getToolSystemRoles).toHaveBeenCalled();
+ // Should inject tool system role when manifests are provided
+ const systemMessage = result.messages.find((msg) => msg.role === 'system');
+ expect(systemMessage).toBeDefined();
+ expect(systemMessage!.content).toContain('tool1');
});
it('should skip tool system role provider when no tools', async () => {
diff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.ts
index faf8ddfb3af..9daf53be24c 100644
--- a/packages/context-engine/src/engine/messages/types.ts
+++ b/packages/context-engine/src/engine/messages/types.ts
@@ -8,6 +8,7 @@ import type { AgentInfo } from '../../processors/GroupMessageSender';
import type { AgentBuilderContext } from '../../providers/AgentBuilderContextInjector';
import type { GroupAgentBuilderContext } from '../../providers/GroupAgentBuilderContextInjector';
import type { GroupMemberInfo } from '../../providers/GroupContextInjector';
+import type { LobeToolManifest } from '../tools/types';
/**
* Model capability checker
@@ -36,9 +37,9 @@ export interface KnowledgeConfig {
* Tools configuration
*/
export interface ToolsConfig {
- /** Function to get tool system roles */
- getToolSystemRoles?: (tools: string[]) => string | undefined;
- /** Enabled tool IDs */
+ /** Tool manifests with systemRole and API definitions */
+ manifests?: LobeToolManifest[];
+ /** Enabled tool IDs (kept for compatibility) */
tools?: string[];
}
diff --git a/packages/context-engine/src/engine/tools/ToolsEngine.ts b/packages/context-engine/src/engine/tools/ToolsEngine.ts
index 782d13e8043..4e69b18f052 100644
--- a/packages/context-engine/src/engine/tools/ToolsEngine.ts
+++ b/packages/context-engine/src/engine/tools/ToolsEngine.ts
@@ -131,6 +131,7 @@ export class ToolsEngine {
);
return {
+ enabledManifests,
enabledToolIds: enabledManifests.map((m) => m.identifier),
filteredTools: filteredPlugins,
tools,
diff --git a/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts
index 95406912dc5..8e7380ecbcf 100644
--- a/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts
+++ b/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts
@@ -982,6 +982,18 @@ describe('ToolsEngine', () => {
},
},
],
+ enabledManifests: [
+ {
+ identifier: 'plugin-1',
+ api: [{ name: 'api-1', description: 'API 1', parameters: {} }],
+ meta: {
+ title: 'Plugin 1',
+ description: 'Plugin 1 description',
+ avatar: '🔧',
+ },
+ type: 'default',
+ },
+ ],
enabledToolIds: ['plugin-1'],
filteredTools: [
{ id: 'plugin-2', reason: 'disabled' },
diff --git a/packages/context-engine/src/engine/tools/types.ts b/packages/context-engine/src/engine/tools/types.ts
index 92e2c605549..6309a7840a4 100644
--- a/packages/context-engine/src/engine/tools/types.ts
+++ b/packages/context-engine/src/engine/tools/types.ts
@@ -101,6 +101,8 @@ export interface ToolsEngineOptions {
* Tools generation result
*/
export interface ToolsGenerationResult {
+ /** List of enabled manifests with systemRole and other metadata */
+ enabledManifests: LobeToolManifest[];
/** List of enabled tool IDs */
enabledToolIds: string[];
/** Filtered plugins and their reasons */
diff --git a/packages/context-engine/src/providers/ToolSystemRole.ts b/packages/context-engine/src/providers/ToolSystemRole.ts
index 5a7f45b2aeb..92ace57b5d7 100644
--- a/packages/context-engine/src/providers/ToolSystemRole.ts
+++ b/packages/context-engine/src/providers/ToolSystemRole.ts
@@ -1,6 +1,9 @@
+import { type API, type Tool, pluginPrompts } from '@lobechat/prompts';
import debug from 'debug';
import { BaseProvider } from '../base/BaseProvider';
+import { ToolNameResolver } from '../engine/tools';
+import type { LobeToolManifest } from '../engine/tools/types';
import type { PipelineContext, ProcessorOptions } from '../types';
const log = debug('context-engine:provider:ToolSystemRoleProvider');
@@ -9,16 +12,14 @@ const log = debug('context-engine:provider:ToolSystemRoleProvider');
* Tool System Role Configuration
*/
export interface ToolSystemRoleConfig {
- /** Function to get tool system roles */
- getToolSystemRoles: (tools: any[]) => string | undefined;
/** Function to check if function calling is supported */
isCanUseFC: (model: string, provider: string) => boolean | undefined;
+ /** Tool manifests with systemRole and API definitions */
+ manifests: LobeToolManifest[];
/** Model name */
model: string;
/** Provider name */
provider: string;
- /** Available tools list */
- tools?: any[];
}
/**
@@ -28,11 +29,14 @@ export interface ToolSystemRoleConfig {
export class ToolSystemRoleProvider extends BaseProvider {
readonly name = 'ToolSystemRoleProvider';
+ private toolNameResolver: ToolNameResolver;
+
constructor(
private config: ToolSystemRoleConfig,
options: ProcessorOptions = {},
) {
super(options);
+ this.toolNameResolver = new ToolNameResolver();
}
protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
@@ -54,10 +58,10 @@ export class ToolSystemRoleProvider extends BaseProvider {
contentLength: toolSystemRole.length,
injected: true,
supportsFunctionCall: this.config.isCanUseFC(this.config.model, this.config.provider),
- toolsCount: this.config.tools?.length || 0,
+ toolsCount: this.config.manifests.length,
};
- log(`Tool system role injection completed, tools count: ${this.config.tools?.length || 0}`);
+ log(`Tool system role injection completed, tools count: ${this.config.manifests.length}`);
return this.markAsExecuted(clonedContext);
}
@@ -65,12 +69,11 @@ export class ToolSystemRoleProvider extends BaseProvider {
* Get tool system role content
*/
private getToolSystemRole(): string | undefined {
- const { tools, model, provider } = this.config;
+ const { manifests, model, provider } = this.config;
- // Check if tools are available
- const hasTools = tools && tools.length > 0;
- if (!hasTools) {
- log('No available tools');
+ // Check if manifests are available
+ if (!manifests || manifests.length === 0) {
+ log('No available tool manifests');
return undefined;
}
@@ -81,13 +84,37 @@ export class ToolSystemRoleProvider extends BaseProvider {
return undefined;
}
- // Get tool system role
- const toolSystemRole = this.config.getToolSystemRoles(tools);
+ // Transform manifests to Tool[] format for pluginPrompts
+ // Only include manifests that have APIs or systemRole
+ const tools: Tool[] = manifests
+ .filter((manifest) => manifest.api.length > 0 || manifest.systemRole)
+ .map((manifest) => ({
+ apis: manifest.api.map(
+ (api): API => ({
+ desc: api.description,
+ name: this.toolNameResolver.generate(manifest.identifier, api.name, manifest.type),
+ }),
+ ),
+ identifier: manifest.identifier,
+ name: manifest.meta?.title || manifest.identifier,
+ systemRole: manifest.systemRole,
+ }));
+
+ // Skip if no meaningful tools after filtering
+ if (tools.length === 0) {
+ log('No meaningful tools to inject (all manifests have empty APIs and no systemRole)');
+ return undefined;
+ }
+
+ // Generate tool system role using pluginPrompts
+ const toolSystemRole = pluginPrompts({ tools });
+
if (!toolSystemRole) {
- log('Failed to get tool system role content');
+ log('Failed to generate tool system role content');
return undefined;
}
+ log(`Generated tool system role for ${manifests.length} tools`);
return toolSystemRole;
}
diff --git a/packages/context-engine/src/providers/__tests__/ToolSystemRoleProvider.test.ts b/packages/context-engine/src/providers/__tests__/ToolSystemRoleProvider.test.ts
index 83f90011772..b99bc122925 100644
--- a/packages/context-engine/src/providers/__tests__/ToolSystemRoleProvider.test.ts
+++ b/packages/context-engine/src/providers/__tests__/ToolSystemRoleProvider.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
+import type { LobeToolManifest } from '../../engine/tools/types';
import type { PipelineContext } from '../../types';
import { ToolSystemRoleProvider } from '../ToolSystemRole';
@@ -10,18 +11,23 @@ const createContext = (messages: any[]): PipelineContext => ({
isAborted: false,
});
-describe('ToolSystemRoleProvider', () => {
- const mockToolSystemRole = 'You have access to the following tools:\n- calculator\n- weather';
+const createMockManifests = (identifiers: string[]): LobeToolManifest[] =>
+ identifiers.map((id) => ({
+ identifier: id,
+ api: [{ name: 'action', description: `${id} action`, parameters: {} }],
+ meta: { title: id },
+ type: 'default' as const,
+ }));
- it('should inject tool system role when tools are available and FC is supported', async () => {
- const mockGetToolSystemRoles = (tools: any[]) => mockToolSystemRole;
- const mockIsCanUseFC = (model: string, provider: string) => true;
+describe('ToolSystemRoleProvider', () => {
+ it('should inject tool system role when manifests are provided and FC is supported', async () => {
+ const mockIsCanUseFC = () => true;
+ const manifests = createMockManifests(['calculator', 'weather']);
const provider = new ToolSystemRoleProvider({
- tools: ['calculator', 'weather'],
+ manifests,
model: 'gpt-4',
provider: 'openai',
- getToolSystemRoles: mockGetToolSystemRoles,
isCanUseFC: mockIsCanUseFC,
});
@@ -33,26 +39,23 @@ describe('ToolSystemRoleProvider', () => {
// Should have system message with tool system role
const systemMessage = result.messages.find((msg) => msg.role === 'system');
expect(systemMessage).toBeDefined();
- expect(systemMessage!.content).toBe(mockToolSystemRole);
+ expect(systemMessage!.content).toContain('calculator');
+ expect(systemMessage!.content).toContain('weather');
// Should update metadata
- expect(result.metadata.toolSystemRole).toEqual({
- injected: true,
- toolsCount: 2,
- supportsFunctionCall: true,
- contentLength: mockToolSystemRole.length,
- });
+ expect(result.metadata.toolSystemRole).toBeDefined();
+ expect(result.metadata.toolSystemRole.injected).toBe(true);
+ expect(result.metadata.toolSystemRole.supportsFunctionCall).toBe(true);
});
it('should merge tool system role with existing system message', async () => {
- const mockGetToolSystemRoles = (tools: any[]) => mockToolSystemRole;
- const mockIsCanUseFC = (model: string, provider: string) => true;
+ const mockIsCanUseFC = () => true;
+ const manifests = createMockManifests(['calculator']);
const provider = new ToolSystemRoleProvider({
- tools: ['calculator'],
+ manifests,
model: 'gpt-4',
provider: 'openai',
- getToolSystemRoles: mockGetToolSystemRoles,
isCanUseFC: mockIsCanUseFC,
});
@@ -66,18 +69,17 @@ describe('ToolSystemRoleProvider', () => {
const result = await provider.process(ctx);
const systemMessage = result.messages.find((msg) => msg.role === 'system');
- expect(systemMessage!.content).toBe(`${existingSystemContent}\n\n${mockToolSystemRole}`);
+ expect(systemMessage!.content).toContain(existingSystemContent);
+ expect(systemMessage!.content).toContain('calculator');
});
- it('should skip injection when no tools are available', async () => {
- const mockGetToolSystemRoles = (tools: any[]) => mockToolSystemRole;
- const mockIsCanUseFC = (model: string, provider: string) => true;
+ it('should skip injection when no manifests are provided', async () => {
+ const mockIsCanUseFC = () => true;
const provider = new ToolSystemRoleProvider({
- tools: [],
+ manifests: [],
model: 'gpt-4',
provider: 'openai',
- getToolSystemRoles: mockGetToolSystemRoles,
isCanUseFC: mockIsCanUseFC,
});
@@ -95,14 +97,13 @@ describe('ToolSystemRoleProvider', () => {
});
it('should skip injection when function calling is not supported', async () => {
- const mockGetToolSystemRoles = (tools: any[]) => mockToolSystemRole;
- const mockIsCanUseFC = (model: string, provider: string) => false;
+ const mockIsCanUseFC = () => false;
+ const manifests = createMockManifests(['calculator']);
const provider = new ToolSystemRoleProvider({
- tools: ['calculator'],
+ manifests,
model: 'gpt-3.5-turbo',
provider: 'openai',
- getToolSystemRoles: mockGetToolSystemRoles,
isCanUseFC: mockIsCanUseFC,
});
@@ -116,15 +117,89 @@ describe('ToolSystemRoleProvider', () => {
expect(systemMessage).toBeUndefined();
});
- it('should skip injection when getToolSystemRoles returns undefined', async () => {
- const mockGetToolSystemRoles = (tools: any[]) => undefined;
- const mockIsCanUseFC = (model: string, provider: string) => true;
+ it('should inject manifest systemRole into the prompt', async () => {
+ const mockIsCanUseFC = () => true;
+
+ // Manifest with custom systemRole
+ const manifests: LobeToolManifest[] = [
+ {
+ identifier: 'gtd-tool',
+ api: [{ name: 'createTask', description: 'Create a task', parameters: {} }],
+ meta: { title: 'GTD Tool' },
+ type: 'builtin',
+ systemRole: 'You are a GTD expert. Always help users organize tasks effectively.',
+ },
+ ];
const provider = new ToolSystemRoleProvider({
- tools: ['calculator'],
+ manifests,
+ model: 'gpt-4',
+ provider: 'openai',
+ isCanUseFC: mockIsCanUseFC,
+ });
+
+ const messages = [{ id: 'u1', role: 'user', content: 'Create a task' }];
+
+ const ctx = createContext(messages);
+ const result = await provider.process(ctx);
+
+ const systemMessage = result.messages.find((msg) => msg.role === 'system');
+ expect(systemMessage).toBeDefined();
+ // Should contain the manifest's systemRole content
+ expect(systemMessage!.content).toContain('GTD expert');
+ expect(systemMessage!.content).toContain('organize tasks effectively');
+ });
+
+ it('should inject systemRole even when manifest has no apis', async () => {
+ const mockIsCanUseFC = () => true;
+
+ // Manifest with systemRole but no APIs
+ const manifests: LobeToolManifest[] = [
+ {
+ identifier: 'knowledge-tool',
+ api: [],
+ meta: { title: 'Knowledge Tool' },
+ type: 'builtin',
+ systemRole: 'You have access to a knowledge base. Use it wisely.',
+ },
+ ];
+
+ const provider = new ToolSystemRoleProvider({
+ manifests,
+ model: 'gpt-4',
+ provider: 'openai',
+ isCanUseFC: mockIsCanUseFC,
+ });
+
+ const messages = [{ id: 'u1', role: 'user', content: 'Search knowledge' }];
+
+ const ctx = createContext(messages);
+ const result = await provider.process(ctx);
+
+ const systemMessage = result.messages.find((msg) => msg.role === 'system');
+ expect(systemMessage).toBeDefined();
+ // Should contain the systemRole even without APIs
+ expect(systemMessage!.content).toContain('knowledge base');
+ expect(systemMessage!.content).toContain('Use it wisely');
+ });
+
+ it('should skip injection when manifests have no systemRole and no apis', async () => {
+ const mockIsCanUseFC = () => true;
+
+ // Empty manifests (no APIs)
+ const manifests: LobeToolManifest[] = [
+ {
+ identifier: 'empty-tool',
+ api: [],
+ meta: { title: 'Empty Tool' },
+ type: 'default',
+ },
+ ];
+
+ const provider = new ToolSystemRoleProvider({
+ manifests,
model: 'gpt-4',
provider: 'openai',
- getToolSystemRoles: mockGetToolSystemRoles,
isCanUseFC: mockIsCanUseFC,
});
@@ -133,7 +208,7 @@ describe('ToolSystemRoleProvider', () => {
const ctx = createContext(messages);
const result = await provider.process(ctx);
- // Should not have system message
+ // Should not have system message (empty tools produce no prompt)
const systemMessage = result.messages.find((msg) => msg.role === 'system');
expect(systemMessage).toBeUndefined();
});
diff --git a/src/features/ChatInput/ActionBar/Token/TokenTag.tsx b/src/features/ChatInput/ActionBar/Token/TokenTag.tsx
index d3b008159e9..ef0207feb0d 100644
--- a/src/features/ChatInput/ActionBar/Token/TokenTag.tsx
+++ b/src/features/ChatInput/ActionBar/Token/TokenTag.tsx
@@ -1,3 +1,5 @@
+import { ToolNameResolver } from '@lobechat/context-engine';
+import { pluginPrompts } from '@lobechat/prompts';
import { Center, Flexbox, Tooltip } from '@lobehub/ui';
import { TokenTag } from '@lobehub/ui/chat';
import { cssVar } from 'antd-style';
@@ -14,12 +16,14 @@ import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selec
import { useChatStore } from '@/store/chat';
import { dbMessageSelectors, topicSelectors } from '@/store/chat/selectors';
import { useToolStore } from '@/store/tool';
-import { toolSelectors } from '@/store/tool/selectors';
+import { pluginHelpers } from '@/store/tool/helpers';
import { useAgentId } from '../../hooks/useAgentId';
import ActionPopover from '../components/ActionPopover';
import TokenProgress from './TokenProgress';
+const toolNameResolver = new ToolNameResolver();
+
interface TokenTagProps {
total: string;
}
@@ -56,19 +60,33 @@ const Token = memo<TokenTagProps>(({ total: messageString }) => {
const canUseTool = useModelSupportToolUse(model, provider);
const pluginIds = useAgentStore((s) => agentByIdSelectors.getAgentPluginsById(agentId)(s));
- const toolsString = useToolStore((s) => {
+ const toolsString = useToolStore(() => {
const toolsEngine = createAgentToolsEngine({ model, provider });
- const { tools, enabledToolIds } = toolsEngine.generateToolsDetailed({
+ const { tools, enabledManifests } = toolsEngine.generateToolsDetailed({
model,
provider,
toolIds: pluginIds,
});
const schemaNumber = tools?.map((i) => JSON.stringify(i)).join('') || '';
- const pluginSystemRoles = toolSelectors.enabledSystemRoles(enabledToolIds)(s);
-
- return pluginSystemRoles + schemaNumber;
+ // Generate plugin system roles from enabledManifests
+ const toolsSystemRole =
+ enabledManifests.length > 0
+ ? pluginPrompts({
+ tools: enabledManifests.map((manifest) => ({
+ apis: manifest.api.map((api) => ({
+ desc: api.description,
+ name: toolNameResolver.generate(manifest.identifier, api.name, manifest.type),
+ })),
+ identifier: manifest.identifier,
+ name: pluginHelpers.getPluginTitle(manifest.meta) || manifest.identifier,
+ systemRole: manifest.systemRole,
+ })),
+ })
+ : '';
+
+ return toolsSystemRole + schemaNumber;
});
const toolsToken = useTokenCount(canUseTool ? toolsString : '');
diff --git a/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts b/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts
index bc3bec6615f..a334ce14afd 100644
--- a/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts
+++ b/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts
@@ -147,7 +147,21 @@ describe('serverMessagesEngine', () => {
describe('tools configuration', () => {
it('should handle tools system roles', async () => {
const messages = createBasicMessages();
- const getToolSystemRoles = vi.fn().mockReturnValue('Tool instructions');
+ const mockManifests = [
+ {
+ identifier: 'tool1',
+ api: [{ name: 'action', description: 'Tool 1 action', parameters: {} }],
+ meta: { title: 'Tool 1' },
+ type: 'default' as const,
+ systemRole: 'Tool 1 instructions',
+ },
+ {
+ identifier: 'tool2',
+ api: [{ name: 'action', description: 'Tool 2 action', parameters: {} }],
+ meta: { title: 'Tool 2' },
+ type: 'default' as const,
+ },
+ ];
const result = await serverMessagesEngine({
capabilities: { isCanUseFC: () => true },
@@ -156,30 +170,37 @@ describe('serverMessagesEngine', () => {
provider: 'openai',
systemRole: 'Base system role',
toolsConfig: {
- getToolSystemRoles,
+ manifests: mockManifests,
tools: ['tool1', 'tool2'],
},
});
- expect(getToolSystemRoles).toHaveBeenCalled();
+ // Should inject tool system role when manifests are provided
+ const systemMessage = result.find((msg) => msg.role === 'system');
+ expect(systemMessage).toBeDefined();
expect(result.length).toBeGreaterThan(0);
});
- it('should skip tool system role when no tools', async () => {
+ it('should skip tool system role when no manifests', async () => {
const messages = createBasicMessages();
- const getToolSystemRoles = vi.fn();
- await serverMessagesEngine({
+ const result = await serverMessagesEngine({
messages,
model: 'gpt-4',
provider: 'openai',
toolsConfig: {
- getToolSystemRoles,
+ manifests: [],
tools: [],
},
});
- expect(getToolSystemRoles).not.toHaveBeenCalled();
+ // Without manifests, no tool-related system role should be injected
+ const systemMessages = result.filter((msg) => msg.role === 'system');
+ const hasToolSystemRole = systemMessages.some((msg) => {
+ const content = typeof msg.content === 'string' ? msg.content : '';
+ return content.includes('plugins');
+ });
+ expect(hasToolSystemRole).toBe(false);
});
});
diff --git a/src/server/modules/Mecha/ContextEngineering/index.ts b/src/server/modules/Mecha/ContextEngineering/index.ts
index b71539449c3..9f92e4a5134 100644
--- a/src/server/modules/Mecha/ContextEngineering/index.ts
+++ b/src/server/modules/Mecha/ContextEngineering/index.ts
@@ -95,7 +95,7 @@ export const serverMessagesEngine = async ({
// Tools configuration
toolsConfig: {
- getToolSystemRoles: toolsConfig?.getToolSystemRoles,
+ manifests: toolsConfig?.manifests,
tools: toolsConfig?.tools,
},
diff --git a/src/server/modules/Mecha/ContextEngineering/types.ts b/src/server/modules/Mecha/ContextEngineering/types.ts
index 6c52d4d6891..7c4b3c51018 100644
--- a/src/server/modules/Mecha/ContextEngineering/types.ts
+++ b/src/server/modules/Mecha/ContextEngineering/types.ts
@@ -2,6 +2,7 @@ import type {
AgentBuilderContext,
FileContent,
KnowledgeBaseInfo,
+ LobeToolManifest,
UserMemoryData,
} from '@lobechat/context-engine';
import type { PageContentContext } from '@lobechat/prompts';
@@ -33,9 +34,9 @@ export interface ServerKnowledgeConfig {
* Tools configuration for server context engineering
*/
export interface ServerToolsConfig {
- /** Function to get tool system roles */
- getToolSystemRoles?: (tools: string[]) => string | undefined;
- /** Enabled tool IDs */
+ /** Tool manifests with systemRole and API definitions */
+ manifests?: LobeToolManifest[];
+ /** Enabled tool IDs (kept for compatibility) */
tools?: string[];
}
diff --git a/src/services/chat/index.ts b/src/services/chat/index.ts
index 78ce7d7eafc..0609d752c8f 100644
--- a/src/services/chat/index.ts
+++ b/src/services/chat/index.ts
@@ -18,7 +18,10 @@ import {
TraceTagMap,
type UIChatMessage,
} from '@lobechat/types';
-import { type PluginRequestPayload, createHeadersWithPluginSettings } from '@lobehub/chat-plugin-sdk';
+import {
+ type PluginRequestPayload,
+ createHeadersWithPluginSettings,
+} from '@lobehub/chat-plugin-sdk';
import { merge } from 'es-toolkit/compat';
import { ModelProvider } from 'model-bank';
@@ -98,7 +101,14 @@ interface CreateAssistantMessageStream extends FetchSSEOptions {
class ChatService {
createAssistantMessage = async (
- { plugins: enabledPlugins, messages, agentId, groupId, scope, ...params }: GetChatCompletionPayload,
+ {
+ plugins: enabledPlugins,
+ messages,
+ agentId,
+ groupId,
+ scope,
+ ...params
+ }: GetChatCompletionPayload,
options?: FetchOptions,
) => {
const payload = merge(
@@ -138,7 +148,7 @@ class ChatService {
provider: payload.provider!,
});
- const { tools, enabledToolIds } = toolsEngine.generateToolsDetailed({
+ const { tools, enabledToolIds, enabledManifests } = toolsEngine.generateToolsDetailed({
model: payload.model,
provider: payload.provider!,
toolIds: pluginIds,
@@ -228,6 +238,7 @@ class ChatService {
// Page editor context from agent runtime
initialContext: options?.initialContext,
inputTemplate: chatConfig.inputTemplate,
+ manifests: enabledManifests,
messages,
model: payload.model,
provider: payload.provider!,
@@ -456,20 +467,22 @@ class ChatService {
onLoadingChange?.(true);
try {
- const llmMessages = await contextEngineering({
- messages: params.messages as any,
- model: params.model!,
- provider: params.provider!,
- tools: params.plugins,
- });
// Use simple tools engine without complex search logic
const toolsEngine = createToolsEngine();
- const tools = toolsEngine.generateTools({
+ const { tools, enabledManifests } = toolsEngine.generateToolsDetailed({
model: params.model!,
provider: params.provider!,
toolIds: params.plugins,
});
+ const llmMessages = await contextEngineering({
+ manifests: enabledManifests,
+ messages: params.messages as any,
+ model: params.model!,
+ provider: params.provider!,
+ tools: params.plugins,
+ });
+
// remove plugins
delete params.plugins;
await this.getChatCompletion(
diff --git a/src/services/chat/mecha/agentConfigResolver.test.ts b/src/services/chat/mecha/agentConfigResolver.test.ts
index 69f140fd072..0cd95bafeee 100644
--- a/src/services/chat/mecha/agentConfigResolver.test.ts
+++ b/src/services/chat/mecha/agentConfigResolver.test.ts
@@ -1,4 +1,6 @@
import * as builtinAgents from '@lobechat/builtin-agents';
+import { GTDIdentifier } from '@lobechat/builtin-tool-gtd';
+import { NotebookIdentifier } from '@lobechat/builtin-tool-notebook';
import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -404,6 +406,42 @@ describe('resolveAgentConfig', () => {
expect(result.chatConfig).toEqual(mockChatConfig);
});
+
+ describe('inbox agent', () => {
+ beforeEach(() => {
+ vi.spyOn(agentSelectors.agentSelectors, 'getAgentSlugById').mockReturnValue(() => 'inbox');
+ });
+
+ it('should include GTD and Notebook tools in plugins', () => {
+ vi.spyOn(builtinAgents, 'getAgentRuntimeConfig').mockReturnValue({
+ plugins: [GTDIdentifier, NotebookIdentifier],
+ systemRole: 'Inbox system role',
+ });
+
+ const result = resolveAgentConfig({ agentId: 'inbox-agent' });
+
+ expect(result.plugins).toContain(GTDIdentifier);
+ expect(result.plugins).toContain(NotebookIdentifier);
+ expect(result.isBuiltinAgent).toBe(true);
+ expect(result.slug).toBe('inbox');
+ });
+
+ it('should preserve user plugins while including GTD and Notebook', () => {
+ vi.spyOn(builtinAgents, 'getAgentRuntimeConfig').mockReturnValue({
+ plugins: [GTDIdentifier, NotebookIdentifier, 'user-plugin'],
+ systemRole: 'Inbox system role',
+ });
+
+ const result = resolveAgentConfig({
+ agentId: 'inbox-agent',
+ plugins: ['user-plugin'],
+ });
+
+ expect(result.plugins).toContain(GTDIdentifier);
+ expect(result.plugins).toContain(NotebookIdentifier);
+ expect(result.plugins).toContain('user-plugin');
+ });
+ });
});
describe('Page Editor Integration (scope: page)', () => {
@@ -467,7 +505,9 @@ describe('resolveAgentConfig', () => {
scope: 'page',
});
- expect(result.agentConfig.systemRole).toBe('Page agent system prompt with XML instructions...');
+ expect(result.agentConfig.systemRole).toBe(
+ 'Page agent system prompt with XML instructions...',
+ );
});
it('should not inject page-agent for non-page scope', () => {
diff --git a/src/services/chat/mecha/agentConfigResolver.ts b/src/services/chat/mecha/agentConfigResolver.ts
index 58251ed872a..b92fd983a64 100644
--- a/src/services/chat/mecha/agentConfigResolver.ts
+++ b/src/services/chat/mecha/agentConfigResolver.ts
@@ -1,6 +1,10 @@
import { BUILTIN_AGENT_SLUGS, getAgentRuntimeConfig } from '@lobechat/builtin-agents';
import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
-import { type LobeAgentChatConfig, type LobeAgentConfig, type MessageMapScope } from '@lobechat/types';
+import {
+ type LobeAgentChatConfig,
+ type LobeAgentConfig,
+ type MessageMapScope,
+} from '@lobechat/types';
import { produce } from 'immer';
import { getAgentStoreState } from '@/store/agent';
@@ -95,13 +99,6 @@ export interface ResolvedAgentConfig {
export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAgentConfig => {
const { agentId, model, documentContent, plugins, targetAgentConfig } = ctx;
- // Debug logging for page editor
- console.log('[agentConfigResolver] Resolving agent config:', {
- agentId,
- plugins,
- scope: ctx.scope,
- });
-
const agentStoreState = getAgentStoreState();
// Get base config from store
@@ -114,10 +111,7 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge
// Check if this is a builtin agent
const slug = agentSelectors.getAgentSlugById(agentId)(agentStoreState);
- console.log('[agentConfigResolver] Agent type check:', { isBuiltin: !!slug, slug });
-
if (!slug) {
- console.log('[agentConfigResolver] Taking CUSTOM AGENT branch');
// Regular agent - use provided plugins if available, fallback to agent's plugins
const finalPlugins = plugins && plugins.length > 0 ? plugins : basePlugins;
@@ -129,8 +123,6 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge
// When custom agent is used in page editor (scope === 'page'),
// automatically inject page-agent tools and system role
if (ctx.scope === 'page') {
- console.log('[agentConfigResolver] Page scope detected! Injecting page-agent tools...');
-
// 1. Inject page-agent tool if not already present
const pageAgentPlugins = finalPlugins.includes(PageAgentIdentifier)
? finalPlugins
@@ -141,9 +133,12 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge
const pageAgentSystemRole = pageAgentRuntime?.systemRole || '';
// 3. Merge system roles: custom agent's role + page-agent role
- const mergedSystemRole = agentConfig.systemRole
- ? `${agentConfig.systemRole}\n\n${pageAgentSystemRole}`
- : pageAgentSystemRole;
+ // Only append page-agent role if it exists
+ const mergedSystemRole = pageAgentSystemRole
+ ? agentConfig.systemRole
+ ? `${agentConfig.systemRole}\n\n${pageAgentSystemRole}`
+ : pageAgentSystemRole
+ : agentConfig.systemRole || '';
finalAgentConfig = {
...finalAgentConfig,
@@ -156,12 +151,6 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge
enableHistoryCount: false, // Disable history truncation for full document context
};
- console.log('[agentConfigResolver] Page-agent injection complete:', {
- chatConfig: finalChatConfig,
- plugins: pageAgentPlugins,
- systemRoleLength: mergedSystemRole.length,
- });
-
return {
agentConfig: finalAgentConfig,
chatConfig: finalChatConfig,
@@ -179,8 +168,6 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge
};
}
- console.log('[agentConfigResolver] Taking BUILTIN AGENT branch, slug:', slug);
-
// Build groupSupervisorContext if this is a group-supervisor agent
let groupSupervisorContext;
if (slug === BUILTIN_AGENT_SLUGS.groupSupervisor) {
@@ -227,8 +214,6 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge
// When a builtin agent (other than page-agent itself) is used in page editor,
// inject page-agent tools and system role
if (ctx.scope === 'page' && slug !== BUILTIN_AGENT_SLUGS.pageAgent) {
- console.log('[agentConfigResolver] Builtin agent in page scope! Injecting page-agent tools...');
-
// 1. Inject page-agent tool if not already present
if (!finalPlugins.includes(PageAgentIdentifier)) {
finalPlugins = [PageAgentIdentifier, ...finalPlugins];
@@ -250,12 +235,6 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge
...resolvedChatConfig,
enableHistoryCount: false,
};
-
- console.log('[agentConfigResolver] Page-agent injection complete for builtin agent:', {
- plugins: finalPlugins,
- slug,
- systemRoleLength: resolvedSystemRole.length,
- });
}
// Merge runtime systemRole into agent config
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index d0c80840d6c..fe2cfb9ae86 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -6,6 +6,7 @@ import {
type AgentGroupConfig,
type GroupAgentBuilderContext,
type GroupOfficialToolItem,
+ type LobeToolManifest,
MessagesEngine,
} from '@lobechat/context-engine';
import { historySummaryPrompt } from '@lobechat/prompts';
@@ -25,7 +26,7 @@ import { getChatGroupStoreState } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
import { getChatStoreState } from '@/store/chat';
import { getToolStoreState } from '@/store/tool';
-import { builtinToolSelectors, klavisStoreSelectors, toolSelectors } from '@/store/tool/selectors';
+import { builtinToolSelectors, klavisStoreSelectors } from '@/store/tool/selectors';
import { isCanUseVideo, isCanUseVision } from '../helper';
import {
@@ -53,6 +54,8 @@ interface ContextEngineeringContext {
*/
initialContext?: RuntimeInitialContext;
inputTemplate?: string;
+ /** Tool manifests with systemRole and API definitions */
+ manifests?: LobeToolManifest[];
messages: UIChatMessage[];
model: string;
provider: string;
@@ -69,6 +72,7 @@ interface ContextEngineeringContext {
// REVIEW:可能这里可以约束一下 identity,preference,exp 的 重新排序或者裁切过的上下文进来而不是全部丢进来
export const contextEngineering = async ({
messages = [],
+ manifests,
tools,
model,
provider,
@@ -291,7 +295,7 @@ export const contextEngineering = async ({
// Tools configuration
toolsConfig: {
- getToolSystemRoles: (tools) => toolSelectors.enabledSystemRoles(tools)(getToolStoreState()),
+ manifests,
tools,
},
diff --git a/src/store/tool/selectors/tool.ts b/src/store/tool/selectors/tool.ts
index 04fa6ebc8e5..9d3b6af155c 100644
--- a/src/store/tool/selectors/tool.ts
+++ b/src/store/tool/selectors/tool.ts
@@ -1,49 +1,13 @@
-import { ToolNameResolver } from '@lobechat/context-engine';
-import { pluginPrompts } from '@lobechat/prompts';
import { type RenderDisplayControl } from '@lobechat/types';
import type { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';
import { type MetaData } from '@/types/meta';
import { type LobeToolMeta } from '@/types/tool/tool';
-import { pluginHelpers } from '../helpers';
import { type ToolStoreState } from '../initialState';
import { builtinToolSelectors } from '../slices/builtin/selectors';
import { pluginSelectors } from '../slices/plugin/selectors';
-const toolNameResolver = new ToolNameResolver();
-
-const enabledSystemRoles =
- (tools: string[] = []) =>
- (s: ToolStoreState) => {
- const toolsSystemRole = pluginSelectors
- .installedPluginManifestList(s)
- .concat(s.builtinTools.map((b) => b.manifest as LobeChatPluginManifest))
- // 如果存在 enabledPlugins,那么只启用 enabledPlugins 中的插件
- .filter((m) => m && tools.includes(m.identifier))
- .map((manifest) => {
- const meta = manifest.meta || {};
-
- const title = pluginHelpers.getPluginTitle(meta) || manifest.identifier;
-
- return {
- apis: manifest.api.map((m) => ({
- desc: m.description,
- name: toolNameResolver.generate(manifest.identifier, m.name, manifest.type),
- })),
- identifier: manifest.identifier,
- name: title,
- systemRole: manifest.systemRole,
- };
- });
-
- if (toolsSystemRole.length > 0) {
- return pluginPrompts({ tools: toolsSystemRole });
- }
-
- return '';
- };
-
const metaList = (s: ToolStoreState): LobeToolMeta[] => {
const pluginList = pluginSelectors.installedPluginMetaList(s) as LobeToolMeta[];
@@ -117,7 +81,6 @@ const getRenderDisplayControl =
};
export const toolSelectors = {
- enabledSystemRoles,
getManifestById,
getManifestLoadingStatus,
getMetaById,