🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(agent-management): surface heterogeneous agent type in searchAgent results (#16292)
Arvin Xu33d836af7871
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.tsindex 9f275e145de..c8698356443 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentManagement.test.ts@@ -217,7 +217,7 @@ describe('agentManagementRuntime', () => {expect(mockQueryAgents).toHaveBeenCalledWith({ keyword: undefined, limit: 20, offset: 0 });expect(result.content).toContain(- 'requested limit 50 exceeds the maximum of 20, so results were capped at 20',+ 'Requested limit 50 exceeds the maximum of 20; results were capped at 20 per call.',);expect(result.state).toMatchObject({ hasMore: false });});@@ -230,7 +230,7 @@ describe('agentManagementRuntime', () => {const result = await runtime.searchAgent({ keyword: 'nonexistent', source: 'user' });expect(result.success).toBe(true);- expect(result.content).toContain('No agents found matching your search criteria.');+ expect(result.content).toContain('No agents matched');});it('explains an out-of-range offset instead of claiming no matches', async () => {@@ -241,7 +241,31 @@ describe('agentManagementRuntime', () => {const result = await runtime.searchAgent({ offset: 200, source: 'user' });expect(result.success).toBe(true);- expect(result.content).toContain('No agents at offset 200; only 37 agents match');+ expect(result.content).toContain('No agents at offset 200; only 37 match');+ });++ it('surfaces heteroType for heterogeneous workspace agents', async () => {+ mockQueryAgents.mockResolvedValue([+ {+ avatar: null,+ backgroundColor: null,+ description: null,+ heteroType: 'claude-code',+ id: 'agent-cc',+ title: 'CC 2号机',+ },+ ]);+ mockCountAgents.mockResolvedValue(1);++ const runtime = createRuntime();+ const result = await runtime.searchAgent({ source: 'user' });++ expect(result.success).toBe(true);+ expect(result.content).toContain('heteroType="claude-code"');+ expect(result.content).toContain('heterogeneous agents');+ expect(result.state).toMatchObject({+ agents: [expect.objectContaining({ id: 'agent-cc', heteroType: 'claude-code' })],+ });});it('searches the marketplace without counting workspace agents', async () => {diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.tsindex ff7570417a5..311fba794cd 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentManagement.ts@@ -10,6 +10,8 @@ import {type UpdateAgentParams,type UpdatePromptParams,} from '@lobechat/builtin-tool-agent-management';+import { searchAgentsResultsPrompt } from '@lobechat/prompts';+import type { HeterogeneousProviderConfig } from '@lobechat/types';import { AgentModel } from '@/database/models/agent';import { PluginModel } from '@/database/models/plugin';@@ -254,6 +256,7 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {avatar?: string | null;backgroundColor?: string | null;description?: string | null;+ heteroType?: HeterogeneousProviderConfig['type'];id: string;isMarket?: boolean;title?: string | null;@@ -298,37 +301,22 @@ export const agentManagementRuntime: ServerRuntimeRegistration = {const shownUserCount = sliced.filter((a) => !a.isMarket).length;const hasMore = offset + shownUserCount < userTotal;- const headerBySource: Record<typeof source, string> = {- all: `Found ${userTotal} agents in your workspace and ${marketTotal} in the marketplace, showing ${sliced.length}:`,- market: `Found ${marketTotal} agents in the marketplace, showing the first ${sliced.length}:`,- user: `Found ${userTotal} agents in your workspace, showing ${offset + 1}-${offset + sliced.length}:`,- };-- const notes: string[] = [];- if (params.limit && params.limit > MAX_SEARCH_AGENT_LIMIT) {- notes.push(- `Note: requested limit ${params.limit} exceeds the maximum of ${MAX_SEARCH_AGENT_LIMIT}, so results were capped at ${MAX_SEARCH_AGENT_LIMIT} per call.`,- );- }- if (hasMore) {- notes.push(- `More workspace agents available: call searchAgent with offset=${offset + shownUserCount}${source === 'all' ? ` and source="user"` : ''} to get the next page.`,- );- }-- let content: string;- if (sliced.length === 0) {- content =- totalCount === 0- ? 'No agents found matching your search criteria.'- : `No agents at offset ${offset}; only ${totalCount} agents match. Retry with a smaller offset.`;- } else {- const list = sliced- .map((a) => `- ${a.title || 'Untitled'} (${a.id})${a.isMarket ? ' [Market]' : ''}`)- .join('\n');- content = `${headerBySource[source]}\n${list}`;- }- if (notes.length > 0) content += `\n\n${notes.join('\n')}`;+ const content = searchAgentsResultsPrompt({+ agents: sliced.map((a) => ({+ description: a.description ?? undefined,+ heteroType: a.heteroType,+ id: a.id,+ isMarket: a.isMarket,+ title: a.title ?? undefined,+ })),+ hasMore,+ marketTotal,+ maxLimit: MAX_SEARCH_AGENT_LIMIT,+ offset,+ requestedLimit: params.limit,+ source,+ userTotal,+ });return {content,diff --git a/packages/agent-manager-runtime/src/AgentManagerRuntime.ts b/packages/agent-manager-runtime/src/AgentManagerRuntime.tsindex 7ae85baaf04..31b8a2e598c 100644--- a/packages/agent-manager-runtime/src/AgentManagerRuntime.ts+++ b/packages/agent-manager-runtime/src/AgentManagerRuntime.ts@@ -15,8 +15,12 @@* (e.g., server-side services vs client-side services).*/import { COMPOSIO_APP_TYPES, LOBEHUB_SKILL_PROVIDERS } from '@lobechat/const';-import { marketToolsResultsPrompt, modelsResultsPrompt } from '@lobechat/prompts';-import type { BuiltinToolResult } from '@lobechat/types';+import {+ marketToolsResultsPrompt,+ modelsResultsPrompt,+ searchAgentsResultsPrompt,+} from '@lobechat/prompts';+import type { BuiltinToolResult, HeterogeneousProviderConfig } from '@lobechat/types';import { getAgentStoreState } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors/selectors';@@ -50,7 +54,6 @@ import type {InstallPluginState,MarketToolItem,SearchAgentParams,- SearchAgentSource,SearchAgentState,SearchMarketToolsParams,SearchMarketToolsState,@@ -414,12 +417,14 @@ export class AgentManagerRuntime {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,@@ -456,37 +461,16 @@ export class AgentManagerRuntime {const shownUserCount = uniqueAgents.filter((a) => !a.isMarket).length;const hasMore = offset + shownUserCount < userTotal;- const headerBySource: Record<SearchAgentSource, string> = {- all: `Found ${userTotal} agents in your workspace and ${marketTotal} in the marketplace, showing ${uniqueAgents.length}:`,- market: `Found ${marketTotal} agents in the marketplace, showing the first ${uniqueAgents.length}:`,- user: `Found ${userTotal} agents in your workspace, showing ${offset + 1}-${offset + uniqueAgents.length}:`,- };-- const notes: string[] = [];- if (params.limit && params.limit > MAX_SEARCH_AGENT_LIMIT) {- notes.push(- `Note: requested limit ${params.limit} exceeds the maximum of ${MAX_SEARCH_AGENT_LIMIT}, so results were capped at ${MAX_SEARCH_AGENT_LIMIT} per call.`,- );- }- if (hasMore) {- notes.push(- `More workspace agents available: call searchAgent with offset=${offset + shownUserCount}${source === 'all' ? ` and source="user"` : ''} to get the next page.`,- );- }-- let content: string;- if (uniqueAgents.length === 0) {- content =- totalCount === 0- ? 'No agents found matching your search criteria.'- : `No agents at offset ${offset}; only ${totalCount} agents match. Retry with a smaller offset.`;- } else {- const agentList = uniqueAgents- .map((a) => `- ${a.title || 'Untitled'} (${a.id})${a.isMarket ? ' [Market]' : ''}`)- .join('\n');- content = `${headerBySource[source]}\n${agentList}`;- }- if (notes.length > 0) content += `\n\n${notes.join('\n')}`;+ const content = searchAgentsResultsPrompt({+ agents: uniqueAgents,+ hasMore,+ marketTotal,+ maxLimit: MAX_SEARCH_AGENT_LIMIT,+ offset,+ requestedLimit: params.limit,+ source,+ userTotal,+ });return {content,diff --git a/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts b/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.tsindex 909374bcf16..95e86afe547 100644--- a/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts+++ b/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts@@ -254,7 +254,9 @@ describe('AgentManagerRuntime', () => {});expect(result.success).toBe(true);- expect(result.content).toContain('Found 2 agents in your workspace, showing 1-2');+ expect(result.content).toContain('Found 2 agents in your workspace, showing 1-2:');+ expect(result.content).toContain('id="agent-1"');+ expect(result.content).toContain('id="agent-2"');expect(result.state).toMatchObject({agents: expect.arrayContaining([expect.objectContaining({ id: 'agent-1', isMarket: false }),@@ -266,6 +268,31 @@ describe('AgentManagerRuntime', () => {});});+ it('should surface heteroType for heterogeneous agents in state and content', async () => {+ vi.mocked(mockAgentService.queryAgents).mockResolvedValue([+ {+ id: 'cc-agent',+ title: 'CC 2号机',+ description: null,+ avatar: null,+ backgroundColor: null,+ heteroType: 'claude-code',+ },+ ] as any);+ vi.mocked(mockAgentService.countAgents).mockResolvedValue(1);++ const result = await runtime.searchAgents({ source: 'user' });++ expect(result.success).toBe(true);+ expect(result.content).toContain('heteroType="claude-code"');+ expect(result.content).toContain('heterogeneous agents');+ expect(result.state).toMatchObject({+ agents: expect.arrayContaining([+ expect.objectContaining({ id: 'cc-agent', heteroType: 'claude-code' }),+ ]),+ });+ });+it('should search marketplace agents', async () => {vi.mocked(mockDiscoverService.getAssistantList).mockResolvedValue({items: [@@ -325,7 +352,7 @@ describe('AgentManagerRuntime', () => {const result = await runtime.searchAgents({ keyword: 'nonexistent', source: 'user' });expect(result.success).toBe(true);- expect(result.content).toContain('No agents found');+ expect(result.content).toContain('No agents matched');});it('should report the real total and a pagination hint when more agents exist', async () => {@@ -342,7 +369,7 @@ describe('AgentManagerRuntime', () => {const result = await runtime.searchAgents({ limit: 20, source: 'user' });expect(result.success).toBe(true);- expect(result.content).toContain('Found 137 agents in your workspace, showing 1-20');+ expect(result.content).toContain('Found 137 agents in your workspace, showing 1-20:');expect(result.content).toContain('call searchAgent with offset=20');expect(result.state).toMatchObject({ hasMore: true, offset: 0, totalCount: 137 });});@@ -365,7 +392,7 @@ describe('AgentManagerRuntime', () => {limit: 20,offset: 20,});- expect(result.content).toContain('Found 50 agents in your workspace, showing 21-40');+ expect(result.content).toContain('Found 50 agents in your workspace, showing 21-40:');expect(result.content).toContain('call searchAgent with offset=40');expect(result.state).toMatchObject({ hasMore: true, offset: 20 });});@@ -390,7 +417,7 @@ describe('AgentManagerRuntime', () => {offset: 0,});expect(result.content).toContain(- 'requested limit 50 exceeds the maximum of 20, so results were capped at 20',+ 'Requested limit 50 exceeds the maximum of 20; results were capped at 20 per call.',);});@@ -401,7 +428,7 @@ describe('AgentManagerRuntime', () => {const result = await runtime.searchAgents({ offset: 200, source: 'user' });expect(result.success).toBe(true);- expect(result.content).toContain('No agents at offset 200; only 37 agents match');+ expect(result.content).toContain('No agents at offset 200; only 37 match');});it('should fall back to item count when marketplace omits totalCount', async () => {diff --git a/packages/agent-manager-runtime/src/types.ts b/packages/agent-manager-runtime/src/types.tsindex 79d286afe25..f0bd2f5e05e 100644--- a/packages/agent-manager-runtime/src/types.ts+++ b/packages/agent-manager-runtime/src/types.ts@@ -1,4 +1,4 @@-import type { LobeAgentConfig, MetaData } from '@lobechat/types';+import type { HeterogeneousProviderConfig, LobeAgentConfig, MetaData } from '@lobechat/types';import type { PartialDeep } from 'type-fest';// ==================== Service Interfaces ====================@@ -142,6 +142,12 @@ export interface AgentSearchItem {avatar?: string;backgroundColor?: string;description?: string;+ /**+ * Heterogeneous agent runtime type (e.g. `claude-code`, `codex`), set only when+ * the agent delegates execution to an external CLI/device runtime. Absent for+ * normal model-runtime agents.+ */+ heteroType?: HeterogeneousProviderConfig['type'];id: string;isMarket?: boolean;title?: string;diff --git a/packages/builtin-tool-agent-management/package.json b/packages/builtin-tool-agent-management/package.jsonindex 4de0a22b02f..27f8eee5290 100644--- a/packages/builtin-tool-agent-management/package.json+++ b/packages/builtin-tool-agent-management/package.json@@ -11,6 +11,7 @@"dependencies": {"@lobechat/agent-manager-runtime": "workspace:*","@lobechat/const": "workspace:*",+ "@lobechat/heterogeneous-agents": "workspace:*","lucide-react": "*","react-router": "*"},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 339d14a0e81..8e0ec597a96 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@@ -1,6 +1,7 @@'use client';import { DEFAULT_AVATAR } from '@lobechat/const';+import { HETEROGENEOUS_TYPE_LABELS } from '@lobechat/heterogeneous-agents';import type { BuiltinRenderProps } from '@lobechat/types';import { Avatar, Flexbox } from '@lobehub/ui';import { createStaticStyles, useTheme } from 'antd-style';@@ -38,6 +39,16 @@ const styles = createStaticStyles(({ css, cssVar }) => ({text-overflow: ellipsis;white-space: nowrap;`,+ heteroBadge: css`+ padding-block: 2px;+ padding-inline: 6px;+ border-radius: 4px;++ font-size: 10px;+ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorFillSecondary};+ `,marketBadge: css`padding-block: 2px;padding-inline: 6px;@@ -84,6 +95,11 @@ export const SearchAgentRender = memo<BuiltinRenderProps<SearchAgentParams, Sear<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>+ )}{agent.isMarket && <span className={styles.marketBadge}>Market</span>}</Flexbox>{agent.description && <span className={styles.description}>{agent.description}</span>}diff --git a/packages/builtin-tool-agent-management/src/manifest.ts b/packages/builtin-tool-agent-management/src/manifest.tsindex 6bf7d9d8b0a..b78818f5047 100644--- a/packages/builtin-tool-agent-management/src/manifest.ts+++ b/packages/builtin-tool-agent-management/src/manifest.ts@@ -242,7 +242,7 @@ export const AgentManagementManifest: BuiltinToolManifest = {// ==================== Search ===================={description:- "Search for agents in your workspace or the marketplace. Use 'user' source to find your own agents, 'market' for marketplace agents, or 'all' for both. Results are paginated: the response reports the real total, and you can page through workspace agents with 'offset'.",+ "Search for agents in your workspace or the marketplace. Use 'user' source to find your own agents, 'market' for marketplace agents, or 'all' for both. Results are paginated: the response reports the real total, and you can page through workspace agents with 'offset'. Each result carries an `origin` (workspace/market) and, for heterogeneous agents, a `heteroType` (e.g. claude-code, codex) — those are backed by an external CLI/device runtime and can execute coding/agentic tasks directly, so you can hand a task to them without further setup.",name: AgentManagementApiName.searchAgent,parameters: {properties: {diff --git a/packages/builtin-tool-agent-management/src/types.ts b/packages/builtin-tool-agent-management/src/types.tsindex 997b2eaa3a9..352f414d267 100644--- a/packages/builtin-tool-agent-management/src/types.ts+++ b/packages/builtin-tool-agent-management/src/types.ts@@ -1,5 +1,5 @@import type { HeteroAgentRuntimeDescriptor } from '@lobechat/agent-manager-runtime';-import type { LobeAgentConfig, MetaData } from '@lobechat/types';+import type { HeterogeneousProviderConfig, LobeAgentConfig, MetaData } from '@lobechat/types';import type { PartialDeep } from 'type-fest';/**@@ -213,6 +213,12 @@ export interface AgentSearchItem {* Agent description*/description?: string;+ /**+ * Heterogeneous agent runtime type (e.g. `claude-code`, `codex`), set only when+ * the agent delegates execution to an external CLI/device runtime. Absent for+ * normal model-runtime agents.+ */+ heteroType?: HeterogeneousProviderConfig['type'];/*** Agent ID (for user agents) or identifier (for market agents)*/diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.tsindex 12f3e0e13b3..42ef117c8af 100644--- a/packages/database/src/models/__tests__/agent.test.ts+++ b/packages/database/src/models/__tests__/agent.test.ts@@ -1685,6 +1685,26 @@ describe('AgentModel', () => {expect(result[0]).toHaveProperty('backgroundColor');});+ it('should derive heteroType from agencyConfig.heterogeneousProvider', async () => {+ await serverDB.insert(agents).values({+ agencyConfig: { heterogeneousProvider: { type: 'claude-code' } },+ id: 'hetero-agent',+ title: 'CC 2号机',+ userId,+ virtual: false,+ });+ await agentModel.create({ title: 'Normal Agent', virtual: false });++ const result = await agentModel.queryAgents();++ const hetero = result.find((a) => a.id === 'hetero-agent');+ const normal = result.find((a) => a.title === 'Normal Agent');+ expect(hetero?.heteroType).toBe('claude-code');+ expect(normal?.heteroType).toBeUndefined();+ // raw agencyConfig must not leak into the result payload+ expect(hetero).not.toHaveProperty('agencyConfig');+ });+it('should exclude virtual agents', async () => {// Create a virtual agentawait agentModel.create({diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.tsindex bce1a07f19e..71c88a166f8 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -214,7 +214,9 @@ export class AgentModel {/*** Query non-virtual agents with optional keyword filter.- * Returns minimal agent info (id, title, description, avatar, backgroundColor).+ * Returns minimal agent info (id, title, description, avatar, backgroundColor),+ * plus a compact `heteroType` derived from `agencyConfig` so callers can tell+ * which results are heterogeneous (external CLI/device) agents.* Excludes virtual agents (like inbox, supervisors, etc).*/queryAgents = async (params?: { keyword?: string; limit?: number; offset?: number }) => {@@ -223,6 +225,7 @@ export class AgentModel {const rows = await this.db.select({+ agencyConfig: agents.agencyConfig,avatar: agents.avatar,backgroundColor: agents.backgroundColor,description: agents.description,@@ -236,7 +239,13 @@ export class AgentModel {.limit(limit).offset(offset);- return rows.map(({ slug, ...row }) => normalizeInboxAgentMeta(row, { slug }));+ // Surface only the hetero runtime type, not the full agencyConfig payload.+ return rows.map(({ slug, agencyConfig, ...row }) =>+ normalizeInboxAgentMeta(+ { ...row, heteroType: agencyConfig?.heterogeneousProvider?.type },+ { slug },+ ),+ );};/**diff --git a/packages/prompts/src/prompts/agentBuilder/index.ts b/packages/prompts/src/prompts/agentBuilder/index.tsindex dbce42ea66a..d6b871a88b0 100644--- a/packages/prompts/src/prompts/agentBuilder/index.ts+++ b/packages/prompts/src/prompts/agentBuilder/index.ts@@ -1,2 +1,3 @@export * from './modelsResultsPrompt';+export * from './searchAgentsResultsPrompt';export * from './toolsResultsPrompt';diff --git a/packages/prompts/src/prompts/agentBuilder/searchAgentsResultsPrompt.test.ts b/packages/prompts/src/prompts/agentBuilder/searchAgentsResultsPrompt.test.tsnew file mode 100644index 00000000000..3dce8fa43ee--- /dev/null+++ b/packages/prompts/src/prompts/agentBuilder/searchAgentsResultsPrompt.test.ts@@ -0,0 +1,88 @@+import { describe, expect, it } from 'vitest';++import { searchAgentsResultsPrompt } from './searchAgentsResultsPrompt';++describe('searchAgentsResultsPrompt', () => {+ it('renders a plain headline plus a compact <agent> element per result', () => {+ const content = searchAgentsResultsPrompt({+ agents: [{ description: 'My CC machine', id: 'agt_1', title: 'CC 2号机' }],+ hasMore: false,+ offset: 0,+ source: 'user',+ userTotal: 1,+ });++ expect(content).toContain('Found 1 agent in your workspace, showing 1-1:');+ expect(content).toContain(+ '<agent id="agt_1" title="CC 2号机" origin="workspace">My CC machine',+ );+ // the result is not wrapped in an XML container+ expect(content).not.toContain('<agentSearchResults');+ });++ it('marks heterogeneous agents and appends a plain Note: guidance line', () => {+ const content = searchAgentsResultsPrompt({+ agents: [{ heteroType: 'claude-code', id: 'agt_cc', title: 'CC 2号机' }],+ source: 'user',+ userTotal: 1,+ });++ expect(content).toContain('heteroType="claude-code"');+ expect(content).not.toContain('<note>');+ expect(content).toContain('\n\nNote: ');+ expect(content).toContain('heterogeneous agents');+ });++ it('tags marketplace agents with market origin', () => {+ const content = searchAgentsResultsPrompt({+ agents: [{ id: 'mkt_1', isMarket: true, title: 'Market Agent' }],+ marketTotal: 5,+ source: 'market',+ });++ expect(content).toContain('Found 5 agents in the marketplace, showing the first 1:');+ expect(content).toContain('origin="market"');+ });++ it('returns a plain empty hint when there are no agents', () => {+ const content = searchAgentsResultsPrompt({ agents: [], source: 'user', userTotal: 0 });++ expect(content).toContain('No agents matched');+ expect(content).not.toContain('<agent');+ });++ it('explains an out-of-range offset instead of claiming no matches', () => {+ const content = searchAgentsResultsPrompt({+ agents: [],+ offset: 200,+ source: 'user',+ userTotal: 37,+ });++ expect(content).toContain('No agents at offset 200; only 37 match');+ });++ it('appends a pagination hint when more workspace agents exist', () => {+ const content = searchAgentsResultsPrompt({+ agents: Array.from({ length: 20 }, (_, i) => ({ id: `agt_${i}`, title: `Agent ${i}` })),+ hasMore: true,+ offset: 0,+ source: 'user',+ userTotal: 137,+ });++ expect(content).toContain('call searchAgent with offset=20');+ });++ it('warns when the requested limit was capped', () => {+ const content = searchAgentsResultsPrompt({+ agents: [{ id: 'agt_1', title: 'Agent One' }],+ maxLimit: 20,+ requestedLimit: 50,+ source: 'user',+ userTotal: 1,+ });++ expect(content).toContain('Requested limit 50 exceeds the maximum of 20');+ });+});diff --git a/packages/prompts/src/prompts/agentBuilder/searchAgentsResultsPrompt.ts b/packages/prompts/src/prompts/agentBuilder/searchAgentsResultsPrompt.tsnew file mode 100644index 00000000000..bf11fae7078--- /dev/null+++ b/packages/prompts/src/prompts/agentBuilder/searchAgentsResultsPrompt.ts@@ -0,0 +1,129 @@+import type { HeterogeneousProviderConfig } from '@lobechat/types';++import { escapeXmlAttr, escapeXmlContent } from '../search/xmlEscape';++export type SearchAgentSource = 'user' | 'market' | 'all';++export interface SearchAgentResultItem {+ /** Short description of what the agent does. */+ description?: string;+ /**+ * Heterogeneous agent runtime type, set only when this agent delegates+ * execution to an external CLI/device runtime (e.g. `claude-code`, `codex`).+ * Absent for normal model-runtime agents.+ */+ heteroType?: HeterogeneousProviderConfig['type'];+ id: string;+ /** Whether the agent comes from the marketplace (vs. the user's workspace). */+ isMarket?: boolean;+ title?: string;+}++export interface SearchAgentsPromptInput {+ agents: SearchAgentResultItem[];+ /** Whether more workspace agents exist beyond the returned page. */+ hasMore?: boolean;+ /** Real count of marketplace matches across all pages. */+ marketTotal?: number;+ /** Max results allowed per call — used to warn when the request was capped. */+ maxLimit?: number;+ /** Number of workspace agents skipped for this page. */+ offset?: number;+ /** The limit the caller requested (to warn when it exceeds `maxLimit`). */+ requestedLimit?: number;+ source: SearchAgentSource;+ /** Real count of workspace matches across all pages. */+ userTotal?: number;+}++const formatAgent = (agent: SearchAgentResultItem): string => {+ const attrs: string[] = [+ `id="${escapeXmlAttr(agent.id)}"`,+ `title="${escapeXmlAttr(agent.title || 'Untitled')}"`,+ `origin="${agent.isMarket ? 'market' : 'workspace'}"`,+ ];++ if (agent.heteroType) attrs.push(`heteroType="${escapeXmlAttr(agent.heteroType)}"`);++ const attrString = attrs.join(' ');+ const content = agent.description ? escapeXmlContent(agent.description) : '';++ return content ? `<agent ${attrString}>${content}</agent>` : `<agent ${attrString} />`;+};++/**+ * Build a search result for the agent-management `searchAgent` tool.+ *+ * The outer summary is a plain sentence; each agent is rendered as a compact+ * `<agent>` XML element to raise semantic density — surfacing its `origin`+ * (workspace vs. market) and, for heterogeneous agents, the `heteroType` so the+ * supervisor can tell at a glance that a result (e.g. a Claude Code machine) can+ * directly execute a handed-off task. Pagination / cap hints follow as plain+ * `Note:` lines after a blank line.+ *+ * @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>+ *+ * 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.+ * ```+ */+export const searchAgentsResultsPrompt = (input: SearchAgentsPromptInput): string => {+ const {+ agents,+ source,+ userTotal = 0,+ marketTotal = 0,+ offset = 0,+ hasMore = false,+ requestedLimit,+ maxLimit,+ } = input;++ const shown = agents.length;+ const plural = (n: number) => (n === 1 ? 'agent' : 'agents');++ let headline: string;+ if (shown === 0) {+ const totalCount = userTotal + marketTotal;+ headline =+ totalCount === 0+ ? 'No agents matched. Try different keywords, or create a new agent.'+ : `No agents at offset ${offset}; only ${totalCount} match. Retry with a smaller offset.`;+ } else if (source === 'market') {+ headline = `Found ${marketTotal} ${plural(marketTotal)} in the marketplace, showing the first ${shown}:`;+ } else if (source === 'all') {+ headline = `Found ${userTotal} ${plural(userTotal)} in your workspace and ${marketTotal} in the marketplace, showing ${shown}:`;+ } else {+ headline = `Found ${userTotal} ${plural(userTotal)} in your workspace, showing ${offset + 1}-${offset + shown}:`;+ }++ const lines = [headline, ...agents.map(formatAgent)];++ const notes: string[] = [];++ if (agents.some((a) => a.heteroType)) {+ notes.push(+ 'Agents with a `heteroType` are heterogeneous agents backed by an external CLI/device runtime (e.g. claude-code, codex). They can execute coding / agentic tasks directly — you can hand a task to such an agent without further setup.',+ );+ }++ if (requestedLimit && maxLimit && requestedLimit > maxLimit) {+ notes.push(+ `Requested limit ${requestedLimit} exceeds the maximum of ${maxLimit}; results were capped at ${maxLimit} per call.`,+ );+ }++ if (hasMore) {+ const shownUserCount = agents.filter((a) => !a.isMarket).length;+ notes.push(+ `More workspace agents available: call searchAgent with offset=${offset + shownUserCount}${source === 'all' ? ' and source="user"' : ''} to get the next page.`,+ );+ }++ const body = lines.join('\n');+ const noteBlock = notes.map((note) => `Note: ${note}`).join('\n');++ return noteBlock ? `${body}\n\n${noteBlock}` : body;+};