🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🔨 chore: add disableTools option to execAgent (#13454)
Arvin Xufee0fe569942
diff --git a/src/server/services/aiAgent/__tests__/execAgent.disableTools.test.ts b/src/server/services/aiAgent/__tests__/execAgent.disableTools.test.tsnew file mode 100644index 00000000000..0acd13d6d61--- /dev/null+++ b/src/server/services/aiAgent/__tests__/execAgent.disableTools.test.ts@@ -0,0 +1,178 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AiAgentService } from '../index';++const {+ mockCreateOperation,+ mockCreateServerAgentToolsEngine,+ mockGetAgentConfig,+ mockGetKlavisManifests,+ mockGetLobehubSkillManifests,+ mockMessageCreate,+ mockPluginQuery,+} = vi.hoisted(() => ({+ mockCreateOperation: vi.fn(),+ mockCreateServerAgentToolsEngine: vi.fn().mockReturnValue({+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),+ }),+ mockGetAgentConfig: vi.fn(),+ mockGetKlavisManifests: vi.fn().mockResolvedValue([]),+ mockGetLobehubSkillManifests: vi.fn().mockResolvedValue([]),+ mockMessageCreate: vi.fn(),+ mockPluginQuery: vi.fn().mockResolvedValue([]),+}));++vi.mock('@/libs/trusted-client', () => ({+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),+}));++vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(() => ({+ create: mockMessageCreate,+ query: vi.fn().mockResolvedValue([]),+ update: vi.fn().mockResolvedValue({}),+ })),+}));++vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn().mockImplementation(() => ({+ getAgentConfig: vi.fn(),+ })),+}));++vi.mock('@/server/services/agent', () => ({+ AgentService: vi.fn().mockImplementation(() => ({+ getAgentConfig: mockGetAgentConfig,+ })),+}));++vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn().mockImplementation(() => ({+ query: mockPluginQuery,+ })),+}));++vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(() => ({+ create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ })),+}));++vi.mock('@/database/models/thread', () => ({+ ThreadModel: vi.fn().mockImplementation(() => ({+ create: vi.fn(),+ findById: vi.fn(),+ update: vi.fn(),+ })),+}));++vi.mock('@/server/services/agentRuntime', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(() => ({+ createOperation: mockCreateOperation,+ })),+}));++vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn().mockImplementation(() => ({+ getLobehubSkillManifests: mockGetLobehubSkillManifests,+ })),+}));++vi.mock('@/server/services/klavis', () => ({+ KlavisService: vi.fn().mockImplementation(() => ({+ getKlavisManifests: mockGetKlavisManifests,+ })),+}));++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn().mockImplementation(() => ({+ uploadFromUrl: vi.fn(),+ })),+}));++vi.mock('@/server/modules/Mecha', () => ({+ createServerAgentToolsEngine: mockCreateServerAgentToolsEngine,+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),+}));++vi.mock('@/server/services/toolExecution/deviceProxy', () => ({+ deviceProxy: {+ isConfigured: false,+ queryDeviceList: vi.fn().mockResolvedValue([]),+ },+}));++vi.mock('model-bank', () => ({+ LOBE_DEFAULT_MODEL_LIST: [+ {+ abilities: { functionCall: true },+ id: 'gpt-4',+ providerId: 'openai',+ },+ ],+}));++describe('AiAgentService.execAgent - disableTools', () => {+ let service: AiAgentService;+ const mockDb = {} as any;+ const userId = 'test-user-id';++ beforeEach(() => {+ vi.clearAllMocks();+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });+ mockCreateOperation.mockResolvedValue({+ autoStarted: true,+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ success: true,+ });+ mockGetAgentConfig.mockResolvedValue({+ chatConfig: {},+ id: 'agent-1',+ model: 'gpt-4',+ plugins: ['plugin-a'],+ provider: 'openai',+ systemRole: 'You are a helper',+ });+ service = new AiAgentService(mockDb, userId);+ });++ it('should skip all tool discovery when disableTools is true', async () => {+ await service.execAgent({+ agentId: 'agent-1',+ disableTools: true,+ prompt: 'Hello',+ } as any);++ // Plugin DB query should NOT be called+ expect(mockPluginQuery).not.toHaveBeenCalled();++ // Manifest fetches should NOT be called+ expect(mockGetLobehubSkillManifests).not.toHaveBeenCalled();+ expect(mockGetKlavisManifests).not.toHaveBeenCalled();++ // ToolsEngine should NOT be created+ expect(mockCreateServerAgentToolsEngine).not.toHaveBeenCalled();++ // createOperation should still be called with tools=undefined+ expect(mockCreateOperation).toHaveBeenCalledTimes(1);+ const callArgs = mockCreateOperation.mock.calls[0][0];+ expect(callArgs.tools).toBeUndefined();+ });++ it('should perform full tool discovery when disableTools is not set', async () => {+ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Hello',+ });++ // All tool discovery steps should be called+ expect(mockPluginQuery).toHaveBeenCalledTimes(1);+ expect(mockGetLobehubSkillManifests).toHaveBeenCalledTimes(1);+ expect(mockGetKlavisManifests).toHaveBeenCalledTimes(1);+ expect(mockCreateServerAgentToolsEngine).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex 1080e5d1ef4..d66f83ec918 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -104,6 +104,8 @@ interface InternalExecAgentParams extends ExecAgentParams {};/** Cron job ID that triggered this execution (if trigger is 'cron') */cronJobId?: string;+ /** Disable all tools (no plugins, no system manifests). Useful for eval/benchmark scenarios. */+ disableTools?: boolean;/** Discord context for injecting channel/guild info into agent system message */discordContext?: any;/** Eval context for injecting environment prompts into system message */@@ -385,36 +387,7 @@ export class AiAgentService {const model = agentConfig.model!;const provider = agentConfig.provider!;- // 4. Get installed plugins from database- const installedPlugins = await this.pluginModel.query();- log('execAgent: got %d installed plugins', installedPlugins.length);-- // 5. Get model abilities from model-bank for function calling support check- const { LOBE_DEFAULT_MODEL_LIST } = await import('model-bank');- const isModelSupportToolUse = (m: string, p: string) => {- const info = LOBE_DEFAULT_MODEL_LIST.find((item) => item.id === m && item.providerId === p);- return info?.abilities?.functionCall ?? true;- };-- // 6. Fetch LobeHub Skills manifests (temporary solution until LOBE-3517 is implemented)- let lobehubSkillManifests: LobeToolManifest[] = [];- try {- lobehubSkillManifests = await this.marketService.getLobehubSkillManifests();- } catch (error) {- log('execAgent: failed to fetch lobehub skill manifests: %O', error);- }- log('execAgent: got %d lobehub skill manifests', lobehubSkillManifests.length);-- // 7. Fetch Klavis tool manifests from database- let klavisManifests: LobeToolManifest[] = [];- try {- klavisManifests = await this.klavisService.getKlavisManifests();- } catch (error) {- log('execAgent: failed to fetch klavis manifests: %O', error);- }- log('execAgent: got %d klavis manifests', klavisManifests.length);-- // 8. Fetch user settings (memory config + timezone)+ // 4. Fetch user settings (memory config + timezone)// Agent-level memory config takes priority; fallback to user-level settingconst agentMemoryEnabled = agentConfig.chatConfig?.memory?.enabled;let globalMemoryEnabled = agentMemoryEnabled ?? false;@@ -437,129 +410,172 @@ export class AiAgentService {userTimezone ?? 'default',);- await throwIfExecutionAborted('tool discovery');+ // 5. Tool discovery — short-circuit when disableTools is set+ let tools: any[] | undefined;+ let toolsResult: { enabledToolIds: string[]; tools?: any[] | undefined } = {+ enabledToolIds: [],+ tools: undefined,+ };+ const toolManifestMap: Record<string, any> = {};+ const toolSourceMap: Record<string, ToolSource> = {};+ let onlineDevices: DeviceAttachment[] = [];+ let activeDeviceId: string | undefined;+ let hasAgentDocuments = false;+ let hasEnabledKnowledgeBases = false;+ const isBotConversation = !!(botContext || discordContext);- // 9. Create tools using Server AgentToolsEngine- const hasEnabledKnowledgeBases =- agentConfig.knowledgeBases?.some((kb: { enabled?: boolean | null }) => kb.enabled === true) ??- false;+ // These are needed outside the tools block (for agent management context, skill engine, etc.)+ let lobehubSkillManifests: LobeToolManifest[] = [];+ let klavisManifests: LobeToolManifest[] = [];+ let agentPlugins: string[] = [...(agentConfig?.plugins ?? []), ...(additionalPluginIds || [])];- // Check if agent has documents (for auto-enabling agent-documents tool)- let hasAgentDocuments = false;- try {- const docs = await this.agentDocumentsService.getAgentDocuments(resolvedAgentId);- hasAgentDocuments = docs.length > 0;- } catch {- // Agent documents check is non-critical- }+ // model-bank is needed both for tool support check and model metadata+ const { LOBE_DEFAULT_MODEL_LIST } = await import('model-bank');- // Auto-enable message tool when request comes from a bot conversation (e.g., Discord, Slack, Telegram)- const isBotConversation = !!(botContext || discordContext);- log('execAgent: isBotConversation=%s', isBotConversation);+ if (params.disableTools) {+ log('execAgent: tools disabled by disableTools flag, skipping all tool discovery');+ } else {+ // 5a. Get installed plugins from database+ const installedPlugins = await this.pluginModel.query();+ log('execAgent: got %d installed plugins', installedPlugins.length);++ // 5b. Get model abilities from model-bank for function calling support check+ const isModelSupportToolUse = (m: string, p: string) => {+ const info = LOBE_DEFAULT_MODEL_LIST.find((item) => item.id === m && item.providerId === p);+ return info?.abilities?.functionCall ?? true;+ };- // Build device context for ToolsEngine enableChecker- const gatewayConfigured = deviceProxy.isConfigured;- const boundDeviceId = agentConfig.agencyConfig?.boundDeviceId;- let onlineDevices: DeviceAttachment[] = [];- if (gatewayConfigured) {+ // 5c. Fetch LobeHub Skills manifeststry {- onlineDevices = await deviceProxy.queryDeviceList(this.userId);- log('execAgent: found %d online device(s)', onlineDevices.length);+ lobehubSkillManifests = await this.marketService.getLobehubSkillManifests();} catch (error) {- log('execAgent: failed to query device list: %O', error);+ log('execAgent: failed to fetch lobehub skill manifests: %O', error);}- }- const deviceOnline = onlineDevices.length > 0;+ log('execAgent: got %d lobehub skill manifests', lobehubSkillManifests.length);- const toolsContext: ServerAgentToolsContext = {- installedPlugins,- isModelSupportToolUse,- };+ // 5d. Fetch Klavis tool manifests from database+ try {+ klavisManifests = await this.klavisService.getKlavisManifests();+ } catch (error) {+ log('execAgent: failed to fetch klavis manifests: %O', error);+ }+ log('execAgent: got %d klavis manifests', klavisManifests.length);- // Dynamically inject topic-reference tool when prompt contains <refer_topic> tags- const hasTopicReference = /refer_topic/.test(prompt ?? '');- const agentPlugins = [- ...(agentConfig?.plugins ?? []),- ...(additionalPluginIds || []),- ...(hasTopicReference ? ['lobe-topic-reference'] : []),- ...(isBotConversation ? [MessageToolIdentifier] : []),- ];+ await throwIfExecutionAborted('tool discovery');- // Derive activeDeviceId from device context:- // 1. If agent has a bound device and it's online, use it- // 2. In IM/Bot scenarios, auto-activate when exactly one device is online- const activeDeviceId = boundDeviceId- ? deviceOnline- ? boundDeviceId- : undefined- : (discordContext || botContext) && onlineDevices.length === 1- ? onlineDevices[0].deviceId- : undefined;-- const toolsEngine = createServerAgentToolsEngine(toolsContext, {- additionalManifests: [...lobehubSkillManifests, ...klavisManifests],- agentConfig: {- chatConfig: agentConfig.chatConfig ?? undefined,- plugins: agentPlugins,- },- deviceContext: gatewayConfigured- ? {- autoActivated: activeDeviceId ? true : undefined,- boundDeviceId,- deviceOnline,- gatewayConfigured: true,- }- : undefined,- globalMemoryEnabled,- hasAgentDocuments,- hasEnabledKnowledgeBases,- isBotConversation,- model,- provider,- });+ // 5e. Create tools using Server AgentToolsEngine+ hasEnabledKnowledgeBases =+ agentConfig.knowledgeBases?.some(+ (kb: { enabled?: boolean | null }) => kb.enabled === true,+ ) ?? false;- // Generate tools and manifest map- // Include device tool IDs so ToolsEngine can process them via enableChecker- const pluginIds = [- ...(agentConfig.plugins || []),- ...(additionalPluginIds || []),- LocalSystemManifest.identifier,- RemoteDeviceManifest.identifier,- ...(isBotConversation ? [MessageToolIdentifier] : []),- ];- log('execAgent: agent configured plugins: %O', pluginIds);+ try {+ const docs = await this.agentDocumentsService.getAgentDocuments(resolvedAgentId);+ hasAgentDocuments = docs.length > 0;+ } catch {+ // Agent documents check is non-critical+ }- // When skillActivateMode is 'manual', exclude only discovery tools (lobe-activator, lobe-skill-store)- // so that externally enabled tools (sandbox, web browsing, etc.) remain available- const isManualMode = agentConfig.chatConfig?.skillActivateMode === 'manual';+ log('execAgent: isBotConversation=%s', isBotConversation);- const toolsResult = toolsEngine.generateToolsDetailed({- excludeDefaultToolIds: isManualMode ? manualModeExcludeToolIds : undefined,- model,- provider,- toolIds: pluginIds,- });+ // Build device context for ToolsEngine enableChecker+ const gatewayConfigured = deviceProxy.isConfigured;+ const boundDeviceId = agentConfig.agencyConfig?.boundDeviceId;+ if (gatewayConfigured) {+ try {+ onlineDevices = await deviceProxy.queryDeviceList(this.userId);+ log('execAgent: found %d online device(s)', onlineDevices.length);+ } catch (error) {+ log('execAgent: failed to query device list: %O', error);+ }+ }+ const deviceOnline = onlineDevices.length > 0;- const tools = toolsResult.tools;+ const toolsContext: ServerAgentToolsContext = {+ installedPlugins,+ isModelSupportToolUse,+ };- log('execAgent: enabled tool ids: %O', toolsResult.enabledToolIds);+ // Dynamically inject topic-reference tool when prompt contains <refer_topic> tags+ const hasTopicReference = /refer_topic/.test(prompt ?? '');+ agentPlugins = [+ ...agentPlugins,+ ...(hasTopicReference ? ['lobe-topic-reference'] : []),+ ...(isBotConversation ? [MessageToolIdentifier] : []),+ ];- // Get manifest map and convert from Map to Record- const manifestMap = toolsEngine.getEnabledPluginManifests(pluginIds);- const toolManifestMap: Record<string, any> = {};- manifestMap.forEach((manifest, id) => {- toolManifestMap[id] = manifest;- });+ // Derive activeDeviceId from device context+ activeDeviceId = boundDeviceId+ ? deviceOnline+ ? boundDeviceId+ : undefined+ : (discordContext || botContext) && onlineDevices.length === 1+ ? onlineDevices[0].deviceId+ : undefined;- // Build toolSourceMap for routing tool execution- const toolSourceMap: Record<string, ToolSource> = {};- // Mark lobehub skills- for (const manifest of lobehubSkillManifests) {- toolSourceMap[manifest.identifier] = 'lobehubSkill';- }- // Mark klavis tools- for (const manifest of klavisManifests) {- toolSourceMap[manifest.identifier] = 'klavis';+ const toolsEngine = createServerAgentToolsEngine(toolsContext, {+ additionalManifests: [...lobehubSkillManifests, ...klavisManifests],+ agentConfig: {+ chatConfig: agentConfig.chatConfig ?? undefined,+ plugins: agentPlugins,+ },+ deviceContext: gatewayConfigured+ ? {+ autoActivated: activeDeviceId ? true : undefined,+ boundDeviceId,+ deviceOnline,+ gatewayConfigured: true,+ }+ : undefined,+ globalMemoryEnabled,+ hasAgentDocuments,+ hasEnabledKnowledgeBases,+ isBotConversation,+ model,+ provider,+ });++ // 5f. Generate tools and manifest map+ const pluginIds = [+ ...(agentConfig.plugins || []),+ ...(additionalPluginIds || []),+ LocalSystemManifest.identifier,+ RemoteDeviceManifest.identifier,+ ...(isBotConversation ? [MessageToolIdentifier] : []),+ ];+ log('execAgent: agent configured plugins: %O', pluginIds);++ const isManualMode = agentConfig.chatConfig?.skillActivateMode === 'manual';++ toolsResult = toolsEngine.generateToolsDetailed({+ excludeDefaultToolIds: isManualMode ? manualModeExcludeToolIds : undefined,+ model,+ provider,+ toolIds: pluginIds,+ });++ tools = toolsResult.tools;++ log('execAgent: enabled tool ids: %O', toolsResult.enabledToolIds);++ const manifestMap = toolsEngine.getEnabledPluginManifests(pluginIds);+ manifestMap.forEach((manifest, id) => {+ toolManifestMap[id] = manifest;+ });++ for (const manifest of lobehubSkillManifests) {+ toolSourceMap[manifest.identifier] = 'lobehubSkill';+ }+ for (const manifest of klavisManifests) {+ toolSourceMap[manifest.identifier] = 'klavis';+ }++ log(+ 'execAgent: generated %d tools, %d lobehub skills, %d klavis tools',+ tools?.length ?? 0,+ lobehubSkillManifests.length,+ klavisManifests.length,+ );}// Inject client function tools from Response API@@ -589,15 +605,6 @@ export class AiAgentService {toolsResult.enabledToolIds.push(CLIENT_FN_IDENTIFIER);}- log(- 'execAgent: generated %d tools from %d configured plugins, %d lobehub skills, %d klavis tools, %d client function tools',- tools?.length ?? 0,- pluginIds.length,- lobehubSkillManifests.length,- klavisManifests.length,- functionTools?.length ?? 0,- );-// Override RemoteDevice manifest's systemRole with dynamic device list prompt// The manifest is already included/excluded by ToolsEngine enableCheckerif (toolManifestMap[RemoteDeviceManifest.identifier]) {