🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
feat: Swtich agent
Rene Wang1a82a12cac01
diff --git a/src/services/chat/index.ts b/src/services/chat/index.tsindex 232fa01c19a..78ce7d7eafc 100644--- a/src/services/chat/index.ts+++ b/src/services/chat/index.ts@@ -11,6 +11,7 @@ import {import { AgentRuntimeError, type ChatCompletionErrorPayload } from '@lobechat/model-runtime';import {ChatErrorType,+ type MessageMapScope,type RuntimeInitialContext,type RuntimeStepContext,type TracePayload,@@ -62,6 +63,7 @@ interface GetChatCompletionPayload extends Partial<Omit<ChatStreamPayload, 'messagentId?: string;groupId?: string;messages: UIChatMessage[];+ scope?: MessageMapScope;}type ChatStreamInputParams = Partial<Omit<ChatStreamPayload, 'messages'>> & {@@ -96,7 +98,7 @@ interface CreateAssistantMessageStream extends FetchSSEOptions {class ChatService {createAssistantMessage = async (- { plugins: enabledPlugins, messages, agentId, groupId, ...params }: GetChatCompletionPayload,+ { plugins: enabledPlugins, messages, agentId, groupId, scope, ...params }: GetChatCompletionPayload,options?: FetchOptions,) => {const payload = merge(@@ -112,6 +114,8 @@ class ChatService {const targetAgentId = getTargetAgentId(agentId);+ console.log('[chatService.createAssistantMessage] Resolving with scope:', scope);+// Resolve agent config with builtin agent runtime config merged// plugins is already merged (runtime plugins > agent config plugins)const {@@ -123,6 +127,7 @@ class ChatService {model: payload.model,plugins: enabledPlugins,provider: payload.provider,+ scope, // Pass scope to preserve page-agent injection});// Get search config with agentId for agent-specific settingsdiff --git a/src/services/chat/mecha/agentConfigResolver.test.ts b/src/services/chat/mecha/agentConfigResolver.test.tsindex 48e3ab0a9a0..a3c1519f473 100644--- a/src/services/chat/mecha/agentConfigResolver.test.ts+++ b/src/services/chat/mecha/agentConfigResolver.test.ts@@ -1,4 +1,5 @@import * as builtinAgents from '@lobechat/builtin-agents';+import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';import { beforeEach, describe, expect, it, vi } from 'vitest';import * as agentStore from '@/store/agent';@@ -404,4 +405,182 @@ describe('resolveAgentConfig', () => {expect(result.chatConfig).toEqual(mockChatConfig);});});++ describe('Page Editor Integration (scope: page)', () => {+ beforeEach(() => {+ // No slug means regular agent+ vi.spyOn(agentSelectors.agentSelectors, 'getAgentSlugById').mockReturnValue(() => undefined);++ // Mock page-agent runtime config+ vi.spyOn(builtinAgents, 'getAgentRuntimeConfig').mockReturnValue({+ plugins: [PageAgentIdentifier],+ systemRole: 'Page agent system prompt with XML instructions...',+ });+ });++ it('should inject page-agent tools for custom agent in page scope', () => {+ const result = resolveAgentConfig({+ agentId: 'custom-agent',+ scope: 'page',+ });++ expect(result.plugins).toContain(PageAgentIdentifier);+ expect(result.plugins).toEqual([PageAgentIdentifier, 'plugin-a', 'plugin-b']);+ expect(result.chatConfig.enableHistoryCount).toBe(false);+ expect(result.isBuiltinAgent).toBe(false);+ });++ it('should preserve existing plugins when injecting page-agent', () => {+ const result = resolveAgentConfig({+ agentId: 'custom-agent',+ plugins: ['web-search', 'memory'],+ scope: 'page',+ });++ expect(result.plugins).toEqual([PageAgentIdentifier, 'web-search', 'memory']);+ });++ it('should merge custom system role with page-agent system role', () => {+ const result = resolveAgentConfig({+ agentId: 'custom-agent',+ scope: 'page',+ });++ expect(result.agentConfig.systemRole).toContain('You are a helpful assistant');+ expect(result.agentConfig.systemRole).toContain('Page agent system prompt');+ expect(result.agentConfig.systemRole).toMatch(+ /You are a helpful assistant\n\nPage agent system prompt/,+ );+ });++ it('should use page-agent system role when custom role is empty', () => {+ vi.spyOn(agentSelectors.agentSelectors, 'getAgentConfigById').mockReturnValue(+ () =>+ ({+ ...mockAgentConfig,+ systemRole: '',+ }) as any,+ );++ const result = resolveAgentConfig({+ agentId: 'custom-agent',+ scope: 'page',+ });++ expect(result.agentConfig.systemRole).toBe('Page agent system prompt with XML instructions...');+ });++ it('should not inject page-agent for non-page scope', () => {+ const result = resolveAgentConfig({+ agentId: 'custom-agent',+ scope: 'main',+ });++ expect(result.plugins).not.toContain(PageAgentIdentifier);+ expect(result.plugins).toEqual(['plugin-a', 'plugin-b']);+ expect(result.chatConfig.enableHistoryCount).toBeUndefined();+ });++ it('should not inject page-agent when scope is undefined', () => {+ const result = resolveAgentConfig({+ agentId: 'custom-agent',+ });++ expect(result.plugins).not.toContain(PageAgentIdentifier);+ expect(result.plugins).toEqual(['plugin-a', 'plugin-b']);+ });++ it('should not duplicate PageAgentIdentifier if already present', () => {+ const result = resolveAgentConfig({+ agentId: 'custom-agent',+ plugins: [PageAgentIdentifier, 'other-plugin'],+ scope: 'page',+ });++ expect(result.plugins.filter((p) => p === PageAgentIdentifier)).toHaveLength(1);+ expect(result.plugins).toEqual([PageAgentIdentifier, 'other-plugin']);+ });++ it('should apply chatConfig overrides for page editor', () => {+ vi.spyOn(agentSelectors.chatConfigByIdSelectors, 'getChatConfigById').mockReturnValue(+ () =>+ ({+ enableHistoryCount: true,+ enableStreaming: true,+ historyCount: 20,+ }) as any,+ );++ const result = resolveAgentConfig({+ agentId: 'custom-agent',+ scope: 'page',+ });++ expect(result.chatConfig.enableHistoryCount).toBe(false);+ expect(result.chatConfig.enableStreaming).toBe(true);+ expect(result.chatConfig.historyCount).toBe(20);+ });++ it('should preserve params adjustments in page scope', () => {+ vi.spyOn(agentSelectors.agentSelectors, 'getAgentConfigById').mockReturnValue(+ () =>+ ({+ model: 'gpt-4',+ params: {+ max_tokens: 4096,+ reasoning_effort: 'high',+ temperature: 0.7,+ },+ plugins: ['plugin-a'],+ systemRole: 'You are a helpful assistant',+ }) as any,+ );+ vi.spyOn(agentSelectors.chatConfigByIdSelectors, 'getChatConfigById').mockReturnValue(+ () =>+ ({+ enableMaxTokens: false,+ enableReasoningEffort: true,+ }) as any,+ );++ const result = resolveAgentConfig({+ agentId: 'custom-agent',+ scope: 'page',+ });++ expect(result.agentConfig.params.max_tokens).toBeUndefined();+ expect(result.agentConfig.params.reasoning_effort).toBe('high');+ expect(result.agentConfig.params.temperature).toBe(0.7);+ });++ it('should handle gracefully when page-agent runtime is unavailable', () => {+ vi.spyOn(builtinAgents, 'getAgentRuntimeConfig').mockReturnValue(undefined);++ const result = resolveAgentConfig({+ agentId: 'custom-agent',+ scope: 'page',+ });++ // Should still inject PageAgentIdentifier but with empty systemRole+ expect(result.plugins).toContain(PageAgentIdentifier);+ expect(result.agentConfig.systemRole).toBe('You are a helpful assistant');+ expect(result.chatConfig.enableHistoryCount).toBe(false);+ });++ it('should handle gracefully when page-agent runtime has no systemRole', () => {+ vi.spyOn(builtinAgents, 'getAgentRuntimeConfig').mockReturnValue({+ plugins: [PageAgentIdentifier],+ systemRole: undefined as any,+ });++ const result = resolveAgentConfig({+ agentId: 'custom-agent',+ scope: 'page',+ });++ expect(result.plugins).toContain(PageAgentIdentifier);+ expect(result.agentConfig.systemRole).toBe('You are a helpful assistant');+ expect(result.chatConfig.enableHistoryCount).toBe(false);+ });+ });});diff --git a/src/services/chat/mecha/agentConfigResolver.ts b/src/services/chat/mecha/agentConfigResolver.tsindex 1fad2ffbcbf..a7a3a2a848a 100644--- a/src/services/chat/mecha/agentConfigResolver.ts+++ b/src/services/chat/mecha/agentConfigResolver.ts@@ -1,5 +1,6 @@import { BUILTIN_AGENT_SLUGS, getAgentRuntimeConfig } from '@lobechat/builtin-agents';-import { type LobeAgentChatConfig, type LobeAgentConfig } from '@lobechat/types';+import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';+import { type LobeAgentChatConfig, type LobeAgentConfig, type MessageMapScope } from '@lobechat/types';import { produce } from 'immer';import { getAgentStoreState } from '@/store/agent';@@ -42,6 +43,10 @@ const applyParamsFromChatConfig = (export interface AgentConfigResolverContext {/** Agent ID to resolve config for */agentId: string;++ /** Message map scope (e.g., 'page', 'main', 'thread') */+ scope?: MessageMapScope;+// Builtin agent specific context/** Document content for page-agent */documentContent?: string;@@ -90,6 +95,13 @@ 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,+ scope: ctx.scope,+ plugins,+ });+const agentStoreState = getAgentStoreState();// Get base config from store@@ -101,19 +113,74 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge// Check if this is a builtin agentconst slug = agentSelectors.getAgentSlugById(agentId)(agentStoreState);++ console.log('[agentConfigResolver] Agent type check:', { slug, isBuiltin: !!slug });+if (!slug) {+ console.log('[agentConfigResolver] Taking CUSTOM AGENT branch');// Regular agent - use provided plugins if available, fallback to agent's pluginsconst finalPlugins = plugins && plugins.length > 0 ? plugins : basePlugins;+// Apply params adjustments based on chatConfig- const finalAgentConfig = applyParamsFromChatConfig(agentConfig, chatConfig);+ let finalAgentConfig = applyParamsFromChatConfig(agentConfig, chatConfig);+ let finalChatConfig = chatConfig;++ // === Page Editor Auto-Injection ===+ // 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+ : [PageAgentIdentifier, ...finalPlugins];++ // 2. Get page-agent system prompt from builtin agent runtime+ const pageAgentRuntime = getAgentRuntimeConfig(BUILTIN_AGENT_SLUGS.pageAgent, {});+ 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;++ finalAgentConfig = {+ ...finalAgentConfig,+ systemRole: mergedSystemRole,+ };++ // 4. Apply chatConfig overrides (same as builtin page-copilot)+ finalChatConfig = {+ ...chatConfig,+ enableHistoryCount: false, // Disable history truncation for full document context+ };++ console.log('[agentConfigResolver] Page-agent injection complete:', {+ plugins: pageAgentPlugins,+ systemRoleLength: mergedSystemRole.length,+ chatConfig: finalChatConfig,+ });++ return {+ agentConfig: finalAgentConfig,+ chatConfig: finalChatConfig,+ isBuiltinAgent: false,+ plugins: pageAgentPlugins,+ };+ }++ // Not in page scope - return standard configreturn {agentConfig: finalAgentConfig,- chatConfig,+ chatConfig: finalChatConfig,isBuiltinAgent: false,plugins: finalPlugins,};}+ console.log('[agentConfigResolver] Taking BUILTIN AGENT branch, slug:', slug);+// Build groupSupervisorContext if this is a group-supervisor agentlet groupSupervisorContext;if (slug === BUILTIN_AGENT_SLUGS.groupSupervisor) {@@ -142,24 +209,61 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge});// Merge runtime systemRole into agent config- const resolvedAgentConfig: LobeAgentConfig = {- ...agentConfig,- // Use runtime systemRole if available, otherwise fallback to stored systemRole- systemRole: runtimeConfig?.systemRole ?? agentConfig.systemRole,- };+ let resolvedSystemRole = runtimeConfig?.systemRole ?? agentConfig.systemRole;// Merge plugins: runtime plugins take priority, fallback to base plugins- const finalPlugins =+ let finalPlugins =runtimeConfig?.plugins && runtimeConfig.plugins.length > 0? runtimeConfig.plugins: basePlugins;// Merge chatConfig: runtime chatConfig overrides base chatConfig- const resolvedChatConfig: LobeAgentChatConfig = {+ let resolvedChatConfig: LobeAgentChatConfig = {...chatConfig,...runtimeConfig?.chatConfig,};+ // === Page Editor Auto-Injection for Builtin Agents ===+ // 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];+ }++ // 2. Get page-agent system prompt+ const pageAgentRuntime = getAgentRuntimeConfig(BUILTIN_AGENT_SLUGS.pageAgent, {});+ const pageAgentSystemRole = pageAgentRuntime?.systemRole || '';++ // 3. Merge system roles: builtin agent's role + page-agent role+ if (pageAgentSystemRole) {+ resolvedSystemRole = resolvedSystemRole+ ? `${resolvedSystemRole}\n\n${pageAgentSystemRole}`+ : pageAgentSystemRole;+ }++ // 4. Apply chatConfig overrides+ resolvedChatConfig = {+ ...resolvedChatConfig,+ enableHistoryCount: false,+ };++ console.log('[agentConfigResolver] Page-agent injection complete for builtin agent:', {+ slug,+ plugins: finalPlugins,+ systemRoleLength: resolvedSystemRole.length,+ });+ }++ // Merge runtime systemRole into agent config+ const resolvedAgentConfig: LobeAgentConfig = {+ ...agentConfig,+ systemRole: resolvedSystemRole,+ };+// Apply params adjustments based on chatConfigconst finalAgentConfig = applyParamsFromChatConfig(resolvedAgentConfig, resolvedChatConfig);diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.tsindex de3b92666ca..7c26060d6cc 100644--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts@@ -164,10 +164,17 @@ export const streamingExecutor: StateCreator<// - agentId is used for session ID (message storage location)const effectiveAgentId = paramSubAgentId || agentId;+ // Get scope from operation context if available+ const operation = operationId ? get().operations[operationId] : undefined;+ const scope = operation?.context.scope;++ console.log('[internal_createAgentState] Operation scope:', { operationId, scope });+// Resolve agent config with builtin agent runtime config merged// This ensures runtime plugins (e.g., 'lobe-agent-builder' for Agent Builder) are includedconst { agentConfig: agentConfigData, plugins: pluginIds } = resolveAgentConfig({agentId: effectiveAgentId || '',+ scope, // Pass scope from operation context});// Get tools manifest map@@ -338,7 +345,10 @@ export const streamingExecutor: StateCreator<// Otherwise, resolve from mecha layer which handles:// - Builtin agent runtime config merging// - max_tokens/reasoning_effort based on chatConfig settings- const resolved = resolveAgentConfig({ agentId: effectiveAgentId });+ const resolved = resolveAgentConfig({+ agentId: effectiveAgentId,+ scope, // scope is already available from line 329+ });const finalAgentConfig = agentConfig || resolved.agentConfig;const chatConfig = resolved.chatConfig;@@ -393,6 +403,7 @@ export const streamingExecutor: StateCreator<messages,model,provider,+ scope, // Pass scope to chat service for page-agent injection...finalAgentConfig.params,plugins: finalAgentConfig.plugins,},@@ -929,12 +940,15 @@ export const streamingExecutor: StateCreator<// Create a new array to avoid modifying the original messageslet messages = [...originalMessages];+ console.log('[internal_execAgentRuntime] Context scope:', { scope: context.scope, agentId: effectiveAgentId });+// Use effectiveAgentId to get agent config (subAgentId in group orchestration, agentId otherwise)// resolveAgentConfig handles:// - Builtin agent runtime config merging// - max_tokens/reasoning_effort based on chatConfig settingsconst { agentConfig: agentConfigData, chatConfig } = resolveAgentConfig({agentId: effectiveAgentId || '',+ scope: context.scope, // Pass scope from context parameter (available at line 883)});// Use agent config from agentId