π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(agent): show agent name instead of title in searchAgent and task timeline (#21760)
Arvin Xudb47923b6cf3
diff --git a/apps/server/src/services/task/detail.ts b/apps/server/src/services/task/detail.tsindex a1c210972c7..bfd4fb92014 100644--- a/apps/server/src/services/task/detail.ts+++ b/apps/server/src/services/task/detail.ts@@ -1,14 +1,15 @@-import type {- TaskAssignmentKind,- TaskAutomationSnapshot,- TaskDetailActivity,- TaskDetailActivityAuthor,- TaskDetailData,- TaskDetailSubtask,- TaskDetailWorkspaceNode,- TaskStatus,- TaskTopicHandoff,- WorkspaceData,+import {+ agentDisplayName,+ type TaskAssignmentKind,+ type TaskAutomationSnapshot,+ type TaskDetailActivity,+ type TaskDetailActivityAuthor,+ type TaskDetailData,+ type TaskDetailSubtask,+ type TaskDetailWorkspaceNode,+ type TaskStatus,+ type TaskTopicHandoff,+ type WorkspaceData,} from '@lobechat/types';import pMap from 'p-map';@@ -555,11 +556,12 @@ export class TaskDetailService {UserModel.findByIds(this.db, [...userIds]),]);- // Both display columns are nullable, so fall back to the other one the- // query already returns rather than letting a live participant render as- // nameless β the UI reserves its nameless labels for absent identities.+ // An agent is labelled by its name, with `title` (its role) as the+ // fallback β see `agentDisplayName`. Both columns are nullable, so a live+ // participant never renders as nameless; the UI reserves its nameless+ // labels for absent identities.for (const a of agentRows) {- map.set(a.id, { avatar: a.avatar, id: a.id, name: a.title || a.name, type: 'agent' });+ map.set(a.id, { avatar: a.avatar, id: a.id, name: agentDisplayName(a), type: 'agent' });}for (const u of userRows) {map.set(u.id, { avatar: u.avatar, id: u.id, name: u.fullName || u.username, type: 'user' });diff --git a/apps/server/src/services/task/index.detailState.test.ts b/apps/server/src/services/task/index.detailState.test.tsindex e25474e49e2..7e84892cadd 100644--- a/apps/server/src/services/task/index.detailState.test.ts+++ b/apps/server/src/services/task/index.detailState.test.ts@@ -9,6 +9,7 @@ import { TaskService } from './index';*/const mocks = vi.hoisted(() => ({findByOperations: vi.fn(),+ getAgentAvatarsByIds: vi.fn(),findWithHandoff: vi.fn(),findById: vi.fn(),timeoutRunning: vi.fn(),@@ -18,7 +19,7 @@ const mocks = vi.hoisted(() => ({vi.mock('@/database/models/agent', () => ({AgentModel: vi.fn(function () {- return { getAgentAvatarsByIds: vi.fn().mockResolvedValue([]) };+ return { getAgentAvatarsByIds: mocks.getAgentAvatarsByIds };}),}));vi.mock('@/database/models/project', () => ({ ProjectModel: vi.fn() }));@@ -90,6 +91,30 @@ describe('TaskService.getTaskDetail state', () => {vi.clearAllMocks();mocks.findWithHandoff.mockResolvedValue([]);mocks.findByOperations.mockResolvedValue(new Map());+ mocks.getAgentAvatarsByIds.mockResolvedValue([]);+ });++ it('labels agent authors by name, falling back to title when the name is blank', async () => {+ mocks.findById.mockResolvedValue({+ ...baseTask,+ createdAt: new Date('2024-01-01T00:00:00Z'),+ createdByAgentId: 'agt_named',+ });+ mocks.getAgentAvatarsByIds.mockResolvedValue([+ { avatar: null, id: 'agt_named', name: 'Dario δ»»ε‘ιεη', title: 'ηΎε½100ε' },+ ]);++ const named = await service().getTaskDetail('T-1');+ expect(named?.activities?.find((a) => a.type === 'created')?.author?.name).toBe(+ 'Dario δ»»ε‘ιεη',+ );++ mocks.getAgentAvatarsByIds.mockResolvedValue([+ { avatar: null, id: 'agt_named', name: ' ', title: 'ηΎε½100ε' },+ ]);++ const untitled = await service().getTaskDetail('T-1');+ expect(untitled?.activities?.find((a) => a.type === 'created')?.author?.name).toBe('ηΎε½100ε');});it('pauses a running task whose heartbeat timed out, then re-reads it', async () => {diff --git a/packages/agent-manager-runtime/src/AgentManagerRuntime/errors.ts b/packages/agent-manager-runtime/src/AgentManagerRuntime/errors.tsnew file mode 100644index 00000000000..45592fde93a--- /dev/null+++ b/packages/agent-manager-runtime/src/AgentManagerRuntime/errors.ts@@ -0,0 +1,32 @@+import type { BuiltinToolResult } from '@lobechat/types';++export const handleError = (error: unknown, context: string): BuiltinToolResult => {+ const err = error as Error;+ return {+ content: `${context}: ${err.message}`,+ error: {+ body: error,+ message: err.message,+ type: 'RuntimeError',+ },+ success: false,+ };+};++export const handleErrorWithState = <T extends object>(+ error: unknown,+ context: string,+ state: T,+): BuiltinToolResult => {+ const err = error as Error;+ return {+ content: `${context}: ${err.message}`,+ error: {+ body: error,+ message: err.message,+ type: 'RuntimeError',+ },+ state,+ success: false,+ };+};diff --git a/packages/agent-manager-runtime/src/AgentManagerRuntime/index.installPlugin.test.ts b/packages/agent-manager-runtime/src/AgentManagerRuntime/index.installPlugin.test.tsnew file mode 100644index 00000000000..4007fbc27fd--- /dev/null+++ b/packages/agent-manager-runtime/src/AgentManagerRuntime/index.installPlugin.test.ts@@ -0,0 +1,331 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { ComposioServerStatus } from '@/store/tool/slices/composioStore/types';+import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore/types';++import type { IAgentService, IDiscoverService } from '../types';+import { AgentManagerRuntime } from './index';++/**+ * installPlugin branches: Composio, LobeHub Skill (both with OAuth windows),+ * MCP marketplace and the thrown-error path. Every store call goes through one+ * shared object per store so a test can assert what was written.+ */+const mocks = vi.hoisted(() => ({+ agentState: {+ agentMap: {} as Record<string, unknown>,+ internal_dispatchAgentMap: vi.fn(),+ optimisticUpdateAgentConfig: vi.fn(),+ },+ agentConfig: { plugins: [] as unknown[] },+ composioServers: [] as unknown[],+ installedPlugin: null as unknown,+ isPluginInstalled: false,+ lobehubServers: [] as unknown[],+ resolveConnector: vi.fn(),+ toolState: {+ checkLobehubSkillStatus: vi.fn(),+ createComposioConnection: vi.fn(),+ getLobehubSkillAuthorizeUrl: vi.fn(),+ installMCPPlugin: vi.fn(),+ refreshComposioConnectionStatus: vi.fn(),+ refreshPlugins: vi.fn(),+ },+ userId: 'user-1' as string | undefined,+}));++vi.mock('@lobechat/const', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ resolveConnectorCatalogItem: mocks.resolveConnector,+}));+vi.mock('@/store/agent', () => ({ getAgentStoreState: () => mocks.agentState }));+vi.mock('@/store/agent/selectors/selectors', () => ({+ agentSelectors: { getAgentConfigById: () => () => mocks.agentConfig },+}));+vi.mock('@/store/aiInfra', () => ({ getAiInfraStoreState: vi.fn() }));+vi.mock('@/store/tool', () => ({ getToolStoreState: () => mocks.toolState }));+vi.mock('@/store/tool/selectors', () => ({+ builtinToolSelectors: { metaList: () => [] },+ composioStoreSelectors: { getServers: () => mocks.composioServers },+ lobehubSkillStoreSelectors: { getServers: () => mocks.lobehubServers },+ pluginSelectors: {+ getInstalledPluginById: () => () => mocks.installedPlugin,+ isPluginInstalled: () => () => mocks.isPluginInstalled,+ },+}));+vi.mock('@/store/user', () => ({ getUserStoreState: () => ({}) }));+vi.mock('@/store/user/selectors', () => ({+ userProfileSelectors: { userId: () => mocks.userId },+}));++const agentService = { getAgentConfigById: vi.fn() } as unknown as IAgentService;+const runtime = () =>+ new AgentManagerRuntime({ agentService, discoverService: {} as IDiscoverService });++const composio = { appSlug: 'NOTION', label: 'Notion', serverType: 'composio' };+const lobehub = { id: 'linear', label: 'Linear' };++const install = (identifier: string, source: 'market' | 'official' = 'official') =>+ runtime().installPlugin('agent-1', { identifier, source });++/** Stub window.open with a popup that is already closed when first checked. */+const openClosedPopup = () =>+ vi.spyOn(window, 'open').mockReturnValue({ closed: true } as unknown as Window);++/** Run an install that waits on the OAuth popup, ticking past the 500ms close check. */+const installThroughPopup = async (identifier: string) => {+ const pending = install(identifier);+ await vi.advanceTimersByTimeAsync(500);+ return pending;+};++const enabledPinned = (identifier: string) =>+ expect(mocks.agentState.optimisticUpdateAgentConfig).toHaveBeenCalledWith('agent-1', {+ plugins: [{ identifier, mode: 'pinned' }],+ });++beforeEach(() => {+ vi.clearAllMocks();+ mocks.agentState.agentMap = { 'agent-1': {} };+ mocks.agentConfig.plugins = [];+ mocks.composioServers = [];+ mocks.lobehubServers = [];+ mocks.installedPlugin = null;+ mocks.isPluginInstalled = false;+ mocks.userId = 'user-1';+});++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+});++describe('installPlugin Β· Composio', () => {+ beforeEach(() => {+ mocks.resolveConnector.mockReturnValue({ serverType: composio, type: 'composio' });+ });++ it('enables an already active connection', async () => {+ mocks.composioServers = [{ identifier: 'notion', status: ComposioServerStatus.ACTIVE }];++ const result = await install('notion');++ expect(result).toMatchObject({+ content: 'Successfully enabled Composio tool: Notion',+ state: { installed: true, isComposio: true, serverStatus: 'connected' },+ success: true,+ });+ enabledPinned('notion');+ });++ it('enables a pending connection once its OAuth popup completes', async () => {+ vi.useFakeTimers();+ openClosedPopup();+ mocks.composioServers = [+ {+ identifier: 'notion',+ redirectUrl: 'https://auth',+ status: ComposioServerStatus.PENDING_AUTH,+ },+ ];+ mocks.toolState.refreshComposioConnectionStatus.mockImplementation(async () => {+ mocks.composioServers = [{ identifier: 'notion', status: ComposioServerStatus.ACTIVE }];+ });++ const result = await installThroughPopup('notion');++ expect(window.open).toHaveBeenCalledWith('https://auth', '_blank', 'width=600,height=700');+ expect(result).toMatchObject({+ content: 'Successfully connected and enabled Composio tool: Notion',+ success: true,+ });+ enabledPinned('notion');+ });++ it('reports a pending connection without a redirect URL as failed authorization', async () => {+ mocks.composioServers = [{ identifier: 'notion', status: ComposioServerStatus.PENDING_AUTH }];++ const result = await install('notion');++ expect(result).toMatchObject({+ state: { installed: false, serverStatus: 'pending_auth' },+ success: false,+ });+ expect(result.content).toContain('OAuth authorization was cancelled or failed');+ expect(mocks.agentState.optimisticUpdateAgentConfig).not.toHaveBeenCalled();+ });++ it('refuses to create a connection without a signed-in user', async () => {+ mocks.userId = undefined;++ const result = await install('notion');++ expect(result).toMatchObject({ error: { type: 'AuthRequired' }, success: false });+ expect(mocks.toolState.createComposioConnection).not.toHaveBeenCalled();+ });++ it('enables a newly created connection that is already active', async () => {+ mocks.toolState.createComposioConnection.mockResolvedValue({+ identifier: 'notion',+ status: ComposioServerStatus.ACTIVE,+ });++ const result = await install('notion');++ expect(mocks.toolState.createComposioConnection).toHaveBeenCalledWith({+ appSlug: 'NOTION',+ identifier: 'notion',+ label: 'Notion',+ });+ expect(mocks.toolState.refreshComposioConnectionStatus).toHaveBeenCalledWith('notion');+ expect(result).toMatchObject({ state: { serverStatus: 'connected' }, success: true });+ enabledPinned('notion');+ });++ it('reports a ComposioError when the connection cannot be created', async () => {+ mocks.toolState.createComposioConnection.mockResolvedValue(undefined);++ const result = await install('notion');++ expect(result).toMatchObject({+ content: 'Failed to connect Composio tool: Notion',+ error: { type: 'ComposioError' },+ success: false,+ });+ });+});++describe('installPlugin Β· LobeHub Skill', () => {+ beforeEach(() => {+ mocks.resolveConnector.mockReturnValue({ provider: lobehub, type: 'lobehub' });+ });++ it('fails without an authorize URL, passing the web callback as redirect', async () => {+ mocks.toolState.getLobehubSkillAuthorizeUrl.mockResolvedValue({});++ const result = await install('linear');++ expect(mocks.toolState.getLobehubSkillAuthorizeUrl).toHaveBeenCalledWith('linear', {+ redirectUri: `${window.location.origin}/oauth/callback/success?provider=linear`,+ });+ expect(result).toMatchObject({+ state: { installed: false, isLobehubSkill: true, serverStatus: 'not_connected' },+ success: false,+ });+ expect(result.content).toContain('no authorization URL is available');+ });++ it.each([+ {+ connected: true,+ content: 'Successfully connected and enabled LobehubSkill provider: Linear',+ success: true,+ },+ {+ connected: false,+ content:+ 'OAuth authorization was cancelled or failed for LobehubSkill provider: Linear. Please try again.',+ success: false,+ },+ ])('resolves the OAuth popup by status (connected=$connected)', async (c) => {+ vi.useFakeTimers();+ openClosedPopup();+ mocks.toolState.getLobehubSkillAuthorizeUrl.mockResolvedValue({ authorizeUrl: 'https://a' });+ mocks.toolState.checkLobehubSkillStatus.mockResolvedValue({+ status: c.connected ? LobehubSkillStatus.CONNECTED : 'not_connected',+ });++ const result = await installThroughPopup('linear');++ expect(result).toMatchObject({ content: c.content, success: c.success });+ expect(mocks.agentState.optimisticUpdateAgentConfig).toHaveBeenCalledTimes(c.connected ? 1 : 0);+ });++ it('resolves from the callback page message before the popup closes', async () => {+ vi.useFakeTimers();+ vi.spyOn(window, 'open').mockReturnValue({ closed: false } as unknown as Window);+ mocks.toolState.getLobehubSkillAuthorizeUrl.mockResolvedValue({ authorizeUrl: 'https://a' });+ mocks.toolState.checkLobehubSkillStatus.mockResolvedValue({+ status: LobehubSkillStatus.CONNECTED,+ });++ const pending = install('linear');+ await vi.advanceTimersByTimeAsync(0);+ window.dispatchEvent(+ new MessageEvent('message', {+ data: { provider: 'linear', type: 'LOBEHUB_SKILL_AUTH_SUCCESS' },+ origin: window.location.origin,+ }),+ );+ await vi.advanceTimersByTimeAsync(0);++ expect(await pending).toMatchObject({ success: true });+ });+});++describe('installPlugin Β· market', () => {+ it('enables an already installed plugin without reinstalling it', async () => {+ mocks.isPluginInstalled = true;+ mocks.installedPlugin = { manifest: { meta: { title: 'Weather' } } };++ const result = await install('weather', 'market');++ expect(result).toMatchObject({+ content: 'Plugin "Weather" is already installed. Enabled for current agent.',+ state: { pluginName: 'Weather' },+ success: true,+ });+ expect(mocks.toolState.installMCPPlugin).not.toHaveBeenCalled();+ enabledPinned('weather');+ });++ it('reports a cancelled install without enabling it', async () => {+ mocks.toolState.installMCPPlugin.mockResolvedValue(false);++ const result = await install('weather', 'market');++ expect(result).toMatchObject({ state: { installed: false }, success: false });+ expect(result.content).toContain('Installation was cancelled or configuration is needed');+ expect(mocks.agentState.optimisticUpdateAgentConfig).not.toHaveBeenCalled();+ });++ it('loads an agent that is not in the store before enabling the plugin', async () => {+ mocks.agentState.agentMap = {};+ mocks.isPluginInstalled = true;+ vi.mocked(agentService.getAgentConfigById).mockResolvedValue({ plugins: [] } as any);++ await install('weather', 'market');++ expect(agentService.getAgentConfigById).toHaveBeenCalledWith('agent-1');+ expect(mocks.agentState.internal_dispatchAgentMap).toHaveBeenCalledWith('agent-1', {+ plugins: [],+ });+ });++ it('turns an async install failure into a failed result instead of rejecting', async () => {+ mocks.toolState.installMCPPlugin.mockRejectedValue(new Error('network down'));++ const result = await install('weather', 'market');++ expect(result).toMatchObject({+ content: 'Failed to install plugin: network down',+ state: { error: 'network down', installed: false, pluginId: 'weather' },+ success: false,+ });+ });++ it('turns a thrown error into a failed result that keeps the plugin state', async () => {+ mocks.resolveConnector.mockImplementation(() => {+ throw new Error('boom');+ });++ const result = await install('weather');++ expect(result).toMatchObject({+ content: 'Failed to install plugin: boom',+ error: { message: 'boom', type: 'RuntimeError' },+ state: { error: 'boom', installed: false, pluginId: 'weather', success: false },+ success: false,+ });+ });+});diff --git a/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts b/packages/agent-manager-runtime/src/AgentManagerRuntime/index.test.tssimilarity index 97%rename from packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.tsrename to packages/agent-manager-runtime/src/AgentManagerRuntime/index.test.tsindex 2ec81a60643..6ad717854c8 100644--- a/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts+++ b/packages/agent-manager-runtime/src/AgentManagerRuntime/index.test.ts@@ -5,8 +5,8 @@ import { composioStoreSelectors, lobehubSkillStoreSelectors } from '@/store/toolimport { ComposioServerStatus } from '@/store/tool/slices/composioStore/types';import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore/types';-import { AgentManagerRuntime } from '../AgentManagerRuntime';import type { IAgentService, IDiscoverService } from '../types';+import { AgentManagerRuntime } from './index';/*** The `@/store/agent` mock below recreates a fresh object (with fresh@@ -334,6 +334,29 @@ describe('AgentManagerRuntime', () => {});});+ it('should surface the agent name next to its title', async () => {+ vi.mocked(mockAgentService.queryAgents).mockResolvedValue([+ {+ id: 'agt_dario',+ name: 'Dario δ»»ε‘ιεη',+ title: 'ηΎε½100ε',+ description: null,+ avatar: null,+ backgroundColor: null,+ },+ ] as any);+ vi.mocked(mockAgentService.countAgents).mockResolvedValue(1);++ const result = await runtime.searchAgents({ keyword: 'dario', source: 'user' });++ expect(result.content).toContain(+ '<agent id="agt_dario" name="Dario δ»»ε‘ιεη" title="ηΎε½100ε" origin="workspace" />',+ );+ expect(result.state).toMatchObject({+ agents: [expect.objectContaining({ name: 'Dario δ»»ε‘ιεη', title: 'ηΎε½100ε' })],+ });+ });+it('should surface heteroType for heterogeneous agents in state and content', async () => {vi.mocked(mockAgentService.queryAgents).mockResolvedValue([{diff --git a/packages/agent-manager-runtime/src/AgentManagerRuntime.ts b/packages/agent-manager-runtime/src/AgentManagerRuntime/index.tssimilarity index 54%rename from packages/agent-manager-runtime/src/AgentManagerRuntime.tsrename to packages/agent-manager-runtime/src/AgentManagerRuntime/index.tsindex 927bfb79b50..1eec737a33e 100644--- a/packages/agent-manager-runtime/src/AgentManagerRuntime.ts+++ b/packages/agent-manager-runtime/src/AgentManagerRuntime/index.ts@@ -14,8 +14,6 @@* Services must be injected via constructor for runtime-agnostic usage* (e.g., server-side services vs client-side services).*/-import type { ComposioAppType, LobehubSkillProviderType } from '@lobechat/const';-import { resolveConnectorCatalogItem } from '@lobechat/const';import {marketToolsResultsPrompt,modelsResultsPrompt,@@ -25,7 +23,6 @@ import {type BuiltinToolResult,type DiscoverAssistantDetail,getPluginMode,- type HeterogeneousProviderConfig,parsePluginEntry,upsertPluginMode,} from '@lobechat/types';@@ -34,20 +31,9 @@ import { getAgentStoreState } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors/selectors';import { getAiInfraStoreState } from '@/store/aiInfra';import { getToolStoreState } from '@/store/tool';-import {- builtinToolSelectors,- composioStoreSelectors,- lobehubSkillStoreSelectors,- pluginSelectors,-} from '@/store/tool/selectors';-import type { ComposioServer } from '@/store/tool/slices/composioStore/types';-import { ComposioServerStatus } from '@/store/tool/slices/composioStore/types';-import type { LobehubSkillServer } from '@/store/tool/slices/lobehubSkillStore/types';-import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore/types';-import { getUserStoreState } from '@/store/user';-import { userProfileSelectors } from '@/store/user/selectors';--import { describeHeterogeneousAgent, renderHeteroRuntimeLines } from './heteroAgentDescriptor';+import { pluginSelectors } from '@/store/tool/selectors';++import { describeHeterogeneousAgent, renderHeteroRuntimeLines } from '../heteroAgentDescriptor';import type {AgentManagerRuntimeServices,AgentSearchItem,@@ -61,7 +47,6 @@ import type {IAgentService,IDiscoverService,InstallPluginParams,- InstallPluginState,MarketToolItem,SearchAgentParams,SearchAgentState,@@ -71,7 +56,9 @@ import type {UpdateAgentConfigState,UpdatePromptParams,UpdatePromptState,-} from './types';+} from '../types';+import { handleError, handleErrorWithState } from './errors';+import { ensureAgentLoaded, installPlugin } from './installPlugin';/** Max results per searchAgents call (mirrored in the tool manifests: "max: 20") */const MAX_SEARCH_AGENT_LIMIT = 20;@@ -140,7 +127,7 @@ export class AgentManagerRuntime {success: true,};} catch (error) {- return this.handleError(error, 'Failed to create agent');+ return handleError(error, 'Failed to create agent');}}@@ -153,7 +140,7 @@ export class AgentManagerRuntime {): Promise<BuiltinToolResult> {try {// Ensure agent is loaded in store before reading its config- await this.ensureAgentLoaded(agentId);+ await ensureAgentLoaded(this.agentService, agentId);const state = getAgentStoreState();const agentStore = getAgentStoreState();@@ -282,7 +269,7 @@ export class AgentManagerRuntime {success: true,};} catch (error) {- return this.handleError(error, 'Failed to update agent');+ return handleError(error, 'Failed to update agent');}}@@ -302,7 +289,7 @@ export class AgentManagerRuntime {success: true,};} catch (error) {- return this.handleError(error, 'Failed to delete agent');+ return handleError(error, 'Failed to delete agent');}}@@ -390,7 +377,7 @@ export class AgentManagerRuntime {success: true,};} catch (error) {- return this.handleError(error, 'Failed to get agent detail');+ return handleError(error, 'Failed to get agent detail');}}@@ -418,7 +405,7 @@ export class AgentManagerRuntime {success: true,};} catch (error) {- return this.handleError(error, 'Failed to duplicate agent');+ return handleError(error, 'Failed to duplicate agent');}}@@ -453,24 +440,16 @@ export class AgentManagerRuntime {userTotal = total;agents.push(- ...userAgents.map(- (agent: {- avatar?: string | null;- backgroundColor?: string | null;- description?: string | null;- heteroType?: HeterogeneousProviderConfig['type'];- id: string;- title?: string | null;- }) => ({- avatar: agent.avatar ?? undefined,- backgroundColor: agent.backgroundColor ?? undefined,- description: agent.description ?? undefined,- heteroType: agent.heteroType,- id: agent.id,- isMarket: false,- title: agent.title ?? undefined,- }),- ),+ ...userAgents.map((agent) => ({+ avatar: agent.avatar ?? undefined,+ backgroundColor: agent.backgroundColor ?? undefined,+ description: agent.description ?? undefined,+ heteroType: agent.heteroType,+ id: agent.id,+ isMarket: false,+ name: agent.name ?? undefined,+ title: agent.title ?? undefined,+ })),);}@@ -526,7 +505,7 @@ export class AgentManagerRuntime {success: true,};} catch (error) {- return this.handleError(error, 'Failed to search agents');+ return handleError(error, 'Failed to search agents');}}@@ -573,7 +552,7 @@ export class AgentManagerRuntime {success: true,};} catch (error) {- return this.handleError(error, 'Failed to get available models');+ return handleError(error, 'Failed to get available models');}}@@ -585,7 +564,7 @@ export class AgentManagerRuntime {async updatePrompt(agentId: string, params: UpdatePromptParams): Promise<BuiltinToolResult> {try {const previousPrompt = await this.enqueuePromptUpdate(agentId, async () => {- await this.ensureAgentLoaded(agentId);+ await ensureAgentLoaded(this.agentService, agentId);const state = getAgentStoreState();const previousConfig = agentSelectors.getAgentConfigById(agentId)(state);@@ -615,7 +594,7 @@ export class AgentManagerRuntime {success: true,};} catch (error) {- return this.handleErrorWithState(error, 'Failed to update prompt', {+ return handleErrorWithState(error, 'Failed to update prompt', {newPrompt: params.prompt,success: false,} as UpdatePromptState);@@ -815,7 +794,7 @@ export class AgentManagerRuntime {success: true,};} catch (error) {- return this.handleError(error, 'Failed to search market tools');+ return handleError(error, 'Failed to search market tools');}}@@ -823,576 +802,6 @@ export class AgentManagerRuntime {* Install a plugin*/async installPlugin(agentId: string, params: InstallPluginParams): Promise<BuiltinToolResult> {- const { identifier, source } = params;-- try {- const toolState = getToolStoreState();-- if (source === 'official') {- const isComposioEnabled =- typeof window !== 'undefined' &&- window.global_serverConfigStore?.getState()?.serverConfig?.enableComposio;- const isLobehubSkillEnabled =- typeof window !== 'undefined' &&- window.global_serverConfigStore?.getState()?.serverConfig?.enableLobehubSkill;- const connector = resolveConnectorCatalogItem(identifier, {- composio: Boolean(isComposioEnabled),- lobehub: Boolean(isLobehubSkillEnabled),- });-- if (connector?.type === 'composio') {- const composioServer = composioStoreSelectors- .getServers(toolState)- .find((s) => s.identifier === identifier);- return this.handleComposioInstall(- agentId,- identifier,- connector.serverType,- composioServer,- );- }-- if (connector?.type === 'lobehub') {- const lobehubSkillServer = lobehubSkillStoreSelectors- .getServers(toolState)- .find((s) => s.identifier === identifier);- return this.handleLobehubSkillInstall(- agentId,- identifier,- connector.provider,- lobehubSkillServer,- );- }-- // Check if it's a builtin tool- const builtinTools = builtinToolSelectors.metaList(toolState);- const builtinTool = builtinTools.find((t) => t.identifier === identifier);-- if (builtinTool) {- await this.enablePluginForAgent(agentId, 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: { message: 'Tool not found', type: 'NotFound' },- state: {- installed: false,- pluginId: identifier,- success: false,- } as InstallPluginState,- success: false,- };- }-- // Source is 'market' - MCP marketplace plugin- return this.handleMarketPluginInstall(agentId, identifier);- } catch (error) {- const err = error as Error;- return this.handleErrorWithState(error, 'Failed to install plugin', {- error: err.message,- installed: false,- pluginId: identifier,- success: false,- } as InstallPluginState);- }- }-- // ==================== Private Helper Methods ====================-- /**- * Ensure the agent config is loaded into the Zustand store.- * When operating on agents that aren't currently open/active,- * their config won't be in the agentMap. This fetches and dispatches it.- */- private async ensureAgentLoaded(agentId: string): Promise<void> {- const state = getAgentStoreState();- const existing = state.agentMap[agentId];- if (existing) return;-- const config = await this.agentService.getAgentConfigById(agentId);- if (config) {- getAgentStoreState().internal_dispatchAgentMap(agentId, config);- }- }-- private async handleComposioInstall(- agentId: string,- identifier: string,- composioAppInfo: ComposioAppType,- composioServer?: ComposioServer,- ): Promise<BuiltinToolResult> {- if (composioServer) {- if (composioServer.status === ComposioServerStatus.ACTIVE) {- await this.enablePluginForAgent(agentId, identifier);- return {- content: `Successfully enabled Composio tool: ${composioAppInfo.label}`,- state: {- installed: true,- isComposio: true,- pluginId: identifier,- pluginName: composioAppInfo.label,- serverStatus: 'connected',- success: true,- } as InstallPluginState,- success: true,- };- } else if (composioServer.status === ComposioServerStatus.PENDING_AUTH) {- if (composioServer.redirectUrl) {- const authResult = await this.openOAuthWindowAndWait(- composioServer.redirectUrl,- identifier,- );- if (authResult.success) {- await this.enablePluginForAgent(agentId, identifier);- return {- content: `Successfully connected and enabled Composio tool: ${composioAppInfo.label}`,- state: {- installed: true,- isComposio: true,- pluginId: identifier,- pluginName: composioAppInfo.label,- serverStatus: 'connected',- success: true,- } as InstallPluginState,- success: true,- };- }- }- return {- content: `OAuth authorization was cancelled or failed for Composio tool: ${composioAppInfo.label}. Please try again.`,- state: {- installed: false,- isComposio: true,- pluginId: identifier,- pluginName: composioAppInfo.label,- serverStatus: 'pending_auth',- success: false,- } as InstallPluginState,- success: false,- };- }- }-- // Server doesn't exist, create it- const userId = userProfileSelectors.userId(getUserStoreState());- if (!userId) {- return {- content: `Cannot connect Composio tool: User not logged in.`,- error: { message: 'User not logged in', type: 'AuthRequired' },- state: { installed: false, pluginId: identifier, success: false } as InstallPluginState,- success: false,- };- }-- const newServer = await getToolStoreState().createComposioConnection({- appSlug: composioAppInfo.appSlug,- identifier,- label: composioAppInfo.label,- });-- if (newServer) {- // Enable the plugin only once the connection is actually usable. Enabling- // before OAuth completes would leave an enabled-but-unauthorized tool on- // the agent if the user cancels the authorization.- if (newServer.status === ComposioServerStatus.ACTIVE) {- await this.enablePluginForAgent(agentId, identifier);- await getToolStoreState().refreshComposioConnectionStatus(newServer.identifier);- return {- content: `Successfully connected and enabled Composio tool: ${composioAppInfo.label}`,- state: {- installed: true,- isComposio: true,- pluginId: identifier,- pluginName: composioAppInfo.label,- serverStatus: 'connected',- success: true,- } as InstallPluginState,- success: true,- };- } else if (newServer.redirectUrl) {- const authResult = await this.openOAuthWindowAndWait(- newServer.redirectUrl,- newServer.identifier,- );- if (authResult.success) {- await this.enablePluginForAgent(agentId, identifier);- return {- content: `Successfully connected and enabled Composio tool: ${composioAppInfo.label}`,- state: {- installed: true,- isComposio: true,- pluginId: identifier,- pluginName: composioAppInfo.label,- serverStatus: 'connected',- success: true,- } as InstallPluginState,- success: true,- };- }- }- }-- return {- content: `Failed to connect Composio tool: ${composioAppInfo.label}`,- error: { message: 'Failed to create Composio connection', type: 'ComposioError' },- state: {- installed: false,- pluginId: identifier,- success: false,- } as InstallPluginState,- success: false,- };- }-- private async handleLobehubSkillInstall(- agentId: string,- identifier: string,- providerInfo: LobehubSkillProviderType,- server?: LobehubSkillServer,- ): Promise<BuiltinToolResult> {- if (server?.status === LobehubSkillStatus.CONNECTED) {- await this.enablePluginForAgent(agentId, identifier);- return {- content: `Successfully enabled LobehubSkill provider: ${providerInfo.label}`,- state: {- installed: true,- isLobehubSkill: true,- pluginId: identifier,- pluginName: providerInfo.label,- serverStatus: 'connected',- success: true,- } as InstallPluginState,- success: true,- };- }-- // Need OAuth authorization- // Skip redirectUri on desktop (app:// protocol) since the system browser can't navigate to it- const redirectUri =- typeof window !== 'undefined' && window.location.protocol.startsWith('http')- ? `${window.location.origin}/oauth/callback/success?provider=${encodeURIComponent(identifier)}`- : undefined;- const authInfo = await getToolStoreState().getLobehubSkillAuthorizeUrl(identifier, {- redirectUri,- });-- if (!authInfo.authorizeUrl) {- return {- content: `LobehubSkill provider "${providerInfo.label}" requires OAuth authorization but no authorization URL is available.`,- state: {- installed: false,- isLobehubSkill: true,- pluginId: identifier,- pluginName: providerInfo.label,- serverStatus: 'not_connected',- success: false,- } as InstallPluginState,- success: false,- };- }-- const authResult = await this.openLobehubSkillOAuthWindowAndWait(- authInfo.authorizeUrl,- identifier,- );-- if (authResult.success) {- await this.enablePluginForAgent(agentId, identifier);- return {- content: `Successfully connected and enabled LobehubSkill provider: ${providerInfo.label}`,- state: {- installed: true,- isLobehubSkill: true,- pluginId: identifier,- pluginName: providerInfo.label,- serverStatus: 'connected',- success: true,- } as InstallPluginState,- success: true,- };- }-- return {- content: `OAuth authorization was cancelled or failed for LobehubSkill provider: ${providerInfo.label}. Please try again.`,- state: {- installed: false,- isLobehubSkill: true,- pluginId: identifier,- pluginName: providerInfo.label,- serverStatus: 'not_connected',- success: false,- } as InstallPluginState,- success: false,- };- }-- private async handleMarketPluginInstall(- agentId: string,- identifier: string,- ): Promise<BuiltinToolResult> {- const toolState = getToolStoreState();- const isInstalled = pluginSelectors.isPluginInstalled(identifier)(toolState);-- if (isInstalled) {- await this.enablePluginForAgent(agentId, 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,- };- }-- const installSuccess = await getToolStoreState().installMCPPlugin(identifier);-- if (installSuccess) {- await this.enablePluginForAgent(agentId, identifier);- await getToolStoreState().refreshPlugins();- const freshToolState = getToolStoreState();- const installedPlugin = pluginSelectors.getInstalledPluginById(identifier)(freshToolState);-- return {- content: `Successfully installed and enabled MCP plugin "${installedPlugin?.manifest?.meta?.title || identifier}".`,- state: {- installed: true,- pluginId: identifier,- pluginName: installedPlugin?.manifest?.meta?.title || identifier,- success: true,- } as InstallPluginState,- success: true,- };- }-- return {- content: `Failed to install MCP plugin "${identifier}". Installation was cancelled or configuration is needed.`,- state: {- installed: false,- pluginId: identifier,- success: false,- } as InstallPluginState,- success: false,- };- }-- private async enablePluginForAgent(agentId: string, pluginId: string): Promise<void> {- await this.ensureAgentLoaded(agentId);- const agentState = getAgentStoreState();- const currentPlugins = agentSelectors.getAgentConfigById(agentId)(agentState)?.plugins;-- // upsertPluginMode preserves an already-matching entry as-is and flips a- // disabled entry back to pinned in place, instead of blindly pushing a- // duplicate bare-string identifier.- if (getPluginMode(currentPlugins, pluginId) !== 'pinned') {- await getAgentStoreState().optimisticUpdateAgentConfig(agentId, {- plugins: upsertPluginMode(currentPlugins, pluginId, 'pinned'),- });- }- }-- private openOAuthWindowAndWait(- redirectUrl: string,- identifier: string,- ): Promise<{ cancelled: boolean; success: boolean }> {- const checkAuthStatus = async (): Promise<boolean> => {- try {- await getToolStoreState().refreshComposioConnectionStatus(identifier);- const freshToolStore = getToolStoreState();- const server = composioStoreSelectors- .getServers(freshToolStore)- .find((s) => s.identifier === identifier);- return server?.status === ComposioServerStatus.ACTIVE;- } catch {- return false;- }- };-- return new Promise((resolve) => {- const WINDOW_CHECK_INTERVAL_MS = 500;- const POLL_INTERVAL_MS = 1000;- const POLL_TIMEOUT_MS = 300_000;-- 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);- if (pollInterval) clearInterval(pollInterval);- if (pollTimeout) clearTimeout(pollTimeout);- };-- const resolveOnce = (result: { cancelled: boolean; success: boolean }) => {- if (resolved) return;- resolved = true;- cleanup();- resolve(result);- };-- const startFallbackPolling = () => {- if (pollInterval) return;- pollInterval = setInterval(async () => {- const isConnected = await checkAuthStatus();- if (isConnected) resolveOnce({ cancelled: false, success: true });- }, POLL_INTERVAL_MS);- pollTimeout = setTimeout(- () => resolveOnce({ cancelled: true, success: false }),- POLL_TIMEOUT_MS,- );- };-- const oauthWindow = window.open(redirectUrl, '_blank', 'width=600,height=700');-- if (oauthWindow) {- windowCheckInterval = setInterval(async () => {- try {- if (oauthWindow.closed) {- if (windowCheckInterval) clearInterval(windowCheckInterval);- const isConnected = await checkAuthStatus();- resolveOnce({ cancelled: !isConnected, success: isConnected });- }- } catch {- if (windowCheckInterval) clearInterval(windowCheckInterval);- startFallbackPolling();- }- }, WINDOW_CHECK_INTERVAL_MS);- } else {- startFallbackPolling();- }- });- }-- private openLobehubSkillOAuthWindowAndWait(- redirectUrl: string,- provider: string,- ): Promise<{ cancelled: boolean; success: boolean }> {- const checkAuthStatus = async (): Promise<boolean> => {- try {- const server = await getToolStoreState().checkLobehubSkillStatus(provider);- return server?.status === LobehubSkillStatus.CONNECTED;- } catch {- return false;- }- };-- return new Promise((resolve) => {- const WINDOW_CHECK_INTERVAL_MS = 500;- const POLL_INTERVAL_MS = 1000;- const POLL_TIMEOUT_MS = 300_000;-- let pollInterval: ReturnType<typeof setInterval> | null = null;- let pollTimeout: ReturnType<typeof setTimeout> | null = null;- let windowCheckInterval: ReturnType<typeof setInterval> | null = null;- let messageHandler: ((event: MessageEvent) => void) | null = null;- let resolved = false;-- const cleanup = () => {- if (windowCheckInterval) clearInterval(windowCheckInterval);- if (pollInterval) clearInterval(pollInterval);- if (pollTimeout) clearTimeout(pollTimeout);- if (messageHandler) window.removeEventListener('message', messageHandler);- };-- const resolveOnce = (result: { cancelled: boolean; success: boolean }) => {- if (resolved) return;- resolved = true;- cleanup();- resolve(result);- };-- messageHandler = async (event: MessageEvent) => {- if (event.origin !== window.location.origin) return;- if (- event.data?.type === 'LOBEHUB_SKILL_AUTH_SUCCESS' &&- event.data?.provider === provider- ) {- const server = await getToolStoreState().checkLobehubSkillStatus(provider);- const isConnected = server?.status === LobehubSkillStatus.CONNECTED;- resolveOnce({ cancelled: false, success: isConnected });- }- };-- window.addEventListener('message', messageHandler);-- const startFallbackPolling = () => {- if (pollInterval) return;- pollInterval = setInterval(async () => {- const isConnected = await checkAuthStatus();- if (isConnected) resolveOnce({ cancelled: false, success: true });- }, POLL_INTERVAL_MS);- pollTimeout = setTimeout(- () => resolveOnce({ cancelled: true, success: false }),- POLL_TIMEOUT_MS,- );- };-- const oauthWindow = window.open(redirectUrl, '_blank', 'width=600,height=700');-- if (oauthWindow) {- windowCheckInterval = setInterval(async () => {- try {- if (oauthWindow.closed) {- if (windowCheckInterval) clearInterval(windowCheckInterval);- const isConnected = await checkAuthStatus();- resolveOnce({ cancelled: !isConnected, success: isConnected });- }- } catch {- if (windowCheckInterval) clearInterval(windowCheckInterval);- startFallbackPolling();- }- }, WINDOW_CHECK_INTERVAL_MS);- } else {- startFallbackPolling();- }- });- }-- // ==================== Error Handling ====================-- private handleError(error: unknown, context: string): BuiltinToolResult {- const err = error as Error;- return {- content: `${context}: ${err.message}`,- error: {- body: error,- message: err.message,- type: 'RuntimeError',- },- success: false,- };- }-- private handleErrorWithState<T extends object>(- error: unknown,- context: string,- state: T,- ): BuiltinToolResult {- const err = error as Error;- return {- content: `${context}: ${err.message}`,- error: {- body: error,- message: err.message,- type: 'RuntimeError',- },- state,- success: false,- };+ return installPlugin(this.agentService, agentId, params);}}diff --git a/packages/agent-manager-runtime/src/AgentManagerRuntime/installPlugin.ts b/packages/agent-manager-runtime/src/AgentManagerRuntime/installPlugin.tsnew file mode 100644index 00000000000..51618b80e2e--- /dev/null+++ b/packages/agent-manager-runtime/src/AgentManagerRuntime/installPlugin.ts@@ -0,0 +1,423 @@+import type { ComposioAppType, LobehubSkillProviderType } from '@lobechat/const';+import { resolveConnectorCatalogItem } from '@lobechat/const';+import { type BuiltinToolResult, getPluginMode, upsertPluginMode } from '@lobechat/types';++import { getAgentStoreState } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors/selectors';+import { getToolStoreState } from '@/store/tool';+import {+ builtinToolSelectors,+ composioStoreSelectors,+ lobehubSkillStoreSelectors,+ pluginSelectors,+} from '@/store/tool/selectors';+import type { ComposioServer } from '@/store/tool/slices/composioStore/types';+import { ComposioServerStatus } from '@/store/tool/slices/composioStore/types';+import type { LobehubSkillServer } from '@/store/tool/slices/lobehubSkillStore/types';+import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore/types';+import { getUserStoreState } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';++import type { IAgentService, InstallPluginParams, InstallPluginState } from '../types';+import { handleErrorWithState } from './errors';+import { openComposioOAuthWindowAndWait, openLobehubSkillOAuthWindowAndWait } from './oauthWindow';++/**+ * Install a plugin+ */+export const installPlugin = async (+ agentService: IAgentService,+ agentId: string,+ params: InstallPluginParams,+): Promise<BuiltinToolResult> => {+ const { identifier, source } = params;++ // Each branch is `return await`ed: a bare `return` hands back the pending+ // promise, so a store rejection would skip this catch and reach the caller+ // as a thrown error instead of a failed install result.+ try {+ const toolState = getToolStoreState();++ if (source === 'official') {+ const isComposioEnabled =+ typeof window !== 'undefined' &&+ window.global_serverConfigStore?.getState()?.serverConfig?.enableComposio;+ const isLobehubSkillEnabled =+ typeof window !== 'undefined' &&+ window.global_serverConfigStore?.getState()?.serverConfig?.enableLobehubSkill;+ const connector = resolveConnectorCatalogItem(identifier, {+ composio: Boolean(isComposioEnabled),+ lobehub: Boolean(isLobehubSkillEnabled),+ });++ if (connector?.type === 'composio') {+ const composioServer = composioStoreSelectors+ .getServers(toolState)+ .find((s) => s.identifier === identifier);+ return await handleComposioInstall(+ agentService,+ agentId,+ identifier,+ connector.serverType,+ composioServer,+ );+ }++ if (connector?.type === 'lobehub') {+ const lobehubSkillServer = lobehubSkillStoreSelectors+ .getServers(toolState)+ .find((s) => s.identifier === identifier);+ return await handleLobehubSkillInstall(+ agentService,+ agentId,+ identifier,+ connector.provider,+ lobehubSkillServer,+ );+ }++ // Check if it's a builtin tool+ const builtinTools = builtinToolSelectors.metaList(toolState);+ const builtinTool = builtinTools.find((t) => t.identifier === identifier);++ if (builtinTool) {+ await enablePluginForAgent(agentService, agentId, 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: { message: 'Tool not found', type: 'NotFound' },+ state: {+ installed: false,+ pluginId: identifier,+ success: false,+ } as InstallPluginState,+ success: false,+ };+ }++ // Source is 'market' - MCP marketplace plugin+ return await handleMarketPluginInstall(agentService, agentId, identifier);+ } catch (error) {+ const err = error as Error;+ return handleErrorWithState(error, 'Failed to install plugin', {+ error: err.message,+ installed: false,+ pluginId: identifier,+ success: false,+ } as InstallPluginState);+ }+};++/**+ * Ensure the agent config is loaded into the Zustand store.+ * When operating on agents that aren't currently open/active,+ * their config won't be in the agentMap. This fetches and dispatches it.+ */+export const ensureAgentLoaded = async (+ agentService: IAgentService,+ agentId: string,+): Promise<void> => {+ const state = getAgentStoreState();+ const existing = state.agentMap[agentId];+ if (existing) return;++ const config = await agentService.getAgentConfigById(agentId);+ if (config) {+ getAgentStoreState().internal_dispatchAgentMap(agentId, config);+ }+};++const handleComposioInstall = async (+ agentService: IAgentService,+ agentId: string,+ identifier: string,+ composioAppInfo: ComposioAppType,+ composioServer?: ComposioServer,+): Promise<BuiltinToolResult> => {+ if (composioServer) {+ if (composioServer.status === ComposioServerStatus.ACTIVE) {+ await enablePluginForAgent(agentService, agentId, identifier);+ return {+ content: `Successfully enabled Composio tool: ${composioAppInfo.label}`,+ state: {+ installed: true,+ isComposio: true,+ pluginId: identifier,+ pluginName: composioAppInfo.label,+ serverStatus: 'connected',+ success: true,+ } as InstallPluginState,+ success: true,+ };+ } else if (composioServer.status === ComposioServerStatus.PENDING_AUTH) {+ if (composioServer.redirectUrl) {+ const authResult = await openComposioOAuthWindowAndWait(+ composioServer.redirectUrl,+ identifier,+ );+ if (authResult.success) {+ await enablePluginForAgent(agentService, agentId, identifier);+ return {+ content: `Successfully connected and enabled Composio tool: ${composioAppInfo.label}`,+ state: {+ installed: true,+ isComposio: true,+ pluginId: identifier,+ pluginName: composioAppInfo.label,+ serverStatus: 'connected',+ success: true,+ } as InstallPluginState,+ success: true,+ };+ }+ }+ return {+ content: `OAuth authorization was cancelled or failed for Composio tool: ${composioAppInfo.label}. Please try again.`,+ state: {+ installed: false,+ isComposio: true,+ pluginId: identifier,+ pluginName: composioAppInfo.label,+ serverStatus: 'pending_auth',+ success: false,+ } as InstallPluginState,+ success: false,+ };+ }+ }++ // Server doesn't exist, create it+ const userId = userProfileSelectors.userId(getUserStoreState());+ if (!userId) {+ return {+ content: `Cannot connect Composio tool: User not logged in.`,+ error: { message: 'User not logged in', type: 'AuthRequired' },+ state: { installed: false, pluginId: identifier, success: false } as InstallPluginState,+ success: false,+ };+ }++ const newServer = await getToolStoreState().createComposioConnection({+ appSlug: composioAppInfo.appSlug,+ identifier,+ label: composioAppInfo.label,+ });++ if (newServer) {+ // Enable the plugin only once the connection is actually usable. Enabling+ // before OAuth completes would leave an enabled-but-unauthorized tool on+ // the agent if the user cancels the authorization.+ if (newServer.status === ComposioServerStatus.ACTIVE) {+ await enablePluginForAgent(agentService, agentId, identifier);+ await getToolStoreState().refreshComposioConnectionStatus(newServer.identifier);+ return {+ content: `Successfully connected and enabled Composio tool: ${composioAppInfo.label}`,+ state: {+ installed: true,+ isComposio: true,+ pluginId: identifier,+ pluginName: composioAppInfo.label,+ serverStatus: 'connected',+ success: true,+ } as InstallPluginState,+ success: true,+ };+ } else if (newServer.redirectUrl) {+ const authResult = await openComposioOAuthWindowAndWait(+ newServer.redirectUrl,+ newServer.identifier,+ );+ if (authResult.success) {+ await enablePluginForAgent(agentService, agentId, identifier);+ return {+ content: `Successfully connected and enabled Composio tool: ${composioAppInfo.label}`,+ state: {+ installed: true,+ isComposio: true,+ pluginId: identifier,+ pluginName: composioAppInfo.label,+ serverStatus: 'connected',+ success: true,+ } as InstallPluginState,+ success: true,+ };+ }+ }+ }++ return {+ content: `Failed to connect Composio tool: ${composioAppInfo.label}`,+ error: { message: 'Failed to create Composio connection', type: 'ComposioError' },+ state: {+ installed: false,+ pluginId: identifier,+ success: false,+ } as InstallPluginState,+ success: false,+ };+};++const handleLobehubSkillInstall = async (+ agentService: IAgentService,+ agentId: string,+ identifier: string,+ providerInfo: LobehubSkillProviderType,+ server?: LobehubSkillServer,+): Promise<BuiltinToolResult> => {+ if (server?.status === LobehubSkillStatus.CONNECTED) {+ await enablePluginForAgent(agentService, agentId, identifier);+ return {+ content: `Successfully enabled LobehubSkill provider: ${providerInfo.label}`,+ state: {+ installed: true,+ isLobehubSkill: true,+ pluginId: identifier,+ pluginName: providerInfo.label,+ serverStatus: 'connected',+ success: true,+ } as InstallPluginState,+ success: true,+ };+ }++ // Need OAuth authorization+ // Skip redirectUri on desktop (app:// protocol) since the system browser can't navigate to it+ const redirectUri =+ typeof window !== 'undefined' && window.location.protocol.startsWith('http')+ ? `${window.location.origin}/oauth/callback/success?provider=${encodeURIComponent(identifier)}`+ : undefined;+ const authInfo = await getToolStoreState().getLobehubSkillAuthorizeUrl(identifier, {+ redirectUri,+ });++ if (!authInfo.authorizeUrl) {+ return {+ content: `LobehubSkill provider "${providerInfo.label}" requires OAuth authorization but no authorization URL is available.`,+ state: {+ installed: false,+ isLobehubSkill: true,+ pluginId: identifier,+ pluginName: providerInfo.label,+ serverStatus: 'not_connected',+ success: false,+ } as InstallPluginState,+ success: false,+ };+ }++ const authResult = await openLobehubSkillOAuthWindowAndWait(authInfo.authorizeUrl, identifier);++ if (authResult.success) {+ await enablePluginForAgent(agentService, agentId, identifier);+ return {+ content: `Successfully connected and enabled LobehubSkill provider: ${providerInfo.label}`,+ state: {+ installed: true,+ isLobehubSkill: true,+ pluginId: identifier,+ pluginName: providerInfo.label,+ serverStatus: 'connected',+ success: true,+ } as InstallPluginState,+ success: true,+ };+ }++ return {+ content: `OAuth authorization was cancelled or failed for LobehubSkill provider: ${providerInfo.label}. Please try again.`,+ state: {+ installed: false,+ isLobehubSkill: true,+ pluginId: identifier,+ pluginName: providerInfo.label,+ serverStatus: 'not_connected',+ success: false,+ } as InstallPluginState,+ success: false,+ };+};++const handleMarketPluginInstall = async (+ agentService: IAgentService,+ agentId: string,+ identifier: string,+): Promise<BuiltinToolResult> => {+ const toolState = getToolStoreState();+ const isInstalled = pluginSelectors.isPluginInstalled(identifier)(toolState);++ if (isInstalled) {+ await enablePluginForAgent(agentService, agentId, 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,+ };+ }++ const installSuccess = await getToolStoreState().installMCPPlugin(identifier);++ if (installSuccess) {+ await enablePluginForAgent(agentService, agentId, identifier);+ await getToolStoreState().refreshPlugins();+ const freshToolState = getToolStoreState();+ const installedPlugin = pluginSelectors.getInstalledPluginById(identifier)(freshToolState);++ return {+ content: `Successfully installed and enabled MCP plugin "${installedPlugin?.manifest?.meta?.title || identifier}".`,+ state: {+ installed: true,+ pluginId: identifier,+ pluginName: installedPlugin?.manifest?.meta?.title || identifier,+ success: true,+ } as InstallPluginState,+ success: true,+ };+ }++ return {+ content: `Failed to install MCP plugin "${identifier}". Installation was cancelled or configuration is needed.`,+ state: {+ installed: false,+ pluginId: identifier,+ success: false,+ } as InstallPluginState,+ success: false,+ };+};++export const enablePluginForAgent = async (+ agentService: IAgentService,+ agentId: string,+ pluginId: string,+): Promise<void> => {+ await ensureAgentLoaded(agentService, agentId);+ const agentState = getAgentStoreState();+ const currentPlugins = agentSelectors.getAgentConfigById(agentId)(agentState)?.plugins;++ // upsertPluginMode preserves an already-matching entry as-is and flips a+ // disabled entry back to pinned in place, instead of blindly pushing a+ // duplicate bare-string identifier.+ if (getPluginMode(currentPlugins, pluginId) !== 'pinned') {+ await getAgentStoreState().optimisticUpdateAgentConfig(agentId, {+ plugins: upsertPluginMode(currentPlugins, pluginId, 'pinned'),+ });+ }+};diff --git a/packages/agent-manager-runtime/src/AgentManagerRuntime/oauthWindow.ts b/packages/agent-manager-runtime/src/AgentManagerRuntime/oauthWindow.tsnew file mode 100644index 00000000000..c6ba928e888--- /dev/null+++ b/packages/agent-manager-runtime/src/AgentManagerRuntime/oauthWindow.ts@@ -0,0 +1,167 @@+import { getToolStoreState } from '@/store/tool';+import { composioStoreSelectors } from '@/store/tool/selectors';+import { ComposioServerStatus } from '@/store/tool/slices/composioStore/types';+import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore/types';++/**+ * Open a Composio OAuth popup and wait until the connection is active, the+ * popup closes, or polling times out.+ */+export const openComposioOAuthWindowAndWait = (+ redirectUrl: string,+ identifier: string,+): Promise<{ cancelled: boolean; success: boolean }> => {+ const checkAuthStatus = async (): Promise<boolean> => {+ try {+ await getToolStoreState().refreshComposioConnectionStatus(identifier);+ const freshToolStore = getToolStoreState();+ const server = composioStoreSelectors+ .getServers(freshToolStore)+ .find((s) => s.identifier === identifier);+ return server?.status === ComposioServerStatus.ACTIVE;+ } catch {+ return false;+ }+ };++ return new Promise((resolve) => {+ const WINDOW_CHECK_INTERVAL_MS = 500;+ const POLL_INTERVAL_MS = 1000;+ const POLL_TIMEOUT_MS = 300_000;++ 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);+ if (pollInterval) clearInterval(pollInterval);+ if (pollTimeout) clearTimeout(pollTimeout);+ };++ const resolveOnce = (result: { cancelled: boolean; success: boolean }) => {+ if (resolved) return;+ resolved = true;+ cleanup();+ resolve(result);+ };++ const startFallbackPolling = () => {+ if (pollInterval) return;+ pollInterval = setInterval(async () => {+ const isConnected = await checkAuthStatus();+ if (isConnected) resolveOnce({ cancelled: false, success: true });+ }, POLL_INTERVAL_MS);+ pollTimeout = setTimeout(+ () => resolveOnce({ cancelled: true, success: false }),+ POLL_TIMEOUT_MS,+ );+ };++ const oauthWindow = window.open(redirectUrl, '_blank', 'width=600,height=700');++ if (oauthWindow) {+ windowCheckInterval = setInterval(async () => {+ try {+ if (oauthWindow.closed) {+ if (windowCheckInterval) clearInterval(windowCheckInterval);+ const isConnected = await checkAuthStatus();+ resolveOnce({ cancelled: !isConnected, success: isConnected });+ }+ } catch {+ if (windowCheckInterval) clearInterval(windowCheckInterval);+ startFallbackPolling();+ }+ }, WINDOW_CHECK_INTERVAL_MS);+ } else {+ startFallbackPolling();+ }+ });+};++/**+ * Open a LobeHub Skill OAuth popup and wait for the callback page message,+ * the popup closing, or the polling timeout.+ */+export const openLobehubSkillOAuthWindowAndWait = (+ redirectUrl: string,+ provider: string,+): Promise<{ cancelled: boolean; success: boolean }> => {+ const checkAuthStatus = async (): Promise<boolean> => {+ try {+ const server = await getToolStoreState().checkLobehubSkillStatus(provider);+ return server?.status === LobehubSkillStatus.CONNECTED;+ } catch {+ return false;+ }+ };++ return new Promise((resolve) => {+ const WINDOW_CHECK_INTERVAL_MS = 500;+ const POLL_INTERVAL_MS = 1000;+ const POLL_TIMEOUT_MS = 300_000;++ let pollInterval: ReturnType<typeof setInterval> | null = null;+ let pollTimeout: ReturnType<typeof setTimeout> | null = null;+ let windowCheckInterval: ReturnType<typeof setInterval> | null = null;+ let messageHandler: ((event: MessageEvent) => void) | null = null;+ let resolved = false;++ const cleanup = () => {+ if (windowCheckInterval) clearInterval(windowCheckInterval);+ if (pollInterval) clearInterval(pollInterval);+ if (pollTimeout) clearTimeout(pollTimeout);+ if (messageHandler) window.removeEventListener('message', messageHandler);+ };++ const resolveOnce = (result: { cancelled: boolean; success: boolean }) => {+ if (resolved) return;+ resolved = true;+ cleanup();+ resolve(result);+ };++ messageHandler = async (event: MessageEvent) => {+ if (event.origin !== window.location.origin) return;+ if (event.data?.type === 'LOBEHUB_SKILL_AUTH_SUCCESS' && event.data?.provider === provider) {+ const server = await getToolStoreState().checkLobehubSkillStatus(provider);+ const isConnected = server?.status === LobehubSkillStatus.CONNECTED;+ resolveOnce({ cancelled: false, success: isConnected });+ }+ };++ window.addEventListener('message', messageHandler);++ const startFallbackPolling = () => {+ if (pollInterval) return;+ pollInterval = setInterval(async () => {+ const isConnected = await checkAuthStatus();+ if (isConnected) resolveOnce({ cancelled: false, success: true });+ }, POLL_INTERVAL_MS);+ pollTimeout = setTimeout(+ () => resolveOnce({ cancelled: true, success: false }),+ POLL_TIMEOUT_MS,+ );+ };++ const oauthWindow = window.open(redirectUrl, '_blank', 'width=600,height=700');++ if (oauthWindow) {+ windowCheckInterval = setInterval(async () => {+ try {+ if (oauthWindow.closed) {+ if (windowCheckInterval) clearInterval(windowCheckInterval);+ const isConnected = await checkAuthStatus();+ resolveOnce({ cancelled: !isConnected, success: isConnected });+ }+ } catch {+ if (windowCheckInterval) clearInterval(windowCheckInterval);+ startFallbackPolling();+ }+ }, WINDOW_CHECK_INTERVAL_MS);+ } else {+ startFallbackPolling();+ }+ });+};diff --git a/packages/agent-manager-runtime/src/types.ts b/packages/agent-manager-runtime/src/types.tsindex a50768d68c9..13f427e5235 100644--- a/packages/agent-manager-runtime/src/types.ts+++ b/packages/agent-manager-runtime/src/types.ts@@ -30,7 +30,9 @@ export interface IAgentService {avatar?: string | null;backgroundColor?: string | null;description?: string | null;+ heteroType?: HeterogeneousProviderConfig['type'];id: string;+ name?: string | null;title?: string | null;}>>;@@ -41,6 +43,12 @@ export interface IAgentService {* Interface for discover/marketplace service operations*/export interface IDiscoverService {+ getAssistantDetail?: (params: {+ identifier: string;+ locale?: string;+ source?: AssistantMarketSource;+ version?: string;+ }) => Promise<DiscoverAssistantDetail | undefined>;getAssistantList: (params: { category?: string; pageSize?: number; q?: string }) => Promise<{items: Array<{avatar?: string;@@ -51,12 +59,6 @@ export interface IDiscoverService {}>;totalCount: number;}>;- getAssistantDetail?: (params: {- identifier: string;- locale?: string;- source?: AssistantMarketSource;- version?: string;- }) => Promise<DiscoverAssistantDetail | undefined>;getMcpList: (params: { category?: string; pageSize?: number; q?: string }) => Promise<{items: Array<{author?: string;@@ -167,6 +169,8 @@ export interface AgentSearchItem {heteroType?: HeterogeneousProviderConfig['type'];id: string;isMarket?: boolean;+ /** User-facing display name; `title` is the agent's role */+ name?: string;title?: string;}diff --git a/packages/builtin-tool-agent-management/src/client/Render/SearchAgent/index.tsx b/packages/builtin-tool-agent-management/src/client/Render/SearchAgent/index.tsxindex 7867caf7fc7..dc75c7481ce 100644--- a/packages/builtin-tool-agent-management/src/client/Render/SearchAgent/index.tsx+++ b/packages/builtin-tool-agent-management/src/client/Render/SearchAgent/index.tsx@@ -3,9 +3,8 @@import { DEFAULT_AVATAR } from '@lobechat/const';import { HETEROGENEOUS_TYPE_LABELS } from '@lobechat/heterogeneous-agents';import type { BuiltinRenderProps } from '@lobechat/types';-import { Flexbox } from '@lobehub/ui';-import { Avatar } from '@lobehub/ui';-import { createStaticStyles, useTheme } from '@lobehub/ui';+import { agentDisplayName, agentSecondaryDisplayName } from '@lobechat/types';+import { Avatar, createStaticStyles, Flexbox, useTheme } from '@lobehub/ui';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -18,6 +17,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({border-radius: 6px;background: ${cssVar.colorFillQuaternary};`,+ agentRole: css`+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,agentTitle: css`font-size: 13px;font-weight: 500;@@ -84,29 +87,43 @@ export const SearchAgentRender = memo<BuiltinRenderProps<SearchAgentParams, Searreturn (<div className={styles.container}>- {agents.map((agent: AgentSearchItem) => (- <Flexbox horizontal align={'center'} className={styles.agentItem} gap={12} key={agent.id}>- <Avatar- avatar={agent.avatar || DEFAULT_AVATAR}- background={agent.backgroundColor || theme.colorBgContainer}- shape={'square'}- size={32}- title={agent.title || undefined}- />- <Flexbox flex={1} gap={2}>- <Flexbox horizontal align={'center'} gap={8}>- <span className={styles.agentTitle}>{agent.title || agent.id}</span>- {agent.heteroType && (- <span className={styles.heteroBadge}>- {HETEROGENEOUS_TYPE_LABELS[agent.heteroType] ?? agent.heteroType}- </span>+ {agents.map((agent: AgentSearchItem) => {+ const displayName = agentDisplayName(agent, agent.id);+ const role = agentSecondaryDisplayName(agent);++ return (+ <Flexbox+ horizontal+ align={'center'}+ className={styles.agentItem}+ gap={12}+ key={agent.id}+ >+ <Avatar+ avatar={agent.avatar || DEFAULT_AVATAR}+ background={agent.backgroundColor || theme.colorBgContainer}+ shape={'square'}+ size={32}+ title={displayName}+ />+ <Flexbox flex={1} gap={2}>+ <Flexbox horizontal align={'center'} gap={8}>+ <span className={styles.agentTitle}>{displayName}</span>+ {role && <span className={styles.agentRole}>{role}</span>}+ {agent.heteroType && (+ <span className={styles.heteroBadge}>+ {HETEROGENEOUS_TYPE_LABELS[agent.heteroType] ?? agent.heteroType}+ </span>+ )}+ {agent.isMarket && <span className={styles.marketBadge}>Market</span>}+ </Flexbox>+ {agent.description && (+ <span className={styles.description}>{agent.description}</span>)}- {agent.isMarket && <span className={styles.marketBadge}>Market</span>}</Flexbox>- {agent.description && <span className={styles.description}>{agent.description}</span>}</Flexbox>- </Flexbox>- ))}+ );+ })}</div>);},diff --git a/packages/builtin-tool-agent-management/src/types.ts b/packages/builtin-tool-agent-management/src/types.tsindex 9628335b733..6b04366bef1 100644--- a/packages/builtin-tool-agent-management/src/types.ts+++ b/packages/builtin-tool-agent-management/src/types.ts@@ -227,6 +227,10 @@ export interface AgentSearchItem {* Whether this is a marketplace agent*/isMarket?: boolean;+ /**+ * User-facing display name; `title` is the agent's role+ */+ name?: string;/*** Agent title*/diff --git a/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.test.tsnew file mode 100644index 00000000000..1e1544d06b7--- /dev/null+++ b/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.test.ts@@ -0,0 +1,31 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { GroupAgentBuilderExecutionRuntime } from './index';++const { mockQueryAgents } = vi.hoisted(() => ({ mockQueryAgents: vi.fn() }));++vi.mock('@/services/agent', () => ({ agentService: { queryAgents: mockQueryAgents } }));+vi.mock('@/services/chatGroup', () => ({ chatGroupService: {} }));+vi.mock('@/store/agent', () => ({ useAgentStore: { getState: vi.fn() } }));+vi.mock('@/store/agentGroup', () => ({ getChatGroupStoreState: vi.fn() }));+vi.mock('@/store/agentGroup/selectors', () => ({ agentGroupSelectors: {} }));+vi.mock('@/store/groupProfile', () => ({ useGroupProfileStore: { getState: vi.fn() } }));++describe('GroupAgentBuilderExecutionRuntime.searchAgent', () => {+ beforeEach(() => {+ mockQueryAgents.mockReset();+ });++ it('shows the agent name alongside its title so a named agent is recognizable', async () => {+ mockQueryAgents.mockResolvedValue([+ { description: null, id: 'agt_dario', name: 'Dario δ»»ε‘ιεη', title: 'ηΎε½100ε' },+ { description: 'Writes code', id: 'agt_plain', name: null, title: 'Coder' },+ ]);++ const result = await new GroupAgentBuilderExecutionRuntime().searchAgent({ query: 'dario' });++ expect(result.content).toContain('1. Dario δ»»ε‘ιεη [title: ηΎε½100ε] (ID: agt_dario)');+ expect(result.content).toContain('2. Coder (ID: agt_plain) - Writes code');+ expect(result.state.agents[0]).toMatchObject({ name: 'Dario δ»»ε‘ιεη', title: 'ηΎε½100ε' });+ });+});diff --git a/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts b/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.tsindex 4dfc85587d0..6e3de0ac1b9 100644--- a/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts@@ -91,6 +91,7 @@ export class GroupAgentBuilderExecutionRuntime {avatar: agent.avatar,description: agent.description,id: agent.id,+ name: agent.name ?? undefined,title: agent.title,}));@@ -106,12 +107,17 @@ export class GroupAgentBuilderExecutionRuntime {};}- // Format agents list for LLM consumption+ // Format agents list for LLM consumption. Lead with the name the agent is+ // known by and keep the title as its role, so a named agent stays+ // recognizable to the model.const agentList = agents- .map(- (a, i) =>- `${i + 1}. ${a.title || 'Untitled'} (ID: ${a.id})${a.description ? ` - ${a.description}` : ''}`,- )+ .map((a, i) => {+ const name = a.name?.trim();+ const label = name+ ? `${name}${a.title ? ` [title: ${a.title}]` : ''}`+ : a.title || 'Untitled';+ return `${i + 1}. ${label} (ID: ${a.id})${a.description ? ` - ${a.description}` : ''}`;+ }).join('\n');return {diff --git a/packages/builtin-tool-group-agent-builder/src/types.ts b/packages/builtin-tool-group-agent-builder/src/types.tsindex cc4f7cb639e..00836d4976d 100644--- a/packages/builtin-tool-group-agent-builder/src/types.ts+++ b/packages/builtin-tool-group-agent-builder/src/types.ts@@ -370,6 +370,8 @@ export interface SearchAgentResult {avatar?: string;description?: string;id: string;+ /** User-facing display name; `title` is the agent's role */+ name?: string;title: string;}diff --git a/packages/prompts/src/prompts/agentBuilder/searchAgentsResultsPrompt.test.ts b/packages/prompts/src/prompts/agentBuilder/searchAgentsResultsPrompt.test.tsindex 3dce8fa43ee..8e695921f59 100644--- a/packages/prompts/src/prompts/agentBuilder/searchAgentsResultsPrompt.test.ts+++ b/packages/prompts/src/prompts/agentBuilder/searchAgentsResultsPrompt.test.ts@@ -20,6 +20,22 @@ describe('searchAgentsResultsPrompt', () => {expect(content).not.toContain('<agentSearchResults');});+ it('renders the agent name before its title, omitting it when blank', () => {+ const content = searchAgentsResultsPrompt({+ agents: [+ { id: 'agt_named', name: 'Dario δ»»ε‘ιεη', title: 'ηΎε½100ε' },+ { id: 'agt_blank', name: ' ', title: 'Coder' },+ ],+ source: 'user',+ userTotal: 2,+ });++ expect(content).toContain(+ '<agent id="agt_named" name="Dario δ»»ε‘ιεη" title="ηΎε½100ε" origin="workspace" />',+ );+ expect(content).toContain('<agent id="agt_blank" title="Coder" origin="workspace" />');+ });+it('marks heterogeneous agents and appends a plain Note: guidance line', () => {const content = searchAgentsResultsPrompt({agents: [{ heteroType: 'claude-code', id: 'agt_cc', title: 'CC 2ε·ζΊ' }],diff --git a/packages/prompts/src/prompts/agentBuilder/searchAgentsResultsPrompt.ts b/packages/prompts/src/prompts/agentBuilder/searchAgentsResultsPrompt.tsindex bf11fae7078..6e066474110 100644--- a/packages/prompts/src/prompts/agentBuilder/searchAgentsResultsPrompt.ts+++ b/packages/prompts/src/prompts/agentBuilder/searchAgentsResultsPrompt.ts@@ -16,6 +16,12 @@ export interface SearchAgentResultItem {id: string;/** Whether the agent comes from the marketplace (vs. the user's workspace). */isMarket?: boolean;+ /**+ * User-facing display name ("Dario"). Independent of `title`, which is the+ * agent's role β an agent is usually known by its name, so the model must+ * see both or it cannot recognize the agent the user is talking about.+ */+ name?: string;title?: string;}@@ -37,8 +43,10 @@ export interface SearchAgentsPromptInput {}const formatAgent = (agent: SearchAgentResultItem): string => {+ const name = agent.name?.trim();const attrs: string[] = [`id="${escapeXmlAttr(agent.id)}"`,+ ...(name ? [`name="${escapeXmlAttr(name)}"`] : []),`title="${escapeXmlAttr(agent.title || 'Untitled')}"`,`origin="${agent.isMarket ? 'market' : 'workspace'}"`,];@@ -64,7 +72,7 @@ const formatAgent = (agent: SearchAgentResultItem): string => {* @example* ```text* Found 1 agent in your workspace, showing 1-1:- * <agent id="agt_xxx" title="CC 2ε·ζΊ" origin="workspace" heteroType="claude-code">My CC machine</agent>+ * <agent id="agt_xxx" name="Dario" title="CC 2ε·ζΊ" origin="workspace" heteroType="claude-code">My CC machine</agent>** Note: Agents with a `heteroType` are heterogeneous agents backed by an external CLI/device runtime. They can execute coding / agentic tasks directly β hand a task to them without extra setup.* ```