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: implement agent builder

Shinji-Lif638b9751759
diff --git a/packages/builtin-agents/src/agents/agent-builder/index.ts b/packages/builtin-agents/src/agents/agent-builder/index.ts
new file mode 100644
index 00000000000..f59d289314f
--- /dev/null
+++ b/packages/builtin-agents/src/agents/agent-builder/index.ts
@@ -0,0 +1,26 @@
+import { AgentBuilderIdentifier } from '@lobechat/builtin-tool-agent-builder';
+
+import type { BuiltinAgentDefinition } from '../../types';
+import { BUILTIN_AGENT_SLUGS } from '../../types';
+import { systemRoleTemplate } from './systemRole';
+
+/**
+ * Agent Builder - used for configuring AI agents through natural conversation
+ */
+export const AGENT_BUILDER: BuiltinAgentDefinition = {
+ avatar: '/avatars/agent-builder.png',
+
+ // Persist config - stored in database
+ persist: {
+ model: 'claude-sonnet-4-5-20250929',
+ provider: 'anthropic',
+ },
+
+ // Runtime config - static systemRole
+ runtime: (ctx) => ({
+ plugins: [AgentBuilderIdentifier, ...(ctx.plugins || [])],
+ systemRole: systemRoleTemplate,
+ }),
+
+ slug: BUILTIN_AGENT_SLUGS.agentBuilder,
+};
diff --git a/packages/builtin-agents/src/agents/agent-builder/systemRole.ts b/packages/builtin-agents/src/agents/agent-builder/systemRole.ts
new file mode 100644
index 00000000000..4980cf28969
--- /dev/null
+++ b/packages/builtin-agents/src/agents/agent-builder/systemRole.ts
@@ -0,0 +1,112 @@
+/**
+ * Agent Builder System Role Template
+ *
+ * This agent helps users configure and optimize their AI agents through natural conversation.
+ */
+export const systemRoleTemplate = `You are Lobe, an Agent Builder integrated into LobeHub. Your role is to help users configure and optimize their AI agents through natural conversation.
+
+<capabilities>
+You have access to tools that can read and modify agent configurations:
+
+**Read Operations:**
+- **getConfig**: Get the complete configuration of the current agent (model, plugins, chat settings, opening message, etc.)
+- **getMeta**: Get agent metadata (title, description, avatar, tags)
+- **getAvailableModels**: Get all available AI models and providers that can be used. Optionally filter by provider ID.
+- **getAvailableTools**: Get all available tools (built-in tools and installed plugins) that can be enabled for the agent.
+
+**Write Operations:**
+- **updateConfig**: Update multiple configuration fields at once
+- **updateMeta**: Update agent metadata (title, description, avatar, tags)
+- **updateChatConfig**: Update chat-specific settings
+
+**Specific Field Operations:**
+- **togglePlugin**: Enable or disable a specific plugin
+- **setModel**: Change the AI model and provider
+- **setOpeningMessage**: Set the agent's opening message
+- **setOpeningQuestions**: Set suggested opening questions
+</capabilities>
+
+<workflow>
+1. **Understand the request**: Listen carefully to what the user wants to configure
+2. **Read current state**: Use getConfig/getMeta to understand current configuration before making changes
+3. **Make targeted changes**: Use the most specific API for the task (e.g., setModel for model changes, togglePlugin for plugins)
+4. **Confirm changes**: Report what was changed and the new values
+</workflow>
+
+<guidelines>
+1. **Always read before write**: Before making changes, use getConfig to understand the current state, unless the user explicitly tells you the current value.
+2. **Explain your changes**: When modifying configurations, explain what you're changing and why it might benefit the user.
+3. **One change at a time**: Prefer making focused changes rather than bulk updates, unless the user explicitly requests multiple changes at once.
+4. **Validate user intent**: For significant changes (like changing the model or disabling important plugins), confirm with the user before proceeding.
+5. **Provide recommendations**: When users ask for advice, explain the trade-offs of different options based on their use case.
+6. **Use user's language**: Always respond in the same language the user is using.
+</guidelines>
+
+<configuration_knowledge>
+**Model & Provider:**
+- model: The AI model identifier (e.g., "gpt-4o", "gpt-4o-mini", "claude-3-5-sonnet-20241022", "gemini-1.5-pro")
+- provider: The AI provider (e.g., "openai", "anthropic", "google", "azure")
+- Different models have different capabilities, costs, and speed trade-offs
+
+**Chat Configuration (chatConfig):**
+- historyCount: Number of previous messages to include in context (default: 20). Higher values provide more context but increase token usage.
+- enableHistoryCount: Whether to limit history (default: true)
+- enableAutoCreateTopic: Automatically create topics based on conversation (default: true)
+- autoCreateTopicThreshold: Messages before auto-creating topic (default: 2)
+- enableCompressHistory: Compress long conversation history to save tokens (default: true)
+- enableStreaming: Stream responses in real-time (default: true)
+- enableReasoning: Enable reasoning/thinking mode for supported models (default: false)
+- displayMode: "chat" for conversational view, "docs" for document-style view
+
+**Model Parameters (params):**
+- temperature: Controls randomness (0-2, default: 1). Lower = more focused, higher = more creative
+- top_p: Nucleus sampling parameter (0-1, default: 1)
+- frequency_penalty: Reduces repetition (0-2, default: 0)
+- presence_penalty: Encourages new topics (0-2, default: 0)
+
+**Plugins:**
+- Array of enabled plugin identifiers
+- Common plugins: "lobe-web-browsing", "lobe-image-generation", "lobe-artifacts"
+- Plugins extend agent capabilities with external tools
+
+**Opening Experience:**
+- openingMessage: First message shown when starting a new conversation. Good for introducing the agent's purpose.
+- openingQuestions: Suggested questions to help users get started. Should be relevant to the agent's specialty.
+
+**Metadata:**
+- title: Display name for the agent
+- description: Brief description of what the agent does
+- avatar: Emoji or image URL for the agent's avatar
+- tags: Categories for organization
+- backgroundColor: Theme color for the agent card
+</configuration_knowledge>
+
+<examples>
+User: "帮我把模型改成 Claude"
+Action: First check current model with getConfig, then use setModel to change to claude-3-5-sonnet-20241022 with provider "anthropic"
+
+User: "Enable web browsing for this agent"
+Action: Use togglePlugin with pluginId "lobe-web-browsing" and enabled: true
+
+User: "What's my current configuration?"
+Action: Use getConfig and getMeta to retrieve and display the current settings in a readable format
+
+User: "Set up some opening questions about coding"
+Action: Use setOpeningQuestions with relevant programming questions like ["How can I help you with your code today?", "What programming language are you working with?", "Do you need help debugging or writing new code?"]
+
+User: "What models are available?"
+Action: Use getAvailableModels to retrieve and display all available AI models grouped by provider, showing their capabilities (vision, function calling, reasoning)
+
+User: "Show me what tools I can enable"
+Action: Use getAvailableTools to list all available built-in tools and installed plugins that can be enabled for the agent
+
+User: "I want to use a model with vision capabilities"
+Action: Use getAvailableModels to find models with vision capability, then recommend suitable options and use setModel to change if user confirms
+</examples>
+
+<response_format>
+- When showing configuration, format it in a clear, readable way using markdown
+- When making changes, clearly state what was changed (before → after)
+- Use bullet points for listing multiple items
+- Keep responses concise but informative
+</response_format>`;
diff --git a/packages/builtin-agents/src/agents/group-agent-builder/index.ts b/packages/builtin-agents/src/agents/group-agent-builder/index.ts
new file mode 100644
index 00000000000..4ac613c5476
--- /dev/null
+++ b/packages/builtin-agents/src/agents/group-agent-builder/index.ts
@@ -0,0 +1,26 @@
+import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-builder';
+
+import type { BuiltinAgentDefinition } from '../../types';
+import { BUILTIN_AGENT_SLUGS } from '../../types';
+import { systemRoleTemplate } from './systemRole';
+
+/**
+ * Group Agent Builder - used for configuring group chat settings and managing group members
+ */
+export const GROUP_AGENT_BUILDER: BuiltinAgentDefinition = {
+ avatar: '/avatars/agent-builder.png',
+
+ // Persist config - stored in database
+ persist: {
+ model: 'claude-sonnet-4-5-20250929',
+ provider: 'anthropic',
+ },
+
+ // Runtime config - static systemRole
+ runtime: (ctx) => ({
+ plugins: [GroupAgentBuilderIdentifier, ...(ctx.plugins || [])],
+ systemRole: systemRoleTemplate,
+ }),
+
+ slug: BUILTIN_AGENT_SLUGS.groupAgentBuilder,
+};
diff --git a/packages/builtin-agents/src/agents/group-agent-builder/systemRole.ts b/packages/builtin-agents/src/agents/group-agent-builder/systemRole.ts
new file mode 100644
index 00000000000..e67717f1950
--- /dev/null
+++ b/packages/builtin-agents/src/agents/group-agent-builder/systemRole.ts
@@ -0,0 +1,7 @@
+/**
+ * Group Agent Builder System Role Template
+ *
+ * This provides guidance on how to effectively use the group agent builder tools
+ * for configuring group chats and managing group members.
+ */
+export { systemPrompt as systemRoleTemplate } from '@lobechat/builtin-tool-group-agent-builder';
diff --git a/packages/builtin-tool-agent-builder/package.json b/packages/builtin-tool-agent-builder/package.json
new file mode 100644
index 00000000000..2a1744d8b79
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "@lobechat/builtin-tool-agent-builder",
+ "version": "1.0.0",
+ "private": true,
+ "exports": {
+ ".": "./src/index.ts",
+ "./client": "./src/client/index.ts",
+ "./executionRuntime": "./src/ExecutionRuntime/index.ts"
+ },
+ "main": "./src/index.ts",
+ "dependencies": {
+ "@lobechat/const": "workspace:*",
+ "@lobechat/prompts": "workspace:*",
+ "@lobechat/types": "workspace:*",
+ "type-fest": "^4.18.3"
+ },
+ "peerDependencies": {
+ "@lobehub/ui": "*",
+ "antd": "^5",
+ "lucide-react": "*",
+ "next": "*",
+ "react": "*",
+ "react-i18next": "*",
+ "react-layout-kit": "*"
+ }
+}
diff --git a/packages/builtin-tool-agent-builder/src/ExecutionRuntime/index.ts b/packages/builtin-tool-agent-builder/src/ExecutionRuntime/index.ts
new file mode 100644
index 00000000000..6b66c8bda51
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/ExecutionRuntime/index.ts
@@ -0,0 +1,831 @@
+import { KLAVIS_SERVER_TYPES } from '@lobechat/const';
+import { marketToolsResultsPrompt, modelsResultsPrompt } from '@lobechat/prompts';
+import { BuiltinServerRuntimeOutput } from '@lobechat/types';
+
+import { discoverService } from '@/services/discover';
+import { getAgentStoreState } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors/selectors';
+import { getAiInfraStoreState } from '@/store/aiInfra';
+import { getToolStoreState } from '@/store/tool';
+import {
+ builtinToolSelectors,
+ klavisStoreSelectors,
+ pluginSelectors,
+} from '@/store/tool/selectors';
+import { KlavisServerStatus } from '@/store/tool/slices/klavisStore/types';
+import { getUserStoreState } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+import type {
+ AvailableModel,
+ AvailableProvider,
+ GetAvailableModelsParams,
+ GetAvailableModelsState,
+ InstallPluginParams,
+ InstallPluginState,
+ MarketToolItem,
+ SearchMarketToolsParams,
+ SearchMarketToolsState,
+ UpdateAgentConfigParams,
+ UpdateConfigState,
+ UpdatePromptParams,
+ UpdatePromptState,
+} from '../types';
+
+/**
+ * Agent Builder Execution Runtime
+ * Handles the execution logic for all Agent Builder APIs
+ *
+ * Note: getAgentConfig, getAgentMeta, getPrompt, getAvailableTools, searchOfficialTools are removed
+ * because the current agent context is now automatically injected into the conversation
+ */
+export class AgentBuilderExecutionRuntime {
+ // ==================== Read Operations ====================
+
+ /**
+ * Get available models and providers
+ */
+ async getAvailableModels(args: GetAvailableModelsParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const aiInfraState = getAiInfraStoreState();
+ const enabledList = aiInfraState.enabledChatModelList || [];
+
+ // Filter by providerId if specified
+ const filteredList = args.providerId
+ ? enabledList.filter((p) => p.id === args.providerId)
+ : enabledList;
+
+ // Transform to our response format
+ const providers: AvailableProvider[] = filteredList.map((provider) => ({
+ id: provider.id,
+ models: provider.children.map(
+ (model): AvailableModel => ({
+ abilities: model.abilities
+ ? {
+ files: model.abilities.files,
+ functionCall: model.abilities.functionCall,
+ reasoning: model.abilities.reasoning,
+ vision: model.abilities.vision,
+ }
+ : undefined,
+ description: model.description,
+ id: model.id,
+ name: model.displayName || model.id,
+ }),
+ ),
+ name: provider.name,
+ }));
+
+ const totalModels = providers.reduce((sum, p) => sum + p.models.length, 0);
+
+ // Convert to XML format to provide detailed model list to agent
+ const xmlContent = modelsResultsPrompt(providers);
+ const summary = `Found ${providers.length} provider(s) with ${totalModels} model(s) available.\n\n${xmlContent}`;
+
+ return {
+ content: summary,
+ state: { providers } as GetAvailableModelsState,
+ success: true,
+ };
+ } catch (error) {
+ const err = error as Error;
+ return {
+ content: `Failed to get available models: ${err.message}`,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Search for tools in the marketplace
+ */
+ async searchMarketTools(args: SearchMarketToolsParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const toolState = getToolStoreState();
+
+ // Fetch from market
+ const response = await discoverService.getMcpList({
+ category: args.category,
+ pageSize: args.pageSize || 10,
+ q: args.query,
+ });
+
+ // Transform to our format and check installation status
+ const tools: MarketToolItem[] = response.items.map((item) => {
+ const installed = pluginSelectors.isPluginInstalled(item.identifier)(toolState);
+ return {
+ author: item.author,
+ cloudEndPoint: (item as any).cloudEndPoint,
+ description: item.description,
+ haveCloudEndpoint: (item as any).haveCloudEndpoint,
+ icon: item.icon,
+ identifier: item.identifier,
+ installed,
+ name: item.name,
+ tags: item.tags,
+ };
+ });
+
+ const installedCount = tools.filter((t) => t.installed).length;
+ const notInstalledCount = tools.length - installedCount;
+
+ let summary = `Found ${response.totalCount} tool(s) in the marketplace.`;
+ if (args.query) {
+ summary = `Found ${response.totalCount} tool(s) matching "${args.query}".`;
+ }
+ if (installedCount > 0) {
+ summary += ` ${installedCount} already installed, ${notInstalledCount} available to install.`;
+ }
+
+ // Convert to XML format to provide detailed tool list to agent
+ const xmlContent = marketToolsResultsPrompt(tools);
+ const content = `${summary}\n\n${xmlContent}`;
+
+ return {
+ content,
+ state: {
+ query: args.query,
+ tools,
+ totalCount: response.totalCount,
+ } as SearchMarketToolsState,
+ success: true,
+ };
+ } catch (error) {
+ const err = error as Error;
+ return {
+ content: `Failed to search market tools: ${err.message}`,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ // Note: searchOfficialTools is removed because official tools are now
+ // automatically injected into the conversation context via AgentBuilderContextInjector
+
+ // ==================== Write Operations ====================
+
+ /**
+ * Update agent configuration and/or metadata
+ * Now also handles plugin toggle operations in a single update
+ */
+ async updateAgentConfig(
+ agentId: string,
+ args: UpdateAgentConfigParams,
+ ): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const state = getAgentStoreState();
+ const agentStore = getAgentStoreState();
+ const resultState: UpdateConfigState = { success: true };
+ const contentParts: string[] = [];
+
+ // Get current config for merging
+ const previousConfig = agentSelectors.getAgentConfigById(agentId)(state);
+
+ // Build the final config update, merging togglePlugin into config.plugins
+ let finalConfig = args.config ? { ...args.config } : {};
+
+ // Handle togglePlugin - merge into config.plugins
+ if (args.togglePlugin) {
+ const { pluginId, enabled } = args.togglePlugin;
+ const currentPlugins = previousConfig.plugins || [];
+ const isCurrentlyEnabled = currentPlugins.includes(pluginId);
+ const shouldEnable = enabled !== undefined ? enabled : !isCurrentlyEnabled;
+
+ let newPlugins: string[];
+ if (shouldEnable && !isCurrentlyEnabled) {
+ // Enable: add plugin
+ newPlugins = [...currentPlugins, pluginId];
+ } else if (!shouldEnable && isCurrentlyEnabled) {
+ // Disable: remove plugin
+ newPlugins = currentPlugins.filter((id) => id !== pluginId);
+ } else {
+ // No change needed
+ newPlugins = currentPlugins;
+ }
+
+ // Merge plugins into finalConfig
+ finalConfig = { ...finalConfig, plugins: newPlugins };
+
+ resultState.togglePlugin = {
+ enabled: shouldEnable,
+ pluginId,
+ };
+ contentParts.push(`plugin ${pluginId} ${shouldEnable ? 'enabled' : 'disabled'}`);
+ }
+
+ // Handle config update (including merged plugins from togglePlugin)
+ if (Object.keys(finalConfig).length > 0) {
+ const configUpdatedFields = Object.keys(finalConfig);
+ const configPreviousValues: Record<string, unknown> = {};
+ const configNewValues: Record<string, unknown> = {};
+
+ for (const field of configUpdatedFields) {
+ configPreviousValues[field] = (previousConfig as unknown as Record<string, unknown>)[
+ field
+ ];
+ configNewValues[field] = (finalConfig as unknown as Record<string, unknown>)[field];
+ }
+
+ await agentStore.optimisticUpdateAgentConfig(agentId, finalConfig);
+
+ // Only add config to resultState if there are non-plugin updates
+ const nonPluginFields = configUpdatedFields.filter((f) => f !== 'plugins');
+ if (nonPluginFields.length > 0 || !args.togglePlugin) {
+ resultState.config = {
+ newValues: configNewValues,
+ previousValues: configPreviousValues,
+ updatedFields: configUpdatedFields,
+ };
+ if (!args.togglePlugin) {
+ contentParts.push(`config fields: ${configUpdatedFields.join(', ')}`);
+ } else if (nonPluginFields.length > 0) {
+ contentParts.push(`config fields: ${nonPluginFields.join(', ')}`);
+ }
+ }
+ }
+
+ // Handle meta update
+ if (args.meta && Object.keys(args.meta).length > 0) {
+ const previousMeta = agentSelectors.getAgentMetaById(agentId)(state);
+ const metaUpdatedFields = Object.keys(args.meta);
+ const metaPreviousValues: Record<string, unknown> = {};
+
+ for (const field of metaUpdatedFields) {
+ metaPreviousValues[field] = (previousMeta as unknown as Record<string, unknown>)[field];
+ }
+
+ await agentStore.optimisticUpdateAgentMeta(agentId, args.meta);
+
+ resultState.meta = {
+ newValues: args.meta,
+ previousValues: metaPreviousValues as Record<string, unknown>,
+ updatedFields: metaUpdatedFields,
+ };
+ contentParts.push(`meta fields: ${metaUpdatedFields.join(', ')}`);
+ }
+
+ if (contentParts.length === 0) {
+ return {
+ content: 'No fields to update.',
+ state: { success: true } as UpdateConfigState,
+ success: true,
+ };
+ }
+
+ const content = `Successfully updated agent. Updated ${contentParts.join('; ')}`;
+
+ return {
+ content,
+ state: resultState,
+ success: true,
+ };
+ } catch (error) {
+ const err = error as Error;
+ return {
+ content: `Failed to update agent: ${err.message}`,
+ error,
+ state: { success: false } as UpdateConfigState,
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Update agent system prompt
+ */
+ async updatePrompt(
+ agentId: string,
+ args: UpdatePromptParams,
+ ): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const state = getAgentStoreState();
+ const previousConfig = agentSelectors.getAgentConfigById(agentId)(state);
+ const previousPrompt = previousConfig.systemRole;
+
+ if (args.streaming) {
+ // Use streaming mode for typewriter effect
+ await this.streamUpdatePrompt(agentId, args.prompt);
+ } else {
+ // Update the system prompt directly
+ await getAgentStoreState().optimisticUpdateAgentConfig(agentId, {
+ systemRole: args.prompt,
+ });
+ }
+
+ const content = args.prompt
+ ? `Successfully updated system prompt (${args.prompt.length} characters)`
+ : 'Successfully cleared system prompt';
+
+ return {
+ content,
+ state: {
+ newPrompt: args.prompt,
+ previousPrompt,
+ success: true,
+ } as UpdatePromptState,
+ success: true,
+ };
+ } catch (error) {
+ const err = error as Error;
+ return {
+ content: `Failed to update prompt: ${err.message}`,
+ error,
+ state: {
+ newPrompt: args.prompt,
+ success: false,
+ } as UpdatePromptState,
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Open OAuth window and wait for authentication completion
+ * Returns a Promise that resolves when OAuth completes or fails
+ */
+ private openOAuthWindowAndWait(
+ oauthUrl: string,
+ identifier: string,
+ ): Promise<{ cancelled: boolean; success: boolean }> {
+ return new Promise((resolve) => {
+ // Configuration
+ const WINDOW_CHECK_INTERVAL_MS = 500;
+ const POLL_INTERVAL_MS = 1000;
+ const POLL_TIMEOUT_MS = 300_000; // 5 minutes timeout
+
+ let pollInterval: ReturnType<typeof setInterval> | null = null;
+ let pollTimeout: ReturnType<typeof setTimeout> | null = null;
+ let windowCheckInterval: ReturnType<typeof setInterval> | null = null;
+ let resolved = false;
+
+ const cleanup = () => {
+ if (windowCheckInterval) {
+ clearInterval(windowCheckInterval);
+ windowCheckInterval = null;
+ }
+ if (pollInterval) {
+ clearInterval(pollInterval);
+ pollInterval = null;
+ }
+ if (pollTimeout) {
+ clearTimeout(pollTimeout);
+ pollTimeout = null;
+ }
+ };
+
+ const resolveOnce = (result: { cancelled: boolean; success: boolean }) => {
+ if (resolved) return;
+ resolved = true;
+ cleanup();
+ resolve(result);
+ };
+
+ // eslint-disable-next-line unicorn/consistent-function-scoping
+ const checkAuthStatus = async (): Promise<boolean> => {
+ try {
+ // Refresh server status first
+ await getToolStoreState().refreshKlavisServerTools(identifier);
+
+ // Get fresh state after refresh (important: must get new state after refresh)
+ const freshToolStore = getToolStoreState();
+ const server = klavisStoreSelectors
+ .getServers(freshToolStore)
+ .find((s) => s.identifier === identifier);
+
+ return server?.status === KlavisServerStatus.CONNECTED;
+ } catch (error) {
+ console.error('[Klavis] Failed to check auth status:', error);
+ return false;
+ }
+ };
+
+ const startFallbackPolling = () => {
+ if (pollInterval) return;
+
+ pollInterval = setInterval(async () => {
+ const isConnected = await checkAuthStatus();
+ if (isConnected) {
+ resolveOnce({ cancelled: false, success: true });
+ }
+ }, POLL_INTERVAL_MS);
+
+ // Timeout after 5 minutes
+ pollTimeout = setTimeout(() => {
+ resolveOnce({ cancelled: true, success: false });
+ }, POLL_TIMEOUT_MS);
+ };
+
+ // Open OAuth window
+ const oauthWindow = window.open(oauthUrl, '_blank', 'width=600,height=700');
+
+ if (oauthWindow) {
+ // Monitor window close
+ windowCheckInterval = setInterval(async () => {
+ try {
+ if (oauthWindow.closed) {
+ if (windowCheckInterval) {
+ clearInterval(windowCheckInterval);
+ windowCheckInterval = null;
+ }
+
+ // Window closed, check auth status
+ const isConnected = await checkAuthStatus();
+ resolveOnce({ cancelled: !isConnected, success: isConnected });
+ }
+ } catch {
+ // COOP blocked window.closed access, fall back to polling
+ console.log('[Klavis] COOP blocked window.closed access, falling back to polling');
+ if (windowCheckInterval) {
+ clearInterval(windowCheckInterval);
+ windowCheckInterval = null;
+ }
+ startFallbackPolling();
+ }
+ }, WINDOW_CHECK_INTERVAL_MS);
+ } else {
+ // Window was blocked, use polling
+ console.log('[Klavis] OAuth window was blocked, falling back to polling');
+ startFallbackPolling();
+ }
+ });
+ }
+
+ /**
+ * Stream update prompt with typewriter effect
+ */
+ private async streamUpdatePrompt(agentId: string, prompt: string): Promise<void> {
+ // Start streaming
+ getAgentStoreState().startStreamingSystemRole();
+
+ // Simulate streaming by chunking the content
+ const chunkSize = 5; // Characters per chunk
+ const delay = 10; // Milliseconds between chunks
+
+ for (let i = 0; i < prompt.length; i += chunkSize) {
+ const chunk = prompt.slice(i, i + chunkSize);
+ getAgentStoreState().appendStreamingSystemRole(chunk);
+
+ // Small delay for typewriter effect
+ if (i + chunkSize < prompt.length) {
+ // eslint-disable-next-line no-promise-executor-return
+ await new Promise((resolve) => setTimeout(resolve, delay));
+ }
+ }
+
+ // Finish streaming - EditorCanvas will handle save when streaming ends
+ await getAgentStoreState().finishStreamingSystemRole(agentId);
+ }
+
+ // ==================== Plugin Installation ====================
+
+ /**
+ * Install a plugin (MCP marketplace or Klavis/Builtin)
+ * This method prepares the installation state but requires user approval
+ * to actually perform the installation.
+ */
+ async installPlugin(
+ agentId: string,
+ args: InstallPluginParams,
+ ): Promise<BuiltinServerRuntimeOutput> {
+ const { identifier, source } = args;
+
+ try {
+ const toolState = getToolStoreState();
+
+ if (source === 'official') {
+ // Check if it's a Klavis tool
+ const isKlavisEnabled =
+ typeof window !== 'undefined' &&
+ window.global_serverConfigStore?.getState()?.serverConfig?.enableKlavis;
+
+ if (isKlavisEnabled) {
+ // Check if this is a Klavis tool
+ const klavisServer = klavisStoreSelectors
+ .getServers(toolState)
+ .find((s) => s.identifier === identifier);
+
+ // Find Klavis tool info from KLAVIS_SERVER_TYPES
+ const klavisTypeInfo = KLAVIS_SERVER_TYPES.find((t) => t.identifier === identifier);
+
+ if (klavisTypeInfo) {
+ // This is a Klavis tool
+ if (klavisServer) {
+ // Server exists
+ if (klavisServer.status === KlavisServerStatus.CONNECTED) {
+ // Already connected, just enable the plugin
+ const agentState = getAgentStoreState();
+ const currentPlugins =
+ agentSelectors.getAgentConfigById(agentId)(agentState).plugins || [];
+
+ if (!currentPlugins.includes(identifier)) {
+ await getAgentStoreState().optimisticUpdateAgentConfig(agentId, {
+ plugins: [...currentPlugins, identifier],
+ });
+ }
+
+ return {
+ content: `Successfully enabled Klavis tool: ${klavisTypeInfo.label}`,
+ state: {
+ installed: true,
+ isKlavis: true,
+ pluginId: identifier,
+ pluginName: klavisTypeInfo.label,
+ serverStatus: 'connected',
+ success: true,
+ } as InstallPluginState,
+ success: true,
+ };
+ } else if (klavisServer.status === KlavisServerStatus.PENDING_AUTH) {
+ // Needs OAuth authorization - open OAuth window and wait for completion
+ if (klavisServer.oauthUrl) {
+ const authResult = await this.openOAuthWindowAndWait(
+ klavisServer.oauthUrl,
+ identifier,
+ );
+
+ if (authResult.success) {
+ // OAuth successful, enable the plugin
+ const agentState = getAgentStoreState();
+ const currentPlugins =
+ agentSelectors.getAgentConfigById(agentId)(agentState).plugins || [];
+
+ if (!currentPlugins.includes(identifier)) {
+ await getAgentStoreState().optimisticUpdateAgentConfig(agentId, {
+ plugins: [...currentPlugins, identifier],
+ });
+ }
+
+ return {
+ content: `Successfully connected and enabled Klavis tool: ${klavisTypeInfo.label}`,
+ state: {
+ installed: true,
+ isKlavis: true,
+ pluginId: identifier,
+ pluginName: klavisTypeInfo.label,
+ serverStatus: 'connected',
+ success: true,
+ } as InstallPluginState,
+ success: true,
+ };
+ } else {
+ // OAuth cancelled or failed
+ return {
+ content: `OAuth authorization was cancelled or failed for Klavis tool: ${klavisTypeInfo.label}. Please try again.`,
+ state: {
+ installed: false,
+ isKlavis: true,
+ pluginId: identifier,
+ pluginName: klavisTypeInfo.label,
+ serverStatus: 'pending_auth',
+ success: false,
+ } as InstallPluginState,
+ success: false,
+ };
+ }
+ }
+
+ // No OAuth URL available
+ return {
+ content: `Klavis tool "${klavisTypeInfo.label}" requires OAuth authorization but no OAuth URL is available.`,
+ state: {
+ installed: false,
+ isKlavis: true,
+ pluginId: identifier,
+ pluginName: klavisTypeInfo.label,
+ serverStatus: 'pending_auth',
+ success: false,
+ } as InstallPluginState,
+ success: false,
+ };
+ } else {
+ // Server exists but in ERROR state or other unknown state
+ return {
+ content: `Klavis tool "${klavisTypeInfo.label}" is in an error state. Please try reconnecting.`,
+ error: 'Klavis server in error state',
+ state: {
+ installed: false,
+ isKlavis: true,
+ pluginId: identifier,
+ pluginName: klavisTypeInfo.label,
+ serverStatus: 'error',
+ success: false,
+ } as InstallPluginState,
+ success: false,
+ };
+ }
+ } else {
+ // Server doesn't exist yet, create it using createKlavisServer
+ const userId = userProfileSelectors.userId(getUserStoreState());
+ if (!userId) {
+ return {
+ content: `Cannot connect Klavis tool: User not logged in.`,
+ error: 'User not logged in',
+ state: {
+ installed: false,
+ pluginId: identifier,
+ success: false,
+ } as InstallPluginState,
+ success: false,
+ };
+ }
+
+ const newServer = await getToolStoreState().createKlavisServer({
+ identifier,
+ serverName: klavisTypeInfo.serverName,
+ userId,
+ });
+
+ if (newServer) {
+ // Enable the plugin for the agent
+ const agentState = getAgentStoreState();
+ const currentPlugins =
+ agentSelectors.getAgentConfigById(agentId)(agentState).plugins || [];
+
+ if (!currentPlugins.includes(identifier)) {
+ await getAgentStoreState().optimisticUpdateAgentConfig(agentId, {
+ plugins: [...currentPlugins, identifier],
+ });
+ }
+
+ if (newServer.isAuthenticated) {
+ // Already authenticated, refresh tools
+ await getToolStoreState().refreshKlavisServerTools(newServer.identifier);
+
+ return {
+ content: `Successfully connected and enabled Klavis tool: ${klavisTypeInfo.label}`,
+ state: {
+ installed: true,
+ isKlavis: true,
+ pluginId: identifier,
+ pluginName: klavisTypeInfo.label,
+ serverStatus: 'connected',
+ success: true,
+ } as InstallPluginState,
+ success: true,
+ };
+ } else if (newServer.oauthUrl) {
+ // Needs OAuth, open window and wait for completion
+ const authResult = await this.openOAuthWindowAndWait(
+ newServer.oauthUrl,
+ newServer.identifier,
+ );
+
+ if (authResult.success) {
+ // OAuth successful
+ return {
+ content: `Successfully connected and enabled Klavis tool: ${klavisTypeInfo.label}`,
+ state: {
+ installed: true,
+ isKlavis: true,
+ pluginId: identifier,
+ pluginName: klavisTypeInfo.label,
+ serverStatus: 'connected',
+ success: true,
+ } as InstallPluginState,
+ success: true,
+ };
+ } else {
+ // OAuth cancelled or failed
+ return {
+ content: `OAuth authorization was cancelled or failed for Klavis tool: ${klavisTypeInfo.label}. Please try again.`,
+ state: {
+ installed: false,
+ isKlavis: true,
+ pluginId: identifier,
+ pluginName: klavisTypeInfo.label,
+ serverStatus: 'pending_auth',
+ success: false,
+ } as InstallPluginState,
+ success: false,
+ };
+ }
+ } else {
+ // Server created but neither authenticated nor has OAuth URL
+ return {
+ content: `Klavis tool "${klavisTypeInfo.label}" was created but requires additional setup.`,
+ state: {
+ installed: false,
+ isKlavis: true,
+ pluginId: identifier,
+ pluginName: klavisTypeInfo.label,
+ serverStatus: 'pending_auth',
+ success: true,
+ } as InstallPluginState,
+ success: true,
+ };
+ }
+ }
+
+ return {
+ content: `Failed to connect Klavis tool: ${klavisTypeInfo.label}`,
+ error: 'Failed to create Klavis server',
+ state: {
+ installed: false,
+ pluginId: identifier,
+ success: false,
+ } as InstallPluginState,
+ success: false,
+ };
+ }
+ }
+ }
+
+ // Not a Klavis tool, check if it's a builtin tool
+ const builtinTools = builtinToolSelectors.metaList(toolState);
+ const builtinTool = builtinTools.find((t) => t.identifier === identifier);
+
+ if (builtinTool) {
+ // It's a builtin tool, just enable it
+ const agentState = getAgentStoreState();
+ const currentPlugins =
+ agentSelectors.getAgentConfigById(agentId)(agentState).plugins || [];
+
+ if (!currentPlugins.includes(identifier)) {
+ await getAgentStoreState().optimisticUpdateAgentConfig(agentId, {
+ plugins: [...currentPlugins, identifier],
+ });
+ }
+
+ return {
+ content: `Successfully enabled builtin tool: ${builtinTool.meta?.title || identifier}`,
+ state: {
+ installed: true,
+ pluginId: identifier,
+ pluginName: builtinTool.meta?.title || identifier,
+ success: true,
+ } as InstallPluginState,
+ success: true,
+ };
+ }
+
+ return {
+ content: `Official tool "${identifier}" not found.`,
+ error: 'Tool not found',
+ state: {
+ installed: false,
+ pluginId: identifier,
+ success: false,
+ } as InstallPluginState,
+ success: false,
+ };
+ }
+
+ // Source is 'market' - MCP marketplace plugin
+ // Check if already installed
+ const isInstalled = pluginSelectors.isPluginInstalled(identifier)(toolState);
+
+ if (isInstalled) {
+ // Already installed, just enable it for the agent
+ const agentState = getAgentStoreState();
+ const currentPlugins = agentSelectors.getAgentConfigById(agentId)(agentState).plugins || [];
+
+ if (!currentPlugins.includes(identifier)) {
+ await getAgentStoreState().optimisticUpdateAgentConfig(agentId, {
+ plugins: [...currentPlugins, identifier],
+ });
+ }
+
+ const installedPlugin = pluginSelectors.getInstalledPluginById(identifier)(toolState);
+
+ return {
+ content: `Plugin "${installedPlugin?.manifest?.meta?.title || identifier}" is already installed. Enabled for current agent.`,
+ state: {
+ installed: true,
+ pluginId: identifier,
+ pluginName: installedPlugin?.manifest?.meta?.title || identifier,
+ success: true,
+ } as InstallPluginState,
+ success: true,
+ };
+ }
+
+ // Plugin needs to be installed - return state requiring approval
+ // The actual installation will happen when user approves
+ return {
+ content: `MCP plugin "${identifier}" will be installed. Please approve to continue.`,
+ state: {
+ awaitingApproval: true,
+ installed: false,
+ pluginId: identifier,
+ success: true,
+ } as InstallPluginState,
+ success: true,
+ };
+ } catch (error) {
+ const err = error as Error;
+ return {
+ content: `Failed to install plugin: ${err.message}`,
+ error,
+ state: {
+ error: err.message,
+ installed: false,
+ pluginId: identifier,
+ success: false,
+ } as InstallPluginState,
+ success: false,
+ };
+ }
+ }
+}
diff --git a/packages/builtin-tool-agent-builder/src/client/Intervention/InstallPlugin.tsx b/packages/builtin-tool-agent-builder/src/client/Intervention/InstallPlugin.tsx
new file mode 100644
index 00000000000..f686b736bcc
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/client/Intervention/InstallPlugin.tsx
@@ -0,0 +1,133 @@
+'use client';
+
+import { KLAVIS_SERVER_TYPES } from '@lobechat/const';
+import { BuiltinInterventionProps } from '@lobechat/types';
+import { Avatar } from '@lobehub/ui';
+import { CheckCircle } from 'lucide-react';
+import Image from 'next/image';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useToolStore } from '@/store/tool';
+import { klavisStoreSelectors, pluginSelectors } from '@/store/tool/selectors';
+import { KlavisServerStatus } from '@/store/tool/slices/klavisStore/types';
+
+import type { InstallPluginParams } from '../../types';
+
+/**
+ * InstallPlugin Intervention Component
+ *
+ * This component only renders the UI for user confirmation.
+ * The actual OAuth flow and installation logic is handled in ExecutionRuntime.installPlugin()
+ * which runs after the user approves the intervention.
+ */
+const InstallPluginIntervention = memo<BuiltinInterventionProps<InstallPluginParams>>(
+ ({ args }) => {
+ const { identifier, source } = args;
+ const { t } = useTranslation('chat');
+
+ // Tool store selectors
+ const isPluginInstalled = useToolStore((s) => pluginSelectors.isPluginInstalled(identifier)(s));
+
+ // Get Klavis server state
+ const klavisServer = useToolStore((s) =>
+ klavisStoreSelectors.getServers(s).find((srv) => srv.identifier === identifier),
+ );
+
+ // Check if it's a Klavis tool
+ const klavisTypeInfo = KLAVIS_SERVER_TYPES.find((t) => t.identifier === identifier);
+ const isKlavis = source === 'official' && !!klavisTypeInfo;
+
+ // Render success state (already installed)
+ if (isPluginInstalled) {
+ return (
+ <Flexbox
+ align="center"
+ gap={12}
+ horizontal
+ style={{
+ background: 'var(--lobe-fill-tertiary)',
+ borderRadius: 8,
+ padding: 16,
+ }}
+ >
+ <CheckCircle size={20} style={{ color: 'var(--lobe-success-6)' }} />
+ <Flexbox gap={4}>
+ <span style={{ fontWeight: 600 }}>
+ {isKlavis
+ ? t('agentBuilder.installPlugin.connectedAndEnabled')
+ : t('agentBuilder.installPlugin.installedAndEnabled')}
+ </span>
+ <span style={{ color: 'var(--lobe-text-secondary)', fontSize: 12 }}>
+ {klavisTypeInfo?.label || identifier}
+ </span>
+ </Flexbox>
+ </Flexbox>
+ );
+ }
+
+ // Render Klavis tool
+ if (isKlavis) {
+ const icon = typeof klavisTypeInfo?.icon === 'string' ? klavisTypeInfo.icon : undefined;
+ const isPendingAuth = klavisServer?.status === KlavisServerStatus.PENDING_AUTH;
+
+ return (
+ <Flexbox
+ gap={12}
+ style={{ background: 'var(--lobe-fill-tertiary)', borderRadius: 8, padding: 16 }}
+ >
+ <Flexbox align="center" gap={12} horizontal>
+ {icon ? (
+ <Image
+ alt={klavisTypeInfo?.label || identifier}
+ height={40}
+ src={icon}
+ style={{ borderRadius: 8 }}
+ unoptimized
+ width={40}
+ />
+ ) : (
+ <Avatar avatar="☁️" size={40} style={{ borderRadius: 8 }} />
+ )}
+ <Flexbox flex={1} gap={4}>
+ <Flexbox align="center" gap={8} horizontal>
+ <span style={{ fontWeight: 600 }}>{klavisTypeInfo?.label || identifier}</span>
+ <span style={{ color: 'var(--lobe-text-tertiary)', fontSize: 12 }}>Klavis</span>
+ </Flexbox>
+ <span style={{ color: 'var(--lobe-text-secondary)', fontSize: 12 }}>
+ {isPendingAuth
+ ? t('agentBuilder.installPlugin.requiresAuth')
+ : t('agentBuilder.installPlugin.clickApproveToConnect')}
+ </span>
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ );
+ }
+
+ // Render MCP marketplace plugin
+ // Note: The actual installation happens in ExecutionRuntime after user approves
+ return (
+ <Flexbox
+ gap={12}
+ style={{ background: 'var(--lobe-fill-tertiary)', borderRadius: 8, padding: 16 }}
+ >
+ <Flexbox align="center" gap={12} horizontal>
+ <Avatar avatar="🔧" size={40} style={{ borderRadius: 8 }} />
+ <Flexbox flex={1} gap={4}>
+ <Flexbox align="center" gap={8} horizontal>
+ <span style={{ fontWeight: 600 }}>{identifier}</span>
+ <span style={{ color: 'var(--lobe-text-tertiary)', fontSize: 12 }}>MCP Plugin</span>
+ </Flexbox>
+ <span style={{ color: 'var(--lobe-text-secondary)', fontSize: 12 }}>
+ {t('agentBuilder.installPlugin.clickApproveToInstall')}
+ </span>
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+export default InstallPluginIntervention;
diff --git a/packages/builtin-tool-agent-builder/src/client/Intervention/index.ts b/packages/builtin-tool-agent-builder/src/client/Intervention/index.ts
new file mode 100644
index 00000000000..2f07803462c
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/client/Intervention/index.ts
@@ -0,0 +1,10 @@
+import { AgentBuilderApiName } from '../../types';
+import InstallPlugin from './InstallPlugin';
+
+/**
+ * Agent Builder Intervention Components Registry
+ * Only register APIs that have custom intervention UI
+ */
+export const AgentBuilderInterventions = {
+ [AgentBuilderApiName.installPlugin]: InstallPlugin,
+};
diff --git a/packages/builtin-tool-agent-builder/src/client/Render/GetAvailableModels.tsx b/packages/builtin-tool-agent-builder/src/client/Render/GetAvailableModels.tsx
new file mode 100644
index 00000000000..e8b8f939080
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/client/Render/GetAvailableModels.tsx
@@ -0,0 +1,68 @@
+import { BuiltinRenderProps } from '@lobechat/types';
+import { Tag } from 'antd';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import type { GetAvailableModelsParams, GetAvailableModelsState } from '../../types';
+
+const GetAvailableModels = memo<
+ BuiltinRenderProps<GetAvailableModelsParams, GetAvailableModelsState>
+>(({ pluginState }) => {
+ const { providers } = pluginState || {};
+
+ if (!providers || providers.length === 0) {
+ return (
+ <Flexbox style={{ color: 'var(--lobe-text-secondary)', fontSize: 13 }}>
+ No available models found.
+ </Flexbox>
+ );
+ }
+
+ return (
+ <Flexbox gap={12} style={{ fontSize: 13 }}>
+ {providers.map((provider) => (
+ <Flexbox gap={8} key={provider.id}>
+ <Flexbox align="center" gap={8} horizontal>
+ <span style={{ fontWeight: 600 }}>{provider.name}</span>
+ <Tag color="blue" style={{ margin: 0 }}>
+ {provider.models.length} models
+ </Tag>
+ </Flexbox>
+ <Flexbox
+ gap={4}
+ style={{
+ background: 'var(--lobe-fill-tertiary)',
+ borderRadius: 6,
+ maxHeight: 200,
+ overflow: 'auto',
+ padding: 8,
+ }}
+ >
+ {provider.models.map((model) => (
+ <Flexbox align="center" gap={8} horizontal key={model.id} style={{ fontSize: 12 }}>
+ <code style={{ color: 'var(--lobe-text)' }}>{model.id}</code>
+ {model.abilities?.vision && (
+ <Tag color="purple" style={{ fontSize: 10, margin: 0 }}>
+ vision
+ </Tag>
+ )}
+ {model.abilities?.functionCall && (
+ <Tag color="green" style={{ fontSize: 10, margin: 0 }}>
+ tools
+ </Tag>
+ )}
+ {model.abilities?.reasoning && (
+ <Tag color="orange" style={{ fontSize: 10, margin: 0 }}>
+ reasoning
+ </Tag>
+ )}
+ </Flexbox>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ ))}
+ </Flexbox>
+ );
+});
+
+export default GetAvailableModels;
diff --git a/packages/builtin-tool-agent-builder/src/client/Render/InstallPlugin.tsx b/packages/builtin-tool-agent-builder/src/client/Render/InstallPlugin.tsx
new file mode 100644
index 00000000000..5f3f2e99664
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/client/Render/InstallPlugin.tsx
@@ -0,0 +1,114 @@
+'use client';
+
+import { BuiltinRenderProps } from '@lobechat/types';
+import { CheckCircle, Clock, XCircle } from 'lucide-react';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import type { InstallPluginParams, InstallPluginState } from '../../types';
+
+const InstallPlugin = memo<BuiltinRenderProps<InstallPluginParams, InstallPluginState>>(
+ ({ pluginState }) => {
+ const { pluginId, pluginName, installed, awaitingApproval, isKlavis, serverStatus, error } =
+ pluginState || {};
+
+ if (!pluginId) return null;
+
+ // Error state
+ if (error) {
+ return (
+ <Flexbox align={'center'} gap={8} horizontal style={{ fontSize: 13 }}>
+ <XCircle size={14} style={{ color: 'var(--lobe-error-6)' }} />
+ <span style={{ fontWeight: 500 }}>
+ Failed to install plugin:{' '}
+ <code
+ style={{
+ background: 'var(--lobe-fill-tertiary)',
+ borderRadius: 4,
+ color: 'var(--lobe-text)',
+ fontSize: 12,
+ padding: '2px 6px',
+ }}
+ >
+ {pluginName || pluginId}
+ </code>
+ </span>
+ </Flexbox>
+ );
+ }
+
+ // Awaiting approval state
+ if (awaitingApproval) {
+ return (
+ <Flexbox align={'center'} gap={8} horizontal style={{ fontSize: 13 }}>
+ <Clock size={14} style={{ color: 'var(--lobe-warning-6)' }} />
+ <span style={{ fontWeight: 500 }}>
+ {isKlavis ? (
+ <>
+ Waiting for authorization:{' '}
+ <code
+ style={{
+ background: 'var(--lobe-fill-tertiary)',
+ borderRadius: 4,
+ color: 'var(--lobe-text)',
+ fontSize: 12,
+ padding: '2px 6px',
+ }}
+ >
+ {pluginName || pluginId}
+ </code>
+ {serverStatus === 'pending_auth' && (
+ <span style={{ color: 'var(--lobe-text-tertiary)', marginLeft: 8 }}>
+ (OAuth required)
+ </span>
+ )}
+ </>
+ ) : (
+ <>
+ Waiting for installation approval:{' '}
+ <code
+ style={{
+ background: 'var(--lobe-fill-tertiary)',
+ borderRadius: 4,
+ color: 'var(--lobe-text)',
+ fontSize: 12,
+ padding: '2px 6px',
+ }}
+ >
+ {pluginName || pluginId}
+ </code>
+ </>
+ )}
+ </span>
+ </Flexbox>
+ );
+ }
+
+ // Installed state
+ if (installed) {
+ return (
+ <Flexbox align={'center'} gap={8} horizontal style={{ fontSize: 13 }}>
+ <CheckCircle size={14} style={{ color: 'var(--lobe-success-6)' }} />
+ <span style={{ fontWeight: 500 }}>
+ {isKlavis ? 'Connected and enabled' : 'Installed and enabled'}:{' '}
+ <code
+ style={{
+ background: 'var(--lobe-fill-tertiary)',
+ borderRadius: 4,
+ color: 'var(--lobe-text)',
+ fontSize: 12,
+ padding: '2px 6px',
+ }}
+ >
+ {pluginName || pluginId}
+ </code>
+ </span>
+ </Flexbox>
+ );
+ }
+
+ return null;
+ },
+);
+
+export default InstallPlugin;
diff --git a/packages/builtin-tool-agent-builder/src/client/Render/SearchMarketTools.tsx b/packages/builtin-tool-agent-builder/src/client/Render/SearchMarketTools.tsx
new file mode 100644
index 00000000000..60a5e02db50
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/client/Render/SearchMarketTools.tsx
@@ -0,0 +1,161 @@
+'use client';
+
+import { BuiltinRenderProps } from '@lobechat/types';
+import { Avatar, Button, Tag } from '@lobehub/ui';
+import { CheckCircle, Download, Package, Search } from 'lucide-react';
+import { memo, useState } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
+import { useAgentStore } from '@/store/agent';
+import { useToolStore } from '@/store/tool';
+import { mcpStoreSelectors, pluginSelectors } from '@/store/tool/selectors';
+
+import type { MarketToolItem, SearchMarketToolsParams, SearchMarketToolsState } from '../../types';
+
+interface ToolItemProps {
+ tool: MarketToolItem;
+}
+
+const ToolItem = memo<ToolItemProps>(({ tool }) => {
+ const { isAuthenticated, signIn } = useMarketAuth();
+ const [localInstalling, setLocalInstalling] = useState(false);
+
+ const [installed, installing, installMCPPlugin, cancelInstallMCPPlugin] = useToolStore((s) => [
+ pluginSelectors.isPluginInstalled(tool.identifier)(s),
+ mcpStoreSelectors.isMCPInstalling(tool.identifier)(s),
+ s.installMCPPlugin,
+ s.cancelInstallMCPPlugin,
+ ]);
+
+ const togglePlugin = useAgentStore((s) => s.togglePlugin);
+
+ const isCloudMcp = !!(tool.cloudEndPoint || tool.haveCloudEndpoint);
+ const isInstalling = installing || localInstalling;
+
+ const handleInstall = async () => {
+ // If this is a cloud MCP and user is not authenticated, request authorization first
+ if (isCloudMcp && !isAuthenticated) {
+ try {
+ await signIn();
+ } catch {
+ return;
+ }
+ }
+
+ setLocalInstalling(true);
+ try {
+ const isSuccess = await installMCPPlugin(tool.identifier);
+ if (isSuccess) {
+ await togglePlugin(tool.identifier);
+ }
+ } finally {
+ setLocalInstalling(false);
+ }
+ };
+
+ const handleCancel = async () => {
+ await cancelInstallMCPPlugin(tool.identifier);
+ };
+
+ return (
+ <Flexbox
+ gap={12}
+ horizontal
+ style={{
+ background: 'var(--lobe-fill-tertiary)',
+ borderRadius: 8,
+ padding: 12,
+ }}
+ >
+ <Avatar avatar={tool.icon || '🔧'} size={40} style={{ borderRadius: 8, flexShrink: 0 }} />
+ <Flexbox flex={1} gap={4} style={{ overflow: 'hidden' }}>
+ <Flexbox align="center" gap={8} horizontal>
+ <span style={{ fontWeight: 600 }}>{tool.name}</span>
+ {tool.author && (
+ <span style={{ color: 'var(--lobe-text-tertiary)', fontSize: 12 }}>
+ by {tool.author}
+ </span>
+ )}
+ </Flexbox>
+ {tool.description && (
+ <div
+ style={{
+ color: 'var(--lobe-text-secondary)',
+ fontSize: 12,
+ lineHeight: 1.5,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ }}
+ >
+ {tool.description}
+ </div>
+ )}
+ {tool.tags && tool.tags.length > 0 && (
+ <Flexbox gap={4} horizontal style={{ flexWrap: 'wrap', marginTop: 4 }}>
+ {tool.tags.slice(0, 3).map((tag) => (
+ <Tag key={tag} style={{ fontSize: 10 }}>
+ {tag}
+ </Tag>
+ ))}
+ </Flexbox>
+ )}
+ </Flexbox>
+ <Flexbox align="center" justify="center" style={{ flexShrink: 0 }}>
+ {installed || tool.installed ? (
+ <Flexbox align="center" gap={4} horizontal style={{ color: 'var(--lobe-success-6)' }}>
+ <CheckCircle size={14} />
+ <span style={{ fontSize: 12 }}>Installed</span>
+ </Flexbox>
+ ) : isInstalling ? (
+ <Button onClick={handleCancel} size="small" variant="filled">
+ Cancel
+ </Button>
+ ) : (
+ <Button icon={<Download size={14} />} onClick={handleInstall} size="small" type="primary">
+ Install
+ </Button>
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+const SearchMarketTools = memo<BuiltinRenderProps<SearchMarketToolsParams, SearchMarketToolsState>>(
+ ({ pluginState }) => {
+ const { tools, totalCount, query } = pluginState || { tools: [], totalCount: 0 };
+
+ if (!tools || tools.length === 0) {
+ return (
+ <Flexbox align="center" gap={8} style={{ color: 'var(--lobe-text-tertiary)', padding: 16 }}>
+ <Search size={24} />
+ <span>No tools found{query ? ` for "${query}"` : ''}.</span>
+ </Flexbox>
+ );
+ }
+
+ const installedCount = tools.filter((t) => t.installed).length;
+
+ return (
+ <Flexbox gap={12}>
+ <Flexbox align="center" gap={8} horizontal>
+ <Package size={16} style={{ color: 'var(--lobe-primary-6)' }} />
+ <span style={{ fontWeight: 500 }}>
+ {query ? `Search results for "${query}"` : 'Available Tools'}
+ </span>
+ <span style={{ color: 'var(--lobe-text-tertiary)', fontSize: 12 }}>
+ ({totalCount} total, {installedCount} installed)
+ </span>
+ </Flexbox>
+ <Flexbox gap={8}>
+ {tools.map((tool) => (
+ <ToolItem key={tool.identifier} tool={tool} />
+ ))}
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+export default SearchMarketTools;
diff --git a/packages/builtin-tool-agent-builder/src/client/Render/UpdateConfig.tsx b/packages/builtin-tool-agent-builder/src/client/Render/UpdateConfig.tsx
new file mode 100644
index 00000000000..ab408e995fb
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/client/Render/UpdateConfig.tsx
@@ -0,0 +1,65 @@
+import { BuiltinRenderProps } from '@lobechat/types';
+import { CheckCircle, XCircle } from 'lucide-react';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import type { UpdateAgentConfigParams, UpdateConfigState } from '../../types';
+import ConfigDiffView from './components/ConfigDiffView';
+
+const UpdateConfig = memo<BuiltinRenderProps<UpdateAgentConfigParams, UpdateConfigState>>(
+ ({ pluginState }) => {
+ const { config, meta, togglePlugin } = pluginState || {};
+
+ const hasConfig = config && config.updatedFields.length > 0;
+ const hasMeta = meta && meta.updatedFields.length > 0;
+ const hasTogglePlugin = togglePlugin && togglePlugin.pluginId;
+
+ if (!hasConfig && !hasMeta && !hasTogglePlugin) {
+ return null;
+ }
+
+ return (
+ <Flexbox gap={8}>
+ {hasTogglePlugin && (
+ <Flexbox align={'center'} gap={8} horizontal style={{ fontSize: 13 }}>
+ {togglePlugin.enabled ? (
+ <CheckCircle size={14} style={{ color: 'var(--lobe-success-6)' }} />
+ ) : (
+ <XCircle size={14} style={{ color: 'var(--lobe-text-tertiary)' }} />
+ )}
+ <span style={{ fontWeight: 500 }}>
+ {togglePlugin.enabled ? 'Enabled' : 'Disabled'} plugin:{' '}
+ <code
+ style={{
+ background: 'var(--lobe-fill-tertiary)',
+ borderRadius: 4,
+ color: 'var(--lobe-text)',
+ fontSize: 12,
+ padding: '2px 6px',
+ }}
+ >
+ {togglePlugin.pluginId}
+ </code>
+ </span>
+ </Flexbox>
+ )}
+ {hasConfig && (
+ <ConfigDiffView
+ newValues={config.newValues}
+ previousValues={config.previousValues}
+ updatedFields={config.updatedFields}
+ />
+ )}
+ {hasMeta && (
+ <ConfigDiffView
+ newValues={meta.newValues}
+ previousValues={meta.previousValues}
+ updatedFields={meta.updatedFields}
+ />
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+export default UpdateConfig;
diff --git a/packages/builtin-tool-agent-builder/src/client/Render/UpdatePrompt.tsx b/packages/builtin-tool-agent-builder/src/client/Render/UpdatePrompt.tsx
new file mode 100644
index 00000000000..cb8667dab27
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/client/Render/UpdatePrompt.tsx
@@ -0,0 +1,59 @@
+import { BuiltinRenderProps } from '@lobechat/types';
+import { CheckCircle, FileText } from 'lucide-react';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import type { UpdatePromptParams, UpdatePromptState } from '../../types';
+
+const UpdatePrompt = memo<BuiltinRenderProps<UpdatePromptParams, UpdatePromptState>>(
+ ({ pluginState }) => {
+ const { newPrompt } = pluginState || {};
+
+ return (
+ <Flexbox gap={8} style={{ fontSize: 13 }}>
+ <Flexbox align={'center'} gap={6} horizontal style={{ color: 'var(--lobe-success-6)' }}>
+ <CheckCircle size={14} />
+ <span style={{ fontWeight: 500 }}>
+ {newPrompt ? 'System prompt updated' : 'System prompt cleared'}
+ </span>
+ </Flexbox>
+
+ {newPrompt && (
+ <Flexbox
+ gap={8}
+ style={{
+ background: 'var(--lobe-fill-tertiary)',
+ borderLeft: '3px solid var(--lobe-success-6)',
+ borderRadius: 6,
+ marginLeft: 20,
+ padding: 12,
+ }}
+ >
+ <Flexbox align={'center'} gap={6} horizontal>
+ <FileText size={14} style={{ color: 'var(--lobe-text-tertiary)' }} />
+ <span style={{ color: 'var(--lobe-text-secondary)', fontSize: 12, fontWeight: 500 }}>
+ New prompt ({newPrompt.length} characters):
+ </span>
+ </Flexbox>
+ <div
+ style={{
+ color: 'var(--lobe-text)',
+ fontSize: 13,
+ lineHeight: 1.6,
+ marginLeft: 20,
+ maxHeight: 200,
+ overflow: 'auto',
+ whiteSpace: 'pre-wrap',
+ wordBreak: 'break-word',
+ }}
+ >
+ {newPrompt.length > 500 ? newPrompt.slice(0, 500) + '...' : newPrompt}
+ </div>
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+export default UpdatePrompt;
diff --git a/packages/builtin-tool-agent-builder/src/client/Render/components/ConfigCard.tsx b/packages/builtin-tool-agent-builder/src/client/Render/components/ConfigCard.tsx
new file mode 100644
index 00000000000..28057cfc65f
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/client/Render/components/ConfigCard.tsx
@@ -0,0 +1,33 @@
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+interface ConfigCardProps {
+ config: Record<string, unknown>;
+ title?: string;
+}
+
+const ConfigCard = memo<ConfigCardProps>(({ config, title }) => {
+ return (
+ <Flexbox gap={8} style={{ fontSize: 13 }}>
+ {title && (
+ <span style={{ color: 'var(--lobe-text-secondary)', fontWeight: 500 }}>{title}</span>
+ )}
+ <pre
+ style={{
+ background: 'var(--lobe-fill-tertiary)',
+ borderRadius: 6,
+ color: 'var(--lobe-text)',
+ fontSize: 12,
+ margin: 0,
+ maxHeight: 400,
+ overflow: 'auto',
+ padding: 12,
+ }}
+ >
+ {JSON.stringify(config, null, 2)}
+ </pre>
+ </Flexbox>
+ );
+});
+
+export default ConfigCard;
diff --git a/packages/builtin-tool-agent-builder/src/client/Render/components/ConfigDiffView.tsx b/packages/builtin-tool-agent-builder/src/client/Render/components/ConfigDiffView.tsx
new file mode 100644
index 00000000000..5b8a49a5185
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/client/Render/components/ConfigDiffView.tsx
@@ -0,0 +1,72 @@
+import { CheckCircle, ChevronRight } from 'lucide-react';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+interface ConfigDiffViewProps {
+ newValues: Record<string, unknown>;
+ previousValues: Record<string, unknown>;
+ updatedFields: string[];
+}
+
+function formatValue(value: unknown): string {
+ if (value === undefined) return 'undefined';
+ if (value === null) return 'null';
+ if (typeof value === 'string') return `"${value}"`;
+ if (typeof value === 'boolean') return value ? 'true' : 'false';
+ if (typeof value === 'number') return String(value);
+ if (Array.isArray(value)) {
+ if (value.length === 0) return '[]';
+ if (value.length <= 3) return `[${value.map(formatValue).join(', ')}]`;
+ return `[${value.length} items]`;
+ }
+ if (typeof value === 'object') return JSON.stringify(value, null, 2);
+ return String(value);
+}
+
+const ConfigDiffView = memo<ConfigDiffViewProps>(({ updatedFields, previousValues, newValues }) => {
+ if (updatedFields.length === 0) {
+ return null;
+ }
+
+ return (
+ <Flexbox gap={8} style={{ fontSize: 13 }}>
+ <Flexbox align={'center'} gap={6} horizontal style={{ color: 'var(--lobe-success-6)' }}>
+ <CheckCircle size={14} />
+ <span style={{ fontWeight: 500 }}>Updated {updatedFields.length} field(s)</span>
+ </Flexbox>
+
+ <Flexbox gap={8} style={{ marginLeft: 20 }}>
+ {updatedFields.map((field) => {
+ const oldValue = previousValues[field];
+ const newValue = newValues[field];
+
+ return (
+ <Flexbox gap={4} key={field}>
+ <span style={{ color: 'var(--lobe-text-secondary)', fontWeight: 500 }}>{field}:</span>
+ <Flexbox align={'center'} gap={8} horizontal style={{ marginLeft: 12 }}>
+ <span
+ style={{
+ color: 'var(--lobe-text-tertiary)',
+ opacity: 0.7,
+ textDecoration: 'line-through',
+ }}
+ >
+ {formatValue(oldValue)}
+ </span>
+ <ChevronRight
+ size={12}
+ style={{ color: 'var(--lobe-text-tertiary)', opacity: 0.5 }}
+ />
+ <span style={{ color: 'var(--lobe-success-6)', fontWeight: 500 }}>
+ {formatValue(newValue)}
+ </span>
+ </Flexbox>
+ </Flexbox>
+ );
+ })}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+export default ConfigDiffView;
diff --git a/packages/builtin-tool-agent-builder/src/client/Render/index.ts b/packages/builtin-tool-agent-builder/src/client/Render/index.ts
new file mode 100644
index 00000000000..c6c1ce87e5e
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/client/Render/index.ts
@@ -0,0 +1,26 @@
+import { AgentBuilderApiName } from '../../types';
+import GetAvailableModels from './GetAvailableModels';
+import InstallPlugin from './InstallPlugin';
+import SearchMarketTools from './SearchMarketTools';
+import UpdateConfig from './UpdateConfig';
+import UpdatePrompt from './UpdatePrompt';
+
+/**
+ * Agent Builder Render Components Registry
+ *
+ * Note: Read operations (GetConfig, GetMeta, GetPrompt, GetAvailableTools, SearchOfficialTools) are removed
+ * because the current agent context is now automatically injected into the conversation.
+ *
+ * Note: Specific field operations (SetModel, SetOpeningMessage, SetOpeningQuestions, UpdateChatConfig, UpdateMeta, TogglePlugin)
+ * are removed and consolidated into updateAgentConfig.
+ */
+export const AgentBuilderRenders = {
+ // Read operations
+ [AgentBuilderApiName.getAvailableModels]: GetAvailableModels,
+ [AgentBuilderApiName.searchMarketTools]: SearchMarketTools,
+
+ // Write operations
+ [AgentBuilderApiName.installPlugin]: InstallPlugin,
+ [AgentBuilderApiName.updateAgentConfig]: UpdateConfig,
+ [AgentBuilderApiName.updatePrompt]: UpdatePrompt,
+};
diff --git a/packages/builtin-tool-agent-builder/src/client/index.ts b/packages/builtin-tool-agent-builder/src/client/index.ts
new file mode 100644
index 00000000000..d51263fa4c2
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/client/index.ts
@@ -0,0 +1,6 @@
+export { AgentBuilderInterventions } from './Intervention';
+export { AgentBuilderRenders } from './Render';
+
+// Re-export types and manifest for convenience
+export { AgentBuilderManifest } from '../manifest';
+export * from '../types';
diff --git a/packages/builtin-tool-agent-builder/src/index.ts b/packages/builtin-tool-agent-builder/src/index.ts
new file mode 100644
index 00000000000..9bd9b9313b0
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/index.ts
@@ -0,0 +1,20 @@
+export { AgentBuilderManifest } from './manifest';
+export { systemPrompt } from './systemRole';
+export {
+ AgentBuilderApiName,
+ type AgentBuilderApiNameType,
+ AgentBuilderIdentifier,
+ type AvailableModel,
+ type AvailableProvider,
+ type GetAvailableModelsParams,
+ type GetAvailableModelsState,
+ type InstallPluginParams,
+ type InstallPluginState,
+ type MarketToolItem,
+ type SearchMarketToolsParams,
+ type SearchMarketToolsState,
+ type UpdateAgentConfigParams,
+ type UpdateConfigState,
+ type UpdatePromptParams,
+ type UpdatePromptState,
+} from './types';
diff --git a/packages/builtin-tool-agent-builder/src/manifest.ts b/packages/builtin-tool-agent-builder/src/manifest.ts
new file mode 100644
index 00000000000..95b63a189d4
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/manifest.ts
@@ -0,0 +1,208 @@
+import type { BuiltinToolManifest } from '@lobechat/types';
+
+import { systemPrompt } from './systemRole';
+import { AgentBuilderApiName, AgentBuilderIdentifier } from './types';
+
+export const AgentBuilderManifest: BuiltinToolManifest = {
+ api: [
+ // ==================== Read Operations ====================
+ // Note: getAgentConfig, getAgentMeta, getPrompt are removed because
+ // the current agent context is now automatically injected into the conversation
+ {
+ description:
+ 'Get all available AI models and providers that can be used for the agent. Returns a list of providers with their supported models and capabilities (vision, function calling, reasoning, etc.).',
+ name: AgentBuilderApiName.getAvailableModels,
+ parameters: {
+ properties: {
+ providerId: {
+ description:
+ 'Optional: filter models by a specific provider id (e.g., "openai", "anthropic", "google")',
+ type: 'string',
+ },
+ },
+ required: [],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Search for tools (MCP plugins) in the marketplace. Users can browse and install tools directly from the search results. Use this when users want to find new tools or capabilities.',
+ name: AgentBuilderApiName.searchMarketTools,
+ parameters: {
+ properties: {
+ category: {
+ description:
+ 'Optional: filter by category. Available categories: developer, productivity, web-search, tools, media-generate, etc.',
+ type: 'string',
+ },
+ pageSize: {
+ description: 'Optional: number of results to return (default: 10, max: 20).',
+ type: 'number',
+ },
+ query: {
+ description:
+ 'Optional: search keywords to find specific tools. Leave empty to browse all available tools.',
+ type: 'string',
+ },
+ },
+ required: [],
+ type: 'object',
+ },
+ },
+ // Note: searchOfficialTools is removed because official tools are now
+ // automatically injected into the conversation context
+
+ // ==================== Write Operations ====================
+ {
+ description:
+ 'Install a plugin for the agent. This tool ALWAYS REQUIRES user approval before installation, even in auto-run mode. For MCP marketplace plugins, it will install and enable the plugin. For Klavis tools that need OAuth, it will initiate the connection flow and wait for user to complete authorization.',
+ humanIntervention: 'always',
+ name: AgentBuilderApiName.installPlugin,
+ parameters: {
+ properties: {
+ identifier: {
+ description:
+ 'The plugin identifier to install (e.g., "mcp-tavily-search", "google-calendar")',
+ type: 'string',
+ },
+ source: {
+ description:
+ 'Plugin source type: "market" for MCP marketplace plugins, "official" for builtin/Klavis tools',
+ enum: ['market', 'official'],
+ type: 'string',
+ },
+ },
+ required: ['identifier', 'source'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Update agent configuration and/or metadata. Use this to change model, provider, plugins, opening message, opening questions, chat settings, model parameters, title, description, avatar, tags, and toggle plugins. Only include fields you want to update. Use togglePlugin to enable/disable a specific plugin.',
+ name: AgentBuilderApiName.updateAgentConfig,
+ parameters: {
+ properties: {
+ config: {
+ description:
+ 'Partial agent configuration object. Only include fields you want to update.',
+ properties: {
+ chatConfig: {
+ description:
+ 'Chat configuration settings (historyCount, enableHistoryCount, enableAutoCreateTopic, autoCreateTopicThreshold, enableCompressHistory, enableStreaming, enableReasoning)',
+ type: 'object',
+ },
+ model: {
+ description:
+ 'The AI model identifier (e.g., "gpt-4o", "gpt-4o-mini", "claude-3-5-sonnet-20241022", "gemini-1.5-pro")',
+ type: 'string',
+ },
+ openingMessage: {
+ description:
+ 'Opening message for new conversations. Set to empty string to remove.',
+ type: 'string',
+ },
+ openingQuestions: {
+ description:
+ 'Array of suggested opening questions. Set to empty array to remove all.',
+ items: { type: 'string' },
+ type: 'array',
+ },
+ params: {
+ description:
+ 'Model parameters like temperature (0-2), top_p (0-1), frequency_penalty (0-2), presence_penalty (0-2)',
+ type: 'object',
+ },
+ plugins: {
+ description:
+ 'Array of enabled plugin identifiers. Note: prefer using togglePlugin for single plugin changes.',
+ items: { type: 'string' },
+ type: 'array',
+ },
+ provider: {
+ description:
+ 'The AI provider identifier (e.g., "openai", "anthropic", "google", "azure")',
+ type: 'string',
+ },
+ },
+ type: 'object',
+ },
+ meta: {
+ description: 'Partial metadata object. Only include fields you want to update.',
+ properties: {
+ avatar: {
+ description: 'Agent avatar (emoji or image URL)',
+ type: 'string',
+ },
+ backgroundColor: {
+ description: 'Background color for the agent card',
+ type: 'string',
+ },
+ description: {
+ description: 'Agent description',
+ type: 'string',
+ },
+ tags: {
+ description: 'Array of tags for categorization',
+ items: { type: 'string' },
+ type: 'array',
+ },
+ title: {
+ description: 'Agent display name',
+ type: 'string',
+ },
+ },
+ type: 'object',
+ },
+ togglePlugin: {
+ description:
+ 'Toggle a specific plugin on/off. This is the preferred way to enable/disable a single plugin.',
+ properties: {
+ enabled: {
+ description:
+ 'Whether to enable (true) or disable (false) the plugin. If not provided, toggles current state.',
+ type: 'boolean',
+ },
+ pluginId: {
+ description:
+ 'The identifier of the plugin to toggle (e.g., "lobe-web-browsing", "lobe-image-generation")',
+ type: 'string',
+ },
+ },
+ required: ['pluginId'],
+ type: 'object',
+ },
+ },
+ required: [],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ "Update the agent's system prompt (systemRole). This is the core instruction that defines how the agent behaves, responds, and interacts with users. Use streaming mode for a typewriter effect in the editor.",
+ name: AgentBuilderApiName.updatePrompt,
+ parameters: {
+ properties: {
+ prompt: {
+ description:
+ 'The new system prompt content. Supports markdown formatting. Set to empty string to clear the prompt.',
+ type: 'string',
+ },
+ streaming: {
+ description:
+ 'Whether to use streaming mode for typewriter effect in the editor. Defaults to true for better UX.',
+ type: 'boolean',
+ },
+ },
+ required: ['prompt'],
+ type: 'object',
+ },
+ },
+ ],
+ identifier: AgentBuilderIdentifier,
+ meta: {
+ avatar: '🛠️',
+ title: 'Agent Builder',
+ },
+ systemRole: systemPrompt,
+ type: 'builtin',
+};
diff --git a/packages/builtin-tool-agent-builder/src/systemRole.ts b/packages/builtin-tool-agent-builder/src/systemRole.ts
new file mode 100644
index 00000000000..20a28f98f2a
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/systemRole.ts
@@ -0,0 +1,213 @@
+/**
+ * System role for Agent Builder tool
+ *
+ * This provides guidance on how to effectively use the agent builder tools
+ * for configuring and optimizing AI agents.
+ */
+export const systemPrompt = `You are an Agent Configuration Assistant integrated into LobeChat. Your role is to help users configure and optimize their AI agents through natural conversation.
+
+<context_awareness>
+**Important**: The current agent's configuration, metadata, and available official tools are automatically injected into the conversation context as \`<current_agent_context>\`. You can reference this information directly without calling any read APIs.
+
+The injected context includes:
+- **agent_meta**: title, description, avatar, backgroundColor, tags
+- **agent_config**: model, provider, plugins, systemRole (preview), and other advanced settings
+- **official_tools**: List of available official tools including built-in tools and LobeHub integrations (Gmail, Google Calendar, Notion, GitHub, etc.) with their enabled/installed status
+
+You should use this context to understand the current state of the agent and available tools before making any modifications.
+</context_awareness>
+
+<capabilities>
+You have access to tools that can modify agent configurations:
+
+**Read Operations:**
+- **getAvailableModels**: Get all available AI models and providers that can be used. Optionally filter by provider ID.
+- **searchMarketTools**: Search for tools (MCP plugins) in the marketplace. Shows results with install buttons for users to install directly.
+
+Note: Official tools (built-in tools and LobeHub Mcp integrations) are automatically available in the \`<current_agent_context>\` - no need to search for them.
+
+**Write Operations:**
+- **updateConfig**: Update agent configuration fields (model, provider, plugins, and advanced settings). Use this for all config changes.
+- **updateMeta**: Update agent metadata (title, description, avatar, tags, backgroundColor)
+- **updatePrompt**: Update the agent's system prompt (the core instruction that defines agent behavior)
+- **togglePlugin**: Enable or disable a specific plugin
+- **installPlugin**: Install and enable a plugin from marketplace or official tools
+</capabilities>
+
+<workflow>
+1. **Understand the request**: Listen carefully to what the user wants to configure
+2. **Reference injected context**: Use the \`<current_agent_context>\` to understand current configuration - no need to call read APIs
+3. **Make targeted changes**: Use updateConfig for config changes, updateMeta for metadata, updatePrompt for system prompt, togglePlugin for plugin toggles
+4. **Confirm changes**: Report what was changed and the new values
+</workflow>
+
+<modification_sequence>
+When creating or modifying an agent, follow this order:
+
+**Step 1: Metadata & Identity**
+Set avatar, title, description, tags, and backgroundColor first - establish who the agent is
+
+**Step 2: Model & Tools**
+Configure the AI model, provider, and enable necessary plugins/tools - define what capabilities the agent has
+
+**Step 3: System Prompt**
+Write or refine the system prompt last - this step benefits from knowing the agent's identity and available tools
+
+This sequence ensures the system prompt can reference the agent's established identity and capabilities.
+</modification_sequence>
+
+<display_conventions>
+When showing configuration to users, use semantic, user-friendly names instead of technical field names:
+
+| Technical Field | Display As (EN) | Display As (ZH) |
+|-----------------|-----------------|-----------------|
+| systemRole | System Prompt | 系统提示词 |
+| openingMessage | Opening Message | 开场白 |
+| openingQuestions | Suggested Questions | 开场问题 |
+| historyCount | Context History Limit | 上下文消息数 |
+| enableHistoryCount | Limit Context History | 限制上下文 |
+| enableCompressHistory | Compress Long History | 压缩长对话 |
+| enableStreaming | Stream Responses | 流式输出 |
+| enableReasoning | Reasoning Mode | 推理模式 |
+| temperature | Creativity Level | 创意度 |
+| top_p | Sampling Range | 采样范围 |
+| frequency_penalty | Reduce Repetition | 减少重复 |
+| presence_penalty | Topic Diversity | 话题多样性 |
+| autoCreateTopicThreshold | Auto-topic Threshold | 自动话题阈值 |
+
+Always adapt to user's language. Use natural descriptions, not raw field names.
+</display_conventions>
+
+<guidelines>
+1. **Use injected context**: The current agent's config and meta are already available in the conversation context. Reference them directly instead of calling read APIs.
+2. **Explain your changes**: When modifying configurations, explain what you're changing and why it might benefit the user.
+3. **Use updateConfig for config changes**: For model, provider, or other config changes, use the updateConfig API.
+4. **Validate user intent**: For significant changes (like changing the model or disabling important plugins), confirm with the user before proceeding.
+5. **Provide recommendations**: When users ask for advice, explain the trade-offs of different options based on their use case.
+6. **Use user's language**: Always respond in the same language the user is using.
+7. **Keep it simple**: Focus on core settings. Don't overwhelm users with advanced options unless they ask.
+</guidelines>
+
+<configuration_knowledge>
+**Core Settings (always show when asked about configuration):**
+
+**Model & Provider:**
+- model: The AI model identifier (e.g., "gpt-4o", "gpt-4o-mini", "claude-3-5-sonnet-20241022", "gemini-1.5-pro")
+- provider: The AI provider (e.g., "openai", "anthropic", "google", "azure")
+- Different models have different capabilities, costs, and speed trade-offs
+
+**System Prompt (systemRole):**
+- The core instruction that defines the agent's behavior, personality, and capabilities
+- Supports markdown formatting for rich text
+- Should clearly describe what the agent does and how it should respond
+- Can include specific instructions, constraints, and example responses
+- Use updatePrompt to modify the system prompt
+
+**Plugins:**
+- Array of enabled plugin identifiers
+- Common plugins: "lobe-web-browsing", "lobe-image-generation", "lobe-artifacts"
+- Plugins extend agent capabilities with external tools
+
+**Metadata:**
+- title: Display name for the agent
+- description: Brief description of what the agent does
+- avatar: Emoji or image URL for the agent's avatar
+- tags: Categories for organization
+- backgroundColor: Theme color for the agent card
+
+---
+
+**Advanced Settings (only mention when user explicitly asks):**
+
+**Model Parameters (params)** - Technical parameters for fine-tuning model behavior:
+- temperature: Controls randomness (0-2, default: 1). Lower = more focused, higher = more creative
+- top_p: Nucleus sampling parameter (0-1, default: 1)
+- frequency_penalty: Reduces repetition (0-2, default: 0)
+- presence_penalty: Encourages new topics (0-2, default: 0)
+
+**Opening Experience** - First-time conversation setup:
+- openingMessage: First message shown when starting a new conversation
+- openingQuestions: Suggested questions to help users get started
+
+**Chat Configuration (chatConfig)** - Conversation behavior settings:
+- historyCount: Number of previous messages to include in context (default: 20)
+- enableHistoryCount: Whether to limit history (default: true)
+- enableAutoCreateTopic: Automatically create topics based on conversation (default: true)
+- autoCreateTopicThreshold: Messages before auto-creating topic (default: 2)
+- enableCompressHistory: Compress long conversation history to save tokens (default: true)
+- enableStreaming: Stream responses in real-time (default: true)
+- enableReasoning: Enable reasoning/thinking mode for supported models (default: false)
+</configuration_knowledge>
+
+<examples>
+User: "帮我创建一个代码助手" / "Help me create a coding assistant"
+Action: Follow the modification sequence:
+1. First, use updateMeta to set identity: { avatar: "👨‍💻", title: "Code Assistant", description: "A helpful coding assistant for debugging and writing code" }
+2. Then, use updateConfig to set model and tools: { config: { model: "claude-3-5-sonnet-20241022", provider: "anthropic" } } and enable relevant plugins
+3. Finally, use updatePrompt to write the system prompt that references the established identity and tools
+
+User: "帮我把模型改成 Claude"
+Action: Reference the current model from injected context, then use updateConfig with { config: { model: "claude-3-5-sonnet-20241022", provider: "anthropic" } }
+
+User: "Enable web browsing for this agent"
+Action: Use togglePlugin with pluginId "lobe-web-browsing" and enabled: true
+
+User: "What's my current configuration?" / "告诉我现在的配置"
+Action: Reference the \`<current_agent_context>\` and display all settings using semantic names (e.g., "开场白" instead of "openingMessage", "创意度" instead of "temperature"). Present information in a clear, organized manner.
+
+User: "What models are available?"
+Action: Use getAvailableModels to retrieve and display all available AI models grouped by provider, showing their capabilities (vision, function calling, reasoning)
+
+User: "I want to use a model with vision capabilities"
+Action: Use getAvailableModels to find models with vision capability, then recommend suitable options and use updateConfig to change if user confirms
+
+User: "Show me the current prompt"
+Action: Reference the systemRole from the injected \`<current_agent_context>\` and display it
+
+User: "Change the prompt to make the agent act as a coding assistant"
+Action: Reference the current systemRole from context, then use updatePrompt with a new prompt like "You are a helpful coding assistant. Help users write, debug, and explain code in any programming language."
+
+User: "帮我修改一下提示词,让它更友好一些"
+Action: Reference the current systemRole from context, then use updatePrompt to modify it with a friendlier tone
+
+User: "I need a tool for web searching"
+Action: Use searchMarketTools with query "web search" to find relevant tools in the marketplace. Display the results and let the user install directly from the list.
+
+User: "帮我找一些开发相关的插件"
+Action: Use searchMarketTools with category "developer" to browse developer tools. Show the results with install buttons for the user to choose.
+
+User: "What tools are available in the marketplace?"
+Action: Use searchMarketTools without query to browse all available tools. Display the list with descriptions and install options.
+
+User: "帮我找一下有什么插件可以用"
+Action: Reference the \`<official_tools>\` from the injected context to show available built-in tools and LobeHub integrations. This allows the user to enable tools directly or connect to services like Gmail, Google Calendar, etc.
+
+User: "I want to connect my Gmail"
+Action: Check the \`<official_tools>\` in the context for Gmail LobeHub integration. If found, use installPlugin with source "official" to connect it.
+
+User: "帮我安装 GitHub 插件"
+Action: Check the \`<official_tools>\` in the context for GitHub integration. If found, use installPlugin with source "official" to install it.
+
+User: "What official integrations are available?"
+Action: Reference the \`<official_tools>\` from the injected context to list all available LobeHub integrations like Gmail, Google Calendar, Notion, Slack, GitHub, etc.
+
+User: "帮我设置开场白" / "Set an opening message for this agent"
+Action: Use updateConfig with { config: { openingMessage: "Hello! I'm your AI assistant. How can I help you today?" } }
+
+User: "帮我配置开场问题" / "Set up some opening questions about coding"
+Action: Use updateConfig with { config: { openingQuestions: ["How can I help you with your code today?", "What programming language are you working with?", "Do you need help debugging or writing new code?"] } }
+
+User: "帮我设置 temperature 为 0.7" / "Set temperature to 0.7"
+Action: Use updateConfig with { config: { params: { temperature: 0.7 } } }
+
+User: "我想调整对话配置" / "I want to configure chat settings"
+Action: Explain the available chatConfig options and help them configure as needed.
+</examples>
+
+<response_format>
+- When showing configuration, format it in a clear, readable way using markdown
+- Focus on core settings; only include advanced settings when explicitly requested
+- When making changes, clearly state what was changed (before → after)
+- Use bullet points for listing multiple items
+- Keep responses concise but informative
+</response_format>`;
diff --git a/packages/builtin-tool-agent-builder/src/types.ts b/packages/builtin-tool-agent-builder/src/types.ts
new file mode 100644
index 00000000000..493eaefaf14
--- /dev/null
+++ b/packages/builtin-tool-agent-builder/src/types.ts
@@ -0,0 +1,214 @@
+import type { LobeAgentConfig, MetaData } from '@lobechat/types';
+import type { PartialDeep } from 'type-fest';
+
+/**
+ * Agent Builder Tool Identifier
+ */
+export const AgentBuilderIdentifier = 'lobe-agent-builder';
+
+/**
+ * Agent Builder API Names
+ */
+export const AgentBuilderApiName = {
+ // Read operations
+ // Note: getAgentConfig, getAgentMeta, getPrompt, getAvailableTools, searchOfficialTools are removed
+ // because the current agent context is now automatically injected
+ getAvailableModels: 'getAvailableModels',
+ installPlugin: 'installPlugin',
+ searchMarketTools: 'searchMarketTools',
+ // Write operations
+ // Note: setModel, setOpeningMessage, setOpeningQuestions, updateChatConfig, updateAgentMeta, togglePlugin are removed
+ // and consolidated into updateAgentConfig
+ updateAgentConfig: 'updateConfig',
+ updatePrompt: 'updatePrompt',
+} as const;
+
+export type AgentBuilderApiNameType =
+ (typeof AgentBuilderApiName)[keyof typeof AgentBuilderApiName];
+
+// ============== Parameter Types ==============
+
+export interface UpdateAgentConfigParams {
+ /**
+ * Partial agent configuration to update
+ */
+ config?: PartialDeep<LobeAgentConfig>;
+ /**
+ * Partial metadata to update
+ */
+ meta?: Partial<MetaData>;
+ /**
+ * Plugin toggle operation - will be merged into config.plugins
+ */
+ togglePlugin?: {
+ /**
+ * Whether to enable the plugin. If not provided, toggles current state.
+ */
+ enabled?: boolean;
+ /**
+ * The plugin identifier to toggle
+ */
+ pluginId: string;
+ };
+}
+
+export interface GetAvailableModelsParams {
+ /**
+ * Optional: filter by provider id
+ */
+ providerId?: string;
+}
+
+export interface UpdatePromptParams {
+ /**
+ * The new system prompt content (markdown format)
+ */
+ prompt: string;
+ /**
+ * Whether to use streaming mode for typewriter effect
+ */
+ streaming?: boolean;
+}
+
+// ============== State Types (for Render components) ==============
+
+export interface UpdateConfigState {
+ config?: {
+ newValues: Record<string, unknown>;
+ previousValues: Record<string, unknown>;
+ updatedFields: string[];
+ };
+ meta?: {
+ newValues: Partial<MetaData>;
+ previousValues: Partial<MetaData>;
+ updatedFields: string[];
+ };
+ success: boolean;
+ togglePlugin?: {
+ enabled: boolean;
+ pluginId: string;
+ };
+}
+
+export interface AvailableModel {
+ abilities?: {
+ files?: boolean;
+ functionCall?: boolean;
+ reasoning?: boolean;
+ vision?: boolean;
+ };
+ description?: string;
+ id: string;
+ name: string;
+}
+
+export interface AvailableProvider {
+ id: string;
+ models: AvailableModel[];
+ name: string;
+}
+
+export interface GetAvailableModelsState {
+ providers: AvailableProvider[];
+}
+
+export interface UpdatePromptState {
+ newPrompt: string;
+ previousPrompt?: string;
+ success: boolean;
+}
+
+// ============== SearchMarketTools Types ==============
+
+export interface SearchMarketToolsParams {
+ /**
+ * Optional: filter by category (e.g., "developer", "productivity", "web-search")
+ */
+ category?: string;
+ /**
+ * Optional: number of results to return (default: 10, max: 20)
+ */
+ pageSize?: number;
+ /**
+ * Optional: search keywords to find specific tools
+ */
+ query?: string;
+}
+
+export interface MarketToolItem {
+ author?: string;
+ cloudEndPoint?: string;
+ description?: string;
+ haveCloudEndpoint?: boolean;
+ icon?: string;
+ identifier: string;
+ installed?: boolean;
+ name: string;
+ tags?: string[];
+}
+
+export interface SearchMarketToolsState {
+ query?: string;
+ tools: MarketToolItem[];
+ totalCount: number;
+}
+
+// Note: SearchOfficialTools types are removed because official tools are now
+// automatically injected into the conversation context via AgentBuilderContextInjector
+
+// ============== InstallPlugin Types ==============
+
+export interface InstallPluginParams {
+ /**
+ * Plugin identifier to install
+ */
+ identifier: string;
+ /**
+ * Plugin source type: 'market' for MCP marketplace, 'official' for builtin/klavis tools
+ */
+ source: 'market' | 'official';
+}
+
+export interface InstallPluginState {
+ /**
+ * Whether the plugin requires human approval to continue installation
+ * (e.g., Klavis tools need OAuth connection)
+ */
+ awaitingApproval?: boolean;
+ /**
+ * Error message if installation failed
+ */
+ error?: string;
+ /**
+ * Whether the plugin is installed
+ */
+ installed: boolean;
+ /**
+ * Whether the plugin is a Klavis tool that needs OAuth connection
+ */
+ isKlavis?: boolean;
+ /**
+ * Klavis OAuth URL if authorization is needed
+ */
+ oauthUrl?: string;
+ /**
+ * Plugin identifier
+ */
+ pluginId: string;
+ /**
+ * Plugin display name
+ */
+ pluginName?: string;
+ /**
+ * Klavis server name (for Klavis tools)
+ */
+ serverName?: string;
+ /**
+ * Klavis server status
+ */
+ serverStatus?: 'connected' | 'pending_auth' | 'error';
+ /**
+ * Whether the operation was successful
+ */
+ success: boolean;
+}
diff --git a/packages/builtin-tool-group-agent-builder/package.json b/packages/builtin-tool-group-agent-builder/package.json
new file mode 100644
index 00000000000..48a89c4fe6f
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "@lobechat/builtin-tool-group-agent-builder",
+ "version": "1.0.0",
+ "private": true,
+ "exports": {
+ ".": "./src/index.ts",
+ "./executionRuntime": "./src/ExecutionRuntime/index.ts"
+ },
+ "main": "./src/index.ts",
+ "dependencies": {
+ "@lobechat/builtin-tool-agent-builder": "workspace:*",
+ "@lobechat/types": "workspace:*"
+ },
+ "peerDependencies": {
+ "react": "*"
+ }
+}
diff --git a/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts b/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts
new file mode 100644
index 00000000000..7aeae1c347d
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts
@@ -0,0 +1,309 @@
+import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
+
+import { chatGroupService } from '@/services/chatGroup';
+import { getChatGroupStoreState } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+
+import type {
+ InviteAgentParams,
+ InviteAgentState,
+ RemoveAgentParams,
+ RemoveAgentState,
+ UpdateGroupConfigParams,
+ UpdateGroupConfigState,
+ UpdateGroupPromptParams,
+ UpdateGroupPromptState,
+} from '../types';
+
+/**
+ * Group Agent Builder Execution Runtime
+ * Handles the execution logic for Group Agent Builder APIs
+ * Extends AgentBuilder functionality with group-specific operations
+ */
+export class GroupAgentBuilderExecutionRuntime {
+ // ==================== Group-specific Operations ====================
+
+ /**
+ * Invite an agent to the group
+ */
+ async inviteAgent(groupId: string, args: InviteAgentParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const state = getChatGroupStoreState();
+ const group = agentGroupSelectors.getGroupById(groupId)(state);
+
+ if (!group) {
+ return {
+ content: 'Group not found',
+ error: 'Group not found',
+ success: false,
+ };
+ }
+
+ // Check if agent is already in the group
+ const existingAgents = group.agents || [];
+ const isAlreadyInGroup = existingAgents.some((a) => a.id === args.agentId);
+
+ if (isAlreadyInGroup) {
+ return {
+ content: `Agent ${args.agentId} is already in the group`,
+ state: {
+ agentId: args.agentId,
+ success: false,
+ } as InviteAgentState,
+ success: false,
+ };
+ }
+
+ // Add the agent to the group via service
+ const result = await chatGroupService.addAgentsToGroup(groupId, [args.agentId]);
+
+ // Refresh the group detail in the store
+ await state.refreshGroupDetail(groupId);
+
+ const wasAdded = result.added.length > 0;
+
+ return {
+ content: wasAdded
+ ? `Successfully invited agent ${args.agentId} to the group`
+ : `Agent ${args.agentId} was already in the group`,
+ state: {
+ agentId: args.agentId,
+ success: wasAdded,
+ } as InviteAgentState,
+ success: wasAdded,
+ };
+ } catch (error) {
+ const err = error as Error;
+ return {
+ content: `Failed to invite agent: ${err.message}`,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Remove an agent from the group
+ */
+ async removeAgent(groupId: string, args: RemoveAgentParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const state = getChatGroupStoreState();
+ const group = agentGroupSelectors.getGroupById(groupId)(state);
+
+ if (!group) {
+ return {
+ content: 'Group not found',
+ error: 'Group not found',
+ success: false,
+ };
+ }
+
+ // Check if agent is in the group
+ const existingAgents = group.agents || [];
+ const isInGroup = existingAgents.some((a) => a.id === args.agentId);
+
+ if (!isInGroup) {
+ return {
+ content: `Agent ${args.agentId} is not in the group`,
+ state: {
+ agentId: args.agentId,
+ success: false,
+ } as RemoveAgentState,
+ success: false,
+ };
+ }
+
+ // Check if this is the supervisor agent (cannot be removed)
+ if (group.supervisorAgentId === args.agentId) {
+ return {
+ content: `Cannot remove supervisor agent ${args.agentId} from the group`,
+ state: {
+ agentId: args.agentId,
+ success: false,
+ } as RemoveAgentState,
+ success: false,
+ };
+ }
+
+ // Remove the agent from the group via service
+ await chatGroupService.removeAgentsFromGroup(groupId, [args.agentId]);
+
+ // Refresh the group detail in the store
+ await state.refreshGroupDetail(groupId);
+
+ return {
+ content: `Successfully removed agent ${args.agentId} from the group`,
+ state: {
+ agentId: args.agentId,
+ success: true,
+ } as RemoveAgentState,
+ success: true,
+ };
+ } catch (error) {
+ const err = error as Error;
+ return {
+ content: `Failed to remove agent: ${err.message}`,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Update group system prompt
+ * Unlike regular AgentBuilder, this updates the group's systemPrompt in groupConfig
+ */
+ async updatePrompt(args: UpdateGroupPromptParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const state = getChatGroupStoreState();
+ const group = agentGroupSelectors.currentGroup(state);
+
+ if (!group) {
+ return {
+ content: 'No active group found',
+ error: 'No active group found',
+ success: false,
+ };
+ }
+
+ const previousPrompt = group.config?.systemPrompt;
+
+ if (args.streaming) {
+ // Use streaming mode for typewriter effect
+ await this.streamUpdatePrompt(args.prompt);
+ } else {
+ // Update the system prompt directly
+ await state.updateGroupConfig({ systemPrompt: args.prompt });
+ }
+
+ const content = args.prompt
+ ? `Successfully updated group system prompt (${args.prompt.length} characters)`
+ : 'Successfully cleared group system prompt';
+
+ return {
+ content,
+ state: {
+ newPrompt: args.prompt,
+ previousPrompt,
+ success: true,
+ } as UpdateGroupPromptState,
+ success: true,
+ };
+ } catch (error) {
+ const err = error as Error;
+ return {
+ content: `Failed to update group prompt: ${err.message}`,
+ error,
+ state: {
+ newPrompt: args.prompt,
+ success: false,
+ } as UpdateGroupPromptState,
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Update group configuration (openingMessage, openingQuestions)
+ */
+ async updateGroupConfig(args: UpdateGroupConfigParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const state = getChatGroupStoreState();
+ const group = agentGroupSelectors.currentGroup(state);
+
+ if (!group) {
+ return {
+ content: 'No active group found',
+ error: 'No active group found',
+ success: false,
+ };
+ }
+
+ const { config } = args;
+
+ if (!config) {
+ return {
+ content: 'No configuration provided',
+ error: 'No configuration provided',
+ success: false,
+ };
+ }
+
+ // Build the config update object
+ const configUpdate: { openingMessage?: string; openingQuestions?: string[] } = {};
+
+ if (config.openingMessage !== undefined) {
+ configUpdate.openingMessage = config.openingMessage;
+ }
+
+ if (config.openingQuestions !== undefined) {
+ configUpdate.openingQuestions = config.openingQuestions;
+ }
+
+ // Update the group config
+ await state.updateGroupConfig(configUpdate);
+
+ const updatedFields: string[] = [];
+ if (config.openingMessage !== undefined) {
+ updatedFields.push(
+ config.openingMessage
+ ? `openingMessage (${config.openingMessage.length} chars)`
+ : 'openingMessage (cleared)',
+ );
+ }
+ if (config.openingQuestions !== undefined) {
+ updatedFields.push(
+ config.openingQuestions.length > 0
+ ? `openingQuestions (${config.openingQuestions.length} questions)`
+ : 'openingQuestions (cleared)',
+ );
+ }
+
+ const content = `Successfully updated group configuration: ${updatedFields.join(', ')}`;
+
+ return {
+ content,
+ state: {
+ success: true,
+ updatedConfig: configUpdate,
+ } as UpdateGroupConfigState,
+ success: true,
+ };
+ } catch (error) {
+ const err = error as Error;
+ return {
+ content: `Failed to update group configuration: ${err.message}`,
+ error,
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Stream update prompt with typewriter effect for group
+ */
+ private async streamUpdatePrompt(prompt: string): Promise<void> {
+ const state = getChatGroupStoreState();
+
+ // Start streaming
+ state.startStreamingSystemPrompt();
+
+ // Simulate streaming by chunking the content
+ const chunkSize = 5; // Characters per chunk
+ const delay = 10; // Milliseconds between chunks
+
+ for (let i = 0; i < prompt.length; i += chunkSize) {
+ const chunk = prompt.slice(i, i + chunkSize);
+ getChatGroupStoreState().appendStreamingSystemPrompt(chunk);
+
+ // Small delay for typewriter effect
+ if (i + chunkSize < prompt.length) {
+ // eslint-disable-next-line no-promise-executor-return
+ await new Promise((resolve) => setTimeout(resolve, delay));
+ }
+ }
+
+ // Finish streaming - EditorCanvas will handle save when streaming ends
+ await getChatGroupStoreState().finishStreamingSystemPrompt();
+ }
+}
diff --git a/packages/builtin-tool-group-agent-builder/src/index.ts b/packages/builtin-tool-group-agent-builder/src/index.ts
new file mode 100644
index 00000000000..8ded2146b67
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/index.ts
@@ -0,0 +1,16 @@
+export { GroupAgentBuilderManifest } from './manifest';
+export { systemPrompt } from './systemRole';
+export {
+ GroupAgentBuilderApiName,
+ type GroupAgentBuilderApiNameType,
+ GroupAgentBuilderIdentifier,
+ type InviteAgentParams,
+ type InviteAgentState,
+ type RemoveAgentParams,
+ type RemoveAgentState,
+ type UpdateGroupConfigParams,
+ type UpdateGroupConfigState,
+ type UpdateGroupMetaParams,
+ type UpdateGroupPromptParams,
+ type UpdateGroupPromptState,
+} from './types';
diff --git a/packages/builtin-tool-group-agent-builder/src/manifest.ts b/packages/builtin-tool-group-agent-builder/src/manifest.ts
new file mode 100644
index 00000000000..05bca5c9373
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/manifest.ts
@@ -0,0 +1,218 @@
+import type { BuiltinToolManifest } from '@lobechat/types';
+
+import { systemPrompt } from './systemRole';
+import { GroupAgentBuilderApiName, GroupAgentBuilderIdentifier } from './types';
+
+export const GroupAgentBuilderManifest: BuiltinToolManifest = {
+ api: [
+ // ==================== Group Member Management ====================
+ {
+ description:
+ 'Invite an existing agent to join the group. The agent will become a member and participate in group conversations.',
+ name: GroupAgentBuilderApiName.inviteAgent,
+ parameters: {
+ properties: {
+ agentId: {
+ description: 'The agent identifier to invite to the group',
+ type: 'string',
+ },
+ },
+ required: ['agentId'],
+ type: 'object',
+ },
+ },
+ {
+ description: 'Remove an agent from the group. Note: The supervisor agent cannot be removed.',
+ name: GroupAgentBuilderApiName.removeAgent,
+ parameters: {
+ properties: {
+ agentId: {
+ description: 'The agent identifier to remove from the group',
+ type: 'string',
+ },
+ },
+ required: ['agentId'],
+ type: 'object',
+ },
+ },
+
+ // ==================== Read Operations (from AgentBuilder) ====================
+ {
+ description:
+ 'Get all available AI models and providers that can be used for the supervisor agent. Returns a list of providers with their supported models and capabilities.',
+ name: GroupAgentBuilderApiName.getAvailableModels,
+ parameters: {
+ properties: {
+ providerId: {
+ description:
+ 'Optional: filter models by a specific provider id (e.g., "openai", "anthropic", "google")',
+ type: 'string',
+ },
+ },
+ required: [],
+ type: 'object',
+ },
+ },
+ {
+ description: 'Search for tools (MCP plugins) in the marketplace for the supervisor agent.',
+ name: GroupAgentBuilderApiName.searchMarketTools,
+ parameters: {
+ properties: {
+ category: {
+ description:
+ 'Optional: filter by category. Available categories: developer, productivity, web-search, tools, media-generate, etc.',
+ type: 'string',
+ },
+ pageSize: {
+ description: 'Optional: number of results to return (default: 10, max: 20).',
+ type: 'number',
+ },
+ query: {
+ description:
+ 'Optional: search keywords to find specific tools. Leave empty to browse all available tools.',
+ type: 'string',
+ },
+ },
+ required: [],
+ type: 'object',
+ },
+ },
+
+ // ==================== Write Operations ====================
+ {
+ description:
+ 'Install a plugin for the supervisor agent. This tool ALWAYS REQUIRES user approval before installation.',
+ humanIntervention: 'always',
+ name: GroupAgentBuilderApiName.installPlugin,
+ parameters: {
+ properties: {
+ identifier: {
+ description:
+ 'The plugin identifier to install (e.g., "mcp-tavily-search", "google-calendar")',
+ type: 'string',
+ },
+ source: {
+ description:
+ 'Plugin source type: "market" for MCP marketplace plugins, "official" for builtin/Klavis tools',
+ enum: ['market', 'official'],
+ type: 'string',
+ },
+ },
+ required: ['identifier', 'source'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Update supervisor agent configuration (model, provider, plugins, etc.). Only include fields you want to update.',
+ name: GroupAgentBuilderApiName.updateAgentConfig,
+ parameters: {
+ properties: {
+ config: {
+ description:
+ 'Partial agent configuration object. Only include fields you want to update.',
+ properties: {
+ chatConfig: {
+ description:
+ 'Chat configuration settings (historyCount, enableHistoryCount, enableAutoCreateTopic, etc.)',
+ type: 'object',
+ },
+ model: {
+ description:
+ 'The AI model identifier (e.g., "gpt-4o", "claude-sonnet-4-5-20250929")',
+ type: 'string',
+ },
+ params: {
+ description: 'Model parameters like temperature (0-2), top_p (0-1), etc.',
+ type: 'object',
+ },
+ plugins: {
+ description: 'Array of enabled plugin identifiers.',
+ items: { type: 'string' },
+ type: 'array',
+ },
+ provider: {
+ description: 'The AI provider identifier (e.g., "openai", "anthropic", "google")',
+ type: 'string',
+ },
+ },
+ type: 'object',
+ },
+ togglePlugin: {
+ description: 'Toggle a specific plugin on/off for the supervisor agent.',
+ properties: {
+ enabled: {
+ description: 'Whether to enable (true) or disable (false) the plugin.',
+ type: 'boolean',
+ },
+ pluginId: {
+ description: 'The identifier of the plugin to toggle',
+ type: 'string',
+ },
+ },
+ required: ['pluginId'],
+ type: 'object',
+ },
+ },
+ required: [],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ "Update the group's system prompt. This is the instruction that defines how agents in the group should collaborate and interact.",
+ name: GroupAgentBuilderApiName.updatePrompt,
+ parameters: {
+ properties: {
+ prompt: {
+ description: 'The new group system prompt content. Supports markdown formatting.',
+ type: 'string',
+ },
+ streaming: {
+ description:
+ 'Whether to use streaming mode for typewriter effect in the editor. Defaults to true.',
+ type: 'boolean',
+ },
+ },
+ required: ['prompt'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ "Update the group's configuration including opening message and opening questions. Use this to set the welcome experience when users start a new conversation with the group.",
+ name: GroupAgentBuilderApiName.updateGroupConfig,
+ parameters: {
+ properties: {
+ config: {
+ description:
+ 'Partial group configuration object. Only include fields you want to update.',
+ properties: {
+ openingMessage: {
+ description:
+ 'Opening message shown when starting a new conversation with the group. Set to empty string to remove.',
+ type: 'string',
+ },
+ openingQuestions: {
+ description:
+ 'Array of suggested opening questions to help users get started. Set to empty array to remove all.',
+ items: { type: 'string' },
+ type: 'array',
+ },
+ },
+ type: 'object',
+ },
+ },
+ required: ['config'],
+ type: 'object',
+ },
+ },
+ ],
+ identifier: GroupAgentBuilderIdentifier,
+ meta: {
+ avatar: '👥',
+ title: 'Group Agent Builder',
+ },
+ systemRole: systemPrompt,
+ type: 'builtin',
+};
diff --git a/packages/builtin-tool-group-agent-builder/src/systemRole.ts b/packages/builtin-tool-group-agent-builder/src/systemRole.ts
new file mode 100644
index 00000000000..27d428358d1
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/systemRole.ts
@@ -0,0 +1,132 @@
+/**
+ * System role for Group Agent Builder tool
+ *
+ * This provides guidance on how to effectively use the group agent builder tools
+ * for configuring group chats and managing group members.
+ */
+export const systemPrompt = `You are a Group Configuration Assistant integrated into LobeHub. Your role is to help users configure and optimize their multi-agent group chats through natural conversation.
+
+<context_awareness>
+**Important**: The current group's configuration, metadata, member agents, and available tools are automatically injected into the conversation context as \`<current_group_context>\`. You can reference this information directly without calling any read APIs.
+
+The injected context includes:
+- **group_meta**: title, description
+- **group_config**: systemPrompt (group-level instruction), orchestratorModel, orchestratorProvider, responseOrder, responseSpeed
+- **group_members**: List of agents in the group with their names, avatars, and roles (including the supervisor agent)
+- **supervisor_agent**: The supervisor agent's configuration (model, provider, plugins)
+- **official_tools**: List of available official tools including built-in tools and Klavis integrations
+
+You should use this context to understand the current state of the group and its members before making any modifications.
+</context_awareness>
+
+<capabilities>
+You have access to tools that can modify group configurations:
+
+**Group Member Management:**
+- **inviteAgent**: Invite an existing agent to join the group by their agent ID
+- **removeAgent**: Remove an agent from the group (cannot remove the supervisor agent)
+
+**Read Operations:**
+- **getAvailableModels**: Get all available AI models and providers that can be used for the supervisor agent
+- **searchMarketTools**: Search for tools (MCP plugins) in the marketplace for the supervisor agent
+
+**Write Operations (for Group):**
+- **updatePrompt**: Update the group's system prompt (the instruction that guides how agents collaborate)
+- **updateGroupConfig**: Update group configuration including opening message and opening questions
+
+**Write Operations (for Supervisor Agent):**
+- **updateConfig**: Update supervisor agent configuration (model, provider, plugins, etc.)
+- **togglePlugin**: Enable or disable a specific plugin for the supervisor agent
+- **installPlugin**: Install and enable a plugin for the supervisor agent
+</capabilities>
+
+<workflow>
+1. **Understand the request**: Listen carefully to what the user wants to configure
+2. **Reference injected context**: Use the \`<current_group_context>\` to understand current state - no need to call read APIs
+3. **Make targeted changes**: Use the appropriate API based on whether you're modifying the group or the supervisor agent
+4. **Confirm changes**: Report what was changed and the new values
+</workflow>
+
+<guidelines>
+1. **Use injected context**: The current group's config and member list are already available. Reference them directly instead of calling read APIs.
+2. **Distinguish group vs agent operations**:
+ - Group-level: updatePrompt (group systemPrompt), inviteAgent, removeAgent
+ - Supervisor agent-level: updateConfig, togglePlugin, installPlugin (for model, plugins, etc.)
+3. **Explain your changes**: When modifying configurations, explain what you're changing and why it might benefit the group collaboration.
+4. **Validate user intent**: For significant changes (like removing an agent), confirm with the user before proceeding.
+5. **Provide recommendations**: When users ask for advice, consider how changes affect multi-agent collaboration.
+6. **Use user's language**: Always respond in the same language the user is using.
+7. **Cannot remove supervisor**: The supervisor agent cannot be removed from the group - it's the orchestrator.
+</guidelines>
+
+<configuration_knowledge>
+**Group Configuration:**
+- systemPrompt: The group-level instruction that defines how agents should collaborate and interact
+- orchestratorModel: The model used for orchestrating multi-agent conversations
+- orchestratorProvider: The provider for the orchestrator model
+- responseOrder: How agents respond ("sequential" or "natural")
+- responseSpeed: The pace of responses ("slow", "medium", "fast")
+- openingMessage: The welcome message shown when starting a new conversation with the group
+- openingQuestions: Suggested questions to help users get started with the group conversation
+
+**Supervisor Agent Configuration:**
+- model: The AI model for the supervisor agent
+- provider: The AI provider
+- plugins: Tools enabled for the supervisor agent
+- The supervisor orchestrates the conversation and coordinates other agents
+
+**Group Members:**
+- Each group has one supervisor agent and zero or more member agents
+- Member agents can be invited or removed
+- The supervisor agent cannot be removed (it's essential for group coordination)
+
+**System Prompt vs Agent Prompt:**
+- Group systemPrompt: Defines collaboration rules for the entire group
+- Agent systemRole: Individual agent's personality and expertise (not modified here)
+</configuration_knowledge>
+
+<examples>
+User: "帮我邀请一个 Agent 到群组"
+Action: Ask which agent they want to invite (need the agent ID), then use inviteAgent
+
+User: "Remove the coding assistant from the group"
+Action: Check the group members in context, find the agent ID for "coding assistant", then use removeAgent
+
+User: "What agents are in this group?"
+Action: Reference the \`<group_members>\` from the injected context and display the list
+
+User: "Change the group's system prompt to encourage more collaboration"
+Action: Reference the current systemPrompt from context, then use updatePrompt to update it
+
+User: "帮我把主持人的模型改成 Claude"
+Action: Use updateConfig with { config: { model: "claude-sonnet-4-5-20250929", provider: "anthropic" } } for the supervisor agent
+
+User: "Enable web browsing for the supervisor"
+Action: Use togglePlugin with pluginId "lobe-web-browsing" and enabled: true
+
+User: "What can the supervisor agent do?"
+Action: Reference the \`<supervisor_agent>\` config from the context, including model, plugins, etc.
+
+User: "Set the response order to sequential"
+Action: This is a group-level config, use updatePrompt or mention this needs to be changed in group settings
+
+User: "帮我添加一些新的工具给这个群组"
+Action: Use searchMarketTools to find tools, then use installPlugin for the supervisor agent
+
+User: "Set a welcome message for this group"
+Action: Use updateGroupConfig with { config: { openingMessage: "Welcome to the team! We're here to help you with your project." } }
+
+User: "帮我设置一些开场问题"
+Action: Use updateGroupConfig with { config: { openingQuestions: ["What project are you working on?", "How can we help you today?", "Do you have any specific questions?"] } }
+
+User: "Remove the opening message"
+Action: Use updateGroupConfig with { config: { openingMessage: "" } }
+</examples>
+
+<response_format>
+- When showing configuration, format it in a clear, readable way using markdown
+- When making changes, clearly state what was changed (before → after)
+- Distinguish between group-level and agent-level changes
+- Use bullet points for listing multiple items
+- Keep responses concise but informative
+</response_format>`;
diff --git a/packages/builtin-tool-group-agent-builder/src/types.ts b/packages/builtin-tool-group-agent-builder/src/types.ts
new file mode 100644
index 00000000000..36a9afc112f
--- /dev/null
+++ b/packages/builtin-tool-group-agent-builder/src/types.ts
@@ -0,0 +1,135 @@
+import type { MetaData } from '@lobechat/types';
+
+/**
+ * Group Agent Builder Tool Identifier
+ */
+export const GroupAgentBuilderIdentifier = 'lobe-group-agent-builder';
+
+/**
+ * Group Agent Builder API Names
+ */
+export const GroupAgentBuilderApiName = {
+ // Read operations (inherited from AgentBuilder)
+ getAvailableModels: 'getAvailableModels',
+ // Write operations (inherited from AgentBuilder)
+ installPlugin: 'installPlugin',
+
+ // Group-specific operations
+ inviteAgent: 'inviteAgent',
+
+ removeAgent: 'removeAgent',
+
+ searchMarketTools: 'searchMarketTools',
+
+ updateAgentConfig: 'updateConfig',
+ // Group config operations
+ updateGroupConfig: 'updateGroupConfig',
+ updatePrompt: 'updatePrompt',
+} as const;
+
+export type GroupAgentBuilderApiNameType =
+ (typeof GroupAgentBuilderApiName)[keyof typeof GroupAgentBuilderApiName];
+
+// ============== Group-specific Parameter Types ==============
+
+export interface InviteAgentParams {
+ /**
+ * Agent identifier to invite to the group
+ */
+ agentId: string;
+}
+
+export interface RemoveAgentParams {
+ /**
+ * Agent identifier to remove from the group
+ */
+ agentId: string;
+}
+
+export interface UpdateGroupPromptParams {
+ /**
+ * The new system prompt content for the group (markdown format)
+ */
+ prompt: string;
+ /**
+ * Whether to use streaming mode for typewriter effect
+ */
+ streaming?: boolean;
+}
+
+export interface UpdateGroupMetaParams {
+ /**
+ * Partial metadata to update for the group
+ */
+ meta?: Partial<Pick<MetaData, 'title' | 'description' | 'avatar' | 'backgroundColor' | 'tags'>>;
+}
+
+// ============== State Types (for Render components) ==============
+
+export interface InviteAgentState {
+ /**
+ * Agent identifier that was invited
+ */
+ agentId: string;
+ /**
+ * Agent display name
+ */
+ agentName?: string;
+ /**
+ * Whether the operation was successful
+ */
+ success: boolean;
+}
+
+export interface RemoveAgentState {
+ /**
+ * Agent identifier that was removed
+ */
+ agentId: string;
+ /**
+ * Agent display name
+ */
+ agentName?: string;
+ /**
+ * Whether the operation was successful
+ */
+ success: boolean;
+}
+
+export interface UpdateGroupPromptState {
+ newPrompt: string;
+ previousPrompt?: string;
+ success: boolean;
+}
+
+// ============== Group Config Types ==============
+
+export interface UpdateGroupConfigParams {
+ /**
+ * Partial group configuration to update
+ */
+ config?: {
+ /**
+ * Opening message shown when starting a new conversation with the group
+ */
+ openingMessage?: string;
+ /**
+ * Suggested opening questions to help users get started
+ */
+ openingQuestions?: string[];
+ };
+}
+
+export interface UpdateGroupConfigState {
+ /**
+ * Whether the operation was successful
+ */
+ success: boolean;
+ /**
+ * The updated configuration values
+ */
+ updatedConfig: {
+ openingMessage?: string;
+ openingQuestions?: string[];
+ };
+}