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.

πŸ› fix(agent-manager-runtime): fall back to marketplace detail for market-only agents (#20670)

Arvin Xu93a2e07d6b77
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts
index 1e87396042f..930265b6ed4 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts
@@ -9,6 +9,7 @@ import { agentManagementRuntime } from '../agentManagement';
const {
mockCountAgents,
mockGetAssistantList,
+ mockGetAssistantDetail,
mockQueryAgents,
mockExistsById,
mockGetAgentConfigById,
@@ -32,6 +33,7 @@ const {
mockExistsById: vi.fn(),
mockGetAgentConfigById: vi.fn(),
mockGetAssistantList: vi.fn(),
+ mockGetAssistantDetail: vi.fn(),
mockQueryAgents: vi.fn(),
mockServiceUpdateConfig: vi.fn(),
mockUpdateAgent: vi.fn(),
@@ -77,6 +79,7 @@ vi.mock('@/database/models/connector', () => ({
vi.mock('@/server/services/discover', () => ({
DiscoverService: vi.fn(function () {
return {
+ getAssistantDetail: mockGetAssistantDetail,
getAssistantList: mockGetAssistantList,
getMcpManifest: mockGetMcpManifest,
};
@@ -640,6 +643,109 @@ describe('agentManagementRuntime', () => {
});
});
+ // Regression guard: searchAgent surfaces marketplace ids (short codes) that
+ // have no local agents row, but getAgentDetail used to report a false
+ // "not found" for them on the gateway/Cloud execution path.
+ describe('getAgentDetail market fallback', () => {
+ it('falls back to marketplace detail for a market-only agent', async () => {
+ mockGetAgentConfigById.mockResolvedValue(null);
+ mockGetAssistantDetail.mockResolvedValue({
+ avatar: '🌐',
+ backgroundColor: 'pink',
+ config: {
+ model: 'gpt-4o',
+ openingMessage: 'Hi!',
+ openingQuestions: ['Q1'],
+ plugins: ['web-browsing', 'search'],
+ provider: 'openai',
+ systemRole: 'Market prompt',
+ },
+ description: 'A market agent',
+ identifier: 'mkt12345',
+ related: [],
+ tags: ['ai'],
+ title: 'Market Agent',
+ });
+
+ const runtime = createRuntime();
+ const result = await runtime.getAgentDetail({ agentId: 'mkt12345' });
+
+ expect(mockGetAssistantDetail).toHaveBeenCalledWith({
+ identifier: 'mkt12345',
+ source: 'new',
+ });
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Market Agent');
+ expect(result.content).toContain('Market prompt');
+ expect(result.content).toContain('marketplace agent (read-only)');
+ expect(result.state).toMatchObject({
+ agentId: 'mkt12345',
+ isMarket: true,
+ config: expect.objectContaining({ model: 'gpt-4o', systemRole: 'Market prompt' }),
+ meta: expect.objectContaining({ title: 'Market Agent' }),
+ });
+ });
+
+ it('normalizes the object-shaped marketplace model before rendering', async () => {
+ mockGetAgentConfigById.mockResolvedValue(null);
+ mockGetAssistantDetail.mockResolvedValue({
+ avatar: '🌐',
+ config: {
+ model: { model: 'gpt-4o', parameters: { temperature: 0.6 }, provider: 'openai' },
+ plugins: ['web-browsing'],
+ systemRole: 'Market prompt',
+ },
+ description: 'A market agent',
+ identifier: 'mktobj1',
+ related: [],
+ tags: ['ai'],
+ title: 'Object Model Agent',
+ });
+
+ const runtime = createRuntime();
+ const result = await runtime.getAgentDetail({ agentId: 'mktobj1' });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Model: openai/gpt-4o');
+ expect(result.content).not.toContain('[object Object]');
+ expect(result.state).toMatchObject({
+ config: expect.objectContaining({ model: 'gpt-4o', provider: 'openai' }),
+ });
+ });
+
+ it('still reports not found when the market fallback misses', async () => {
+ mockGetAgentConfigById.mockResolvedValue(null);
+ mockGetAssistantDetail.mockResolvedValue(undefined);
+
+ const runtime = createRuntime();
+ const result = await runtime.getAgentDetail({ agentId: 'ghost-id' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('Agent "ghost-id" not found.');
+ });
+
+ it('treats a market lookup failure as best-effort and reports not found', async () => {
+ mockGetAgentConfigById.mockResolvedValue(null);
+ mockGetAssistantDetail.mockRejectedValue(new Error('network down'));
+
+ const runtime = createRuntime();
+ const result = await runtime.getAgentDetail({ agentId: 'offline-id' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('Agent "offline-id" not found.');
+ });
+
+ it('does not hit the market for a local agent', async () => {
+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', provider: 'lobehub' });
+
+ const runtime = createRuntime();
+ const result = await runtime.getAgentDetail({ agentId: 'agent-1' });
+
+ expect(result.success).toBe(true);
+ expect(mockGetAssistantDetail).not.toHaveBeenCalled();
+ });
+ });
+
// Regression guard: built without an identity, DiscoverService sends no
// credentials at all, so every market read from this runtime failed as
// `unauthorized` while the client-side path β€” which signs a trusted-client
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts
index 175a621d769..79449c496a6 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts
@@ -17,6 +17,7 @@ import {
parsePluginEntry,
upsertPluginMode,
} from '@lobechat/types';
+import debug from 'debug';
import { AgentModel } from '@/database/models/agent';
import { ConnectorModel } from '@/database/models/connector';
@@ -40,6 +41,8 @@ const handleError = (error: unknown, message: string): ToolExecutionResult => {
/** Max results per searchAgent call (mirrored in the tool manifest: "max: 20") */
const MAX_SEARCH_AGENT_LIMIT = 20;
+const log = debug('lobe-server:agent-management-runtime');
+
export const agentManagementRuntime: ServerRuntimeRegistration = {
factory: (context) => {
if (!context.userId || !context.serverDB) {
@@ -195,7 +198,15 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {
getAgentDetail: async (params: GetAgentDetailParams): Promise<ToolExecutionResult> => {
try {
const agent = await agentModel.getAgentConfigById(params.agentId);
+
if (!agent) {
+ // searchAgent can surface marketplace agents (short-code ids) that
+ // have no local agents row; read their detail through the market
+ // fallback instead of reporting a false "not found" (same behavior
+ // as the client AgentManagerRuntime).
+ const marketDetail = await getMarketAgentDetail(discoverService, params.agentId);
+ if (marketDetail) return marketDetail;
+
return { content: `Agent "${params.agentId}" not found.`, success: false };
}
@@ -477,3 +488,91 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {
},
identifier: AgentManagementIdentifier,
};
+
+/**
+ * Best-effort marketplace detail lookup for ids that have no local agents row.
+ * Mirrors the client `AgentManagerRuntime.getMarketAgentDetail`; market config
+ * almost never carries `agencyConfig`, so the hetero runtime descriptor is
+ * intentionally not mirrored here (apps/server does not depend on
+ * `@lobechat/agent-manager-runtime`).
+ */
+const getMarketAgentDetail = async (
+ discoverService: DiscoverService,
+ agentId: string,
+): Promise<ToolExecutionResult | null> => {
+ let detail: Awaited<ReturnType<DiscoverService['getAssistantDetail']>>;
+ try {
+ detail = await discoverService.getAssistantDetail({
+ identifier: agentId,
+ source: 'new',
+ });
+ } catch (error) {
+ // Market lookup is best-effort: fall through to the local "not found",
+ // but keep the failure observable instead of silent.
+ log(
+ 'getAgentDetail: market fallback lookup failed for identifier=%s: %s',
+ agentId,
+ error instanceof Error ? error.message : error,
+ );
+ return null;
+ }
+
+ const config = detail?.config as Record<string, any> | undefined;
+ if (!detail || !config) return null;
+
+ const plugins = config.plugins?.map((entry: any) => {
+ const { identifier, mode } = parsePluginEntry(entry);
+ return mode === 'pinned' ? identifier : `${identifier} (${mode})`;
+ }) as string[] | undefined;
+
+ // Marketplace configs can carry the model as an object
+ // ({ model, provider, parameters }) β€” extract the nested model/provider so
+ // the LLM-facing summary and GetAgentDetailRender never see "[object
+ // Object]" (same normalization as src/services/agent.ts).
+ let provider = config.provider as string | undefined;
+ let model = config.model as string | undefined;
+ if (model !== null && typeof model === 'object') {
+ const { model: modelName, provider: modelProvider } = model as {
+ model?: string;
+ provider?: string;
+ };
+ model = modelName;
+ provider = provider ?? modelProvider;
+ }
+ const systemRole = config.systemRole as string | undefined;
+
+ const parts: string[] = [];
+ if (detail.title) parts.push(`**${detail.title}**`);
+ if (detail.description) parts.push(detail.description);
+ if (model) parts.push(`Model: ${provider ? `${provider}/` : ''}${model}`);
+ if (plugins?.length) parts.push(`Plugins: ${plugins.join(', ')}`);
+ if (systemRole) parts.push(`System Prompt: ${systemRole}`);
+ parts.push(
+ 'ℹ️ This is a marketplace agent (read-only). Install it into a workspace before editing.',
+ );
+
+ return {
+ content: parts.join('\n'),
+ state: {
+ agentId,
+ config: {
+ model,
+ openingMessage: config.openingMessage as string | undefined,
+ openingQuestions: config.openingQuestions as string[] | undefined,
+ plugins,
+ provider,
+ systemRole,
+ },
+ isMarket: true,
+ meta: {
+ avatar: detail.avatar,
+ backgroundColor: detail.backgroundColor,
+ description: detail.description,
+ tags: detail.tags,
+ title: detail.title,
+ },
+ success: true,
+ },
+ success: true,
+ };
+};
diff --git a/packages/agent-manager-runtime/src/AgentManagerRuntime.ts b/packages/agent-manager-runtime/src/AgentManagerRuntime.ts
index e1eebc56adf..927bfb79b50 100644
--- a/packages/agent-manager-runtime/src/AgentManagerRuntime.ts
+++ b/packages/agent-manager-runtime/src/AgentManagerRuntime.ts
@@ -23,6 +23,7 @@ import {
} from '@lobechat/prompts';
import {
type BuiltinToolResult,
+ type DiscoverAssistantDetail,
getPluginMode,
type HeterogeneousProviderConfig,
parsePluginEntry,
@@ -313,6 +314,12 @@ export class AgentManagerRuntime {
const config = await this.agentService.getAgentConfigById(agentId);
if (!config) {
+ // searchAgents can surface marketplace agents (short-code ids) that
+ // have no local agents row; read their detail through the market
+ // fallback instead of reporting a false "not found".
+ const marketDetail = await this.getMarketAgentDetail(agentId);
+ if (marketDetail) return marketDetail;
+
return {
content: `Agent "${agentId}" not found.`,
success: false,
@@ -619,6 +626,89 @@ export class AgentManagerRuntime {
* Queue prompt mutations by agent so later invocations cannot finish first
* and then be overwritten by an older, slower stream.
*/
+ /**
+ * Marketplace fallback for getAgentDetail. searchAgents surfaces agents
+ * from the external market index (short-code identifiers), but those rows
+ * do not exist in the local agents table β€” reading their detail through
+ * the local path alone reports "not found" even though search found them.
+ * Project the market detail into the same shape getAgentDetail returns so
+ * callers can read (not edit) market agents.
+ */
+ private async getMarketAgentDetail(agentId: string): Promise<BuiltinToolResult | null> {
+ if (!this.discoverService.getAssistantDetail) return null;
+
+ let detail: DiscoverAssistantDetail | undefined;
+ try {
+ detail = await this.discoverService.getAssistantDetail({
+ identifier: agentId,
+ source: 'new',
+ });
+ } catch {
+ // Market lookup is best-effort: fall through to the local "not found".
+ return null;
+ }
+
+ const config = detail?.config as Record<string, any> | undefined;
+ if (!detail || !config) return null;
+
+ const plugins = config.plugins?.map((entry: any) => {
+ const { identifier, mode } = parsePluginEntry(entry);
+ return mode === 'pinned' ? identifier : `${identifier} (${mode})`;
+ }) as string[] | undefined;
+
+ // Marketplace configs can carry the model as an object
+ // ({ model, provider, parameters }) β€” extract the nested model/provider so
+ // the LLM-facing summary and GetAgentDetailRender never see "[object
+ // Object]" (same normalization as src/services/agent.ts).
+ let provider = config.provider as string | undefined;
+ let model = config.model as string | undefined;
+ if (model !== null && typeof model === 'object') {
+ const { model: modelName, provider: modelProvider } = model as {
+ model?: string;
+ provider?: string;
+ };
+ model = modelName;
+ provider = provider ?? modelProvider;
+ }
+ const systemRole = config.systemRole as string | undefined;
+
+ const parts: string[] = [];
+ if (detail.title) parts.push(`**${detail.title}**`);
+ if (detail.description) parts.push(detail.description);
+ if (model) parts.push(`Model: ${provider ? `${provider}/` : ''}${model}`);
+ if (plugins?.length) parts.push(`Plugins: ${plugins.join(', ')}`);
+ if (systemRole) parts.push(`System Prompt: ${systemRole}`);
+ parts.push(
+ 'ℹ️ This is a marketplace agent (read-only). Install it into a workspace before editing.',
+ );
+
+ return {
+ content: parts.join('\n'),
+ state: {
+ agentId,
+ config: {
+ model,
+ openingMessage: config.openingMessage as string | undefined,
+ openingQuestions: config.openingQuestions as string[] | undefined,
+ plugins,
+ provider,
+ ...(config.agencyConfig && { runtime: describeHeterogeneousAgent(config.agencyConfig) }),
+ systemRole,
+ },
+ isMarket: true,
+ meta: {
+ avatar: detail.avatar,
+ backgroundColor: detail.backgroundColor,
+ description: detail.description,
+ tags: detail.tags,
+ title: detail.title,
+ },
+ success: true,
+ },
+ success: true,
+ };
+ }
+
private async enqueuePromptUpdate<T>(agentId: string, update: () => Promise<T>): Promise<T> {
const previousUpdate = AgentManagerRuntime.promptUpdateQueues.get(agentId);
const previousSettled = previousUpdate
diff --git a/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts b/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts
index 5c0724beb13..2ec81a60643 100644
--- a/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts
+++ b/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts
@@ -47,6 +47,7 @@ const mockAgentService: IAgentService = {
};
const mockDiscoverService: IDiscoverService = {
+ getAssistantDetail: vi.fn(),
getAssistantList: vi.fn(),
getMcpList: vi.fn(),
};
@@ -748,6 +749,92 @@ describe('AgentManagerRuntime', () => {
expect(result.success).toBe(true);
expect((result.state as any).config.runtime).toBeUndefined();
});
+
+ it('should fall back to marketplace detail for a market-only agent', async () => {
+ vi.mocked(mockAgentService.getAgentConfigById).mockResolvedValue(null);
+ vi.mocked(mockDiscoverService.getAssistantDetail!).mockResolvedValue({
+ avatar: '🌐',
+ backgroundColor: 'pink',
+ config: {
+ model: 'gpt-4o',
+ openingMessage: 'Hi!',
+ openingQuestions: ['Q1'],
+ plugins: ['web-browsing', 'search'],
+ provider: 'openai',
+ systemRole: 'Market prompt',
+ },
+ description: 'A market agent',
+ identifier: 'mkt12345',
+ related: [],
+ tags: ['ai'],
+ title: 'Market Agent',
+ } as any);
+
+ const result = await runtime.getAgentDetail('mkt12345');
+
+ expect(mockDiscoverService.getAssistantDetail).toHaveBeenCalledWith({
+ identifier: 'mkt12345',
+ source: 'new',
+ });
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Market Agent');
+ expect(result.content).toContain('Market prompt');
+ expect(result.content).toContain('marketplace agent (read-only)');
+ expect(result.state).toMatchObject({
+ agentId: 'mkt12345',
+ isMarket: true,
+ config: expect.objectContaining({ model: 'gpt-4o', systemRole: 'Market prompt' }),
+ meta: expect.objectContaining({ title: 'Market Agent' }),
+ });
+ });
+
+ it('should still return not found when market fallback misses', async () => {
+ vi.mocked(mockAgentService.getAgentConfigById).mockResolvedValue(null);
+ vi.mocked(mockDiscoverService.getAssistantDetail!).mockResolvedValue(undefined);
+
+ const result = await runtime.getAgentDetail('ghost-id');
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('not found');
+ });
+
+ it('should normalize the object-shaped marketplace model before rendering', async () => {
+ vi.mocked(mockAgentService.getAgentConfigById).mockResolvedValue(null);
+ vi.mocked(mockDiscoverService.getAssistantDetail!).mockResolvedValue({
+ avatar: '🌐',
+ config: {
+ model: { model: 'gpt-4o', parameters: { temperature: 0.6 }, provider: 'openai' },
+ plugins: ['web-browsing'],
+ systemRole: 'Market prompt',
+ },
+ description: 'A market agent',
+ identifier: 'mktobj1',
+ related: [],
+ tags: ['ai'],
+ title: 'Object Model Agent',
+ } as any);
+
+ const result = await runtime.getAgentDetail('mktobj1');
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Model: openai/gpt-4o');
+ expect(result.content).not.toContain('[object Object]');
+ expect(result.state).toMatchObject({
+ config: expect.objectContaining({ model: 'gpt-4o', provider: 'openai' }),
+ });
+ });
+
+ it('should still return not found when discover service lacks getAssistantDetail', async () => {
+ vi.mocked(mockAgentService.getAgentConfigById).mockResolvedValue(null);
+ const originalGetAssistantDetail = mockDiscoverService.getAssistantDetail;
+ mockDiscoverService.getAssistantDetail = undefined;
+
+ const result = await runtime.getAgentDetail('no-fallback-id');
+
+ mockDiscoverService.getAssistantDetail = originalGetAssistantDetail;
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('not found');
+ });
});
describe('duplicateAgent', () => {
diff --git a/packages/agent-manager-runtime/src/types.ts b/packages/agent-manager-runtime/src/types.ts
index 3a0264fca00..a50768d68c9 100644
--- a/packages/agent-manager-runtime/src/types.ts
+++ b/packages/agent-manager-runtime/src/types.ts
@@ -1,4 +1,10 @@
-import type { HeterogeneousProviderConfig, LobeAgentConfig, MetaData } from '@lobechat/types';
+import type {
+ AssistantMarketSource,
+ DiscoverAssistantDetail,
+ HeterogeneousProviderConfig,
+ LobeAgentConfig,
+ MetaData,
+} from '@lobechat/types';
import type { PartialDeep } from 'type-fest';
// ==================== Service Interfaces ====================
@@ -45,6 +51,12 @@ 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;