🤯 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 builder and group builder
arvinxxd735e2c810b0
diff --git a/packages/database/src/types/chatGroup.ts b/packages/database/src/types/chatGroup.tsindex b6e5253fc87..6682d3b4c15 100644--- a/packages/database/src/types/chatGroup.ts+++ b/packages/database/src/types/chatGroup.ts@@ -2,6 +2,8 @@ export interface ChatGroupConfig {allowDM?: boolean;enableSupervisor?: boolean;maxResponseInRow?: number;+ openingMessage?: string;+ openingQuestions?: string[];orchestratorModel?: string;orchestratorProvider?: string;responseOrder?: 'sequential' | 'natural';diff --git a/packages/prompts/src/prompts/agentBuilder/index.ts b/packages/prompts/src/prompts/agentBuilder/index.tsnew file mode 100644index 00000000000..dbce42ea66a--- /dev/null+++ b/packages/prompts/src/prompts/agentBuilder/index.ts@@ -0,0 +1,2 @@+export * from './modelsResultsPrompt';+export * from './toolsResultsPrompt';diff --git a/packages/prompts/src/prompts/agentBuilder/modelsResultsPrompt.ts b/packages/prompts/src/prompts/agentBuilder/modelsResultsPrompt.tsnew file mode 100644index 00000000000..539b424fc88--- /dev/null+++ b/packages/prompts/src/prompts/agentBuilder/modelsResultsPrompt.ts@@ -0,0 +1,81 @@+import { escapeXmlAttr, escapeXmlContent } from '../search/xmlEscape';++export interface ModelResultItem {+ abilities?: {+ files?: boolean;+ functionCall?: boolean;+ reasoning?: boolean;+ vision?: boolean;+ };+ description?: string;+ id: string;+ name: string;+}++export interface ProviderResultItem {+ id: string;+ models: ModelResultItem[];+ name: string;+}++/**+ * Convert available models results to compact XML format for token efficiency+ *+ * @example+ * ```typescript+ * const providers = [+ * { id: "openai", name: "OpenAI", models: [{ id: "gpt-4o", name: "GPT-4o", abilities: { vision: true } }] }+ * ];+ * const xml = modelsResultsPrompt(providers);+ * // Output:+ * // <availableModels>+ * // <provider id="openai" name="OpenAI">+ * // <model id="gpt-4o" name="GPT-4o" vision="true" />+ * // </provider>+ * // </availableModels>+ * ```+ */+export const modelsResultsPrompt = (providers: ProviderResultItem[]): string => {+ if (providers.length === 0) return '<availableModels />';++ const providerItems = providers+ .map((provider) => {+ const providerAttrs = [+ `id="${escapeXmlAttr(provider.id)}"`,+ `name="${escapeXmlAttr(provider.name)}"`,+ ].join(' ');++ if (provider.models.length === 0) {+ return ` <provider ${providerAttrs} />`;+ }++ const modelItems = provider.models+ .map((model) => {+ const attrs: string[] = [+ `id="${escapeXmlAttr(model.id)}"`,+ `name="${escapeXmlAttr(model.name)}"`,+ ];++ // Add abilities as attributes if present+ if (model.abilities) {+ if (model.abilities.vision) attrs.push('vision="true"');+ if (model.abilities.functionCall) attrs.push('functionCall="true"');+ if (model.abilities.reasoning) attrs.push('reasoning="true"');+ if (model.abilities.files) attrs.push('files="true"');+ }++ const attrString = attrs.join(' ');+ const content = model.description ? escapeXmlContent(model.description) : '';++ return content+ ? ` <model ${attrString}>${content}</model>`+ : ` <model ${attrString} />`;+ })+ .join('\n');++ return ` <provider ${providerAttrs}>\n${modelItems}\n </provider>`;+ })+ .join('\n');++ return `<availableModels>\n${providerItems}\n</availableModels>`;+};diff --git a/packages/prompts/src/prompts/agentBuilder/toolsResultsPrompt.ts b/packages/prompts/src/prompts/agentBuilder/toolsResultsPrompt.tsnew file mode 100644index 00000000000..0ca0d789325--- /dev/null+++ b/packages/prompts/src/prompts/agentBuilder/toolsResultsPrompt.ts@@ -0,0 +1,103 @@+import { escapeXmlAttr, escapeXmlContent } from '../search/xmlEscape';++export interface MarketToolResultItem {+ author?: string;+ description?: string;+ identifier: string;+ installed?: boolean;+ name: string;+ tags?: string[];+}++export interface OfficialToolResultItem {+ author?: string;+ description?: string;+ enabled?: boolean;+ identifier: string;+ installed?: boolean;+ name: string;+ status?: 'connected' | 'error' | 'pending_auth';+ type: 'builtin' | 'klavis';+}++/**+ * Convert market tools search results to compact XML format for token efficiency+ *+ * @example+ * ```typescript+ * const tools = [+ * { identifier: "search-engine", name: "Search Engine", installed: true, description: "Web search" }+ * ];+ * const xml = marketToolsResultsPrompt(tools);+ * // Output:+ * // <marketTools>+ * // <tool id="search-engine" name="Search Engine" installed="true">Web search</tool>+ * // </marketTools>+ * ```+ */+export const marketToolsResultsPrompt = (tools: MarketToolResultItem[]): string => {+ if (tools.length === 0) return '<marketTools />';++ const items = tools+ .map((tool) => {+ const attrs: string[] = [+ `id="${escapeXmlAttr(tool.identifier)}"`,+ `name="${escapeXmlAttr(tool.name)}"`,+ ];++ if (tool.installed) attrs.push('installed="true"');+ if (tool.author) attrs.push(`author="${escapeXmlAttr(tool.author)}"`);+ if (tool.tags && tool.tags.length > 0) {+ attrs.push(`tags="${escapeXmlAttr(tool.tags.join(', '))}"`);+ }++ const attrString = attrs.join(' ');+ const content = tool.description ? escapeXmlContent(tool.description) : '';++ return content ? ` <tool ${attrString}>${content}</tool>` : ` <tool ${attrString} />`;+ })+ .join('\n');++ return `<marketTools>\n${items}\n</marketTools>`;+};++/**+ * Convert official tools search results to compact XML format for token efficiency+ *+ * @example+ * ```typescript+ * const tools = [+ * { identifier: "web-browsing", name: "Web Browsing", type: "builtin", enabled: true }+ * ];+ * const xml = officialToolsResultsPrompt(tools);+ * // Output:+ * // <officialTools>+ * // <tool id="web-browsing" name="Web Browsing" type="builtin" enabled="true" />+ * // </officialTools>+ * ```+ */+export const officialToolsResultsPrompt = (tools: OfficialToolResultItem[]): string => {+ if (tools.length === 0) return '<officialTools />';++ const items = tools+ .map((tool) => {+ const attrs: string[] = [+ `id="${escapeXmlAttr(tool.identifier)}"`,+ `name="${escapeXmlAttr(tool.name)}"`,+ `type="${escapeXmlAttr(tool.type)}"`,+ ];++ if (tool.enabled) attrs.push('enabled="true"');+ if (tool.installed) attrs.push('installed="true"');+ if (tool.status) attrs.push(`status="${escapeXmlAttr(tool.status)}"`);+ if (tool.author) attrs.push(`author="${escapeXmlAttr(tool.author)}"`);++ const attrString = attrs.join(' ');+ const content = tool.description ? escapeXmlContent(tool.description) : '';++ return content ? ` <tool ${attrString}>${content}</tool>` : ` <tool ${attrString} />`;+ })+ .join('\n');++ return `<officialTools>\n${items}\n</officialTools>`;+};diff --git a/packages/prompts/src/prompts/agentGroup/__snapshots__/index.test.ts.snap b/packages/prompts/src/prompts/agentGroup/__snapshots__/index.test.ts.snapnew file mode 100644index 00000000000..b66876c8599--- /dev/null+++ b/packages/prompts/src/prompts/agentGroup/__snapshots__/index.test.ts.snap@@ -0,0 +1,88 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`buildGroupMembersXml > should build XML for group supervisor agents 1`] = `+" <member name="创意总监" id="agt_xxx" />+ <member name="设计师" id="agt_yyy" />"+`;++exports[`buildGroupMembersXml > should handle empty agents array 1`] = `""`;++exports[`buildGroupMembersXml > should use agent id as fallback when title is missing 1`] = `+" <member name="agt_xxx" id="agt_xxx" />+ <member name="agt_yyy" id="agt_yyy" />"+`;++exports[`formatAgentProfile > should format agent with all fields 1`] = `+"# Agent: Backend Developer++- **ID**: agent-backend+- **Description**: Expert in backend development+- **Model**: gpt-4++## System Role++You are a backend developer expert."+`;++exports[`formatAgentProfile > should show N/A for missing optional fields 1`] = `+"# Agent: Untitled Agent++- **ID**: agent-123+- **Description**: N/A+- **Model**: Unknown Model++## System Role++N/A"+`;++exports[`formatAgentProfile > should use default title when title is missing 1`] = `+"# Agent: Untitled Agent++- **ID**: agent-123+- **Description**: N/A+- **Model**: Unknown Model++## System Role++N/A"+`;++exports[`formatGroupMembers > should format members list in XML format 1`] = `+" <member name="Supervisor" id="agt_supervisor" />+ <member name="Writer" id="agt_writer" />+ <member name="Editor" id="agt_editor" />"+`;++exports[`formatGroupMembers > should handle empty members array 1`] = `""`;++exports[`formatGroupMembers > should mark current agent with you attribute 1`] = `+" <member name="Supervisor" id="agt_supervisor" />+ <member name="Editor" id="agt_editor" you="true" />"+`;++exports[`groupContextTemplate > should match snapshot 1`] = `+"You are "{{AGENT_NAME}}", acting as a {{AGENT_ROLE}} in the multi-agent group "{{GROUP_TITLE}}".+Your internal agent ID is {{AGENT_ID}} (for system use only, never expose to users).++<critical_output_rules>+IMPORTANT: Your responses must contain ONLY your actual reply content.+- Messages in conversation history start with '<speaker name="..." />' - this identifies who sent each message+- NEVER start your response with '<speaker' tag - the system adds this automatically+- Just output your actual response content directly+</critical_output_rules>++<group_description>The following describes the purpose and goals of this agent group:++{{SYSTEM_PROMPT}}+</group_description>++<group_participants>The following agents are available in this group:++{{GROUP_MEMBERS}}+</group_participants>++<identity_rules>+- NEVER expose or display agent IDs to users - always refer to agents by their names+</identity_rules>"+`;diff --git a/packages/prompts/src/prompts/agentGroup/agentProfile.ts b/packages/prompts/src/prompts/agentGroup/agentProfile.tsnew file mode 100644index 00000000000..236a417d979--- /dev/null+++ b/packages/prompts/src/prompts/agentGroup/agentProfile.ts@@ -0,0 +1,53 @@+/**+ * Agent Profile Formatting+ *+ * Utility for formatting agent information into human-readable profile text.+ * Used by getAgentInfo tool to return agent details to supervisor.+ */++export interface AgentProfileInfo {+ avatar?: string | null;+ description?: string | null;+ id: string;+ model?: string | null;+ provider?: string | null;+ systemRole?: string | null;+ title?: string | null;+}++/**+ * Agent profile template+ *+ * Variables:+ * - {{title}} - Agent's display name+ * - {{id}} - Agent's ID+ * - {{description}} - Agent's description+ * - {{model}} - Model used by agent+ * - {{systemRole}} - Agent's system role (truncated if > 500 chars)+ */+const AGENT_PROFILE_TEMPLATE = `# Agent: {{title}}++- **ID**: {{id}}+- **Description**: {{description}}+- **Model**: {{model}}++## System Role++{{systemRole}}`;++/**+ * Format agent information into a human-readable profile text+ * Used by getAgentInfo tool to return agent details to supervisor+ */+export const formatAgentProfile = (agent: AgentProfileInfo): string => {+ const systemRole =+ agent.systemRole && agent.systemRole.length > 500+ ? agent.systemRole.slice(0, 500) + '... (truncated)'+ : agent.systemRole;++ return AGENT_PROFILE_TEMPLATE.replace('{{title}}', agent.title || 'Untitled Agent')+ .replace('{{id}}', agent.id)+ .replace('{{description}}', agent.description || 'N/A')+ .replace('{{model}}', agent.model || 'Unknown Model')+ .replace('{{systemRole}}', systemRole || 'N/A');+};diff --git a/packages/prompts/src/prompts/agentGroup/groupContext.ts b/packages/prompts/src/prompts/agentGroup/groupContext.tsnew file mode 100644index 00000000000..593241a0025--- /dev/null+++ b/packages/prompts/src/prompts/agentGroup/groupContext.ts@@ -0,0 +1,105 @@+/**+ * Group Context Template+ *+ * Template for injecting group context into participant agents' system role.+ * Used by GroupContextInjector in context-engine.+ *+ * Format follows the same structure as group-supervisor systemRole.+ */++/**+ * Group member info for context injection+ */+export interface GroupContextMemberInfo {+ id: string;+ name: string;+ role: 'supervisor' | 'participant';+}++export const groupContextTemplate = `You are "{{AGENT_NAME}}", acting as a {{AGENT_ROLE}} in the multi-agent group "{{GROUP_TITLE}}".+Your internal agent ID is {{AGENT_ID}} (for system use only, never expose to users).++<critical_output_rules>+IMPORTANT: Your responses must contain ONLY your actual reply content.+- Messages in conversation history start with '<speaker name="..." />' - this identifies who sent each message+- NEVER start your response with '<speaker' tag - the system adds this automatically+- Just output your actual response content directly+</critical_output_rules>++<group_description>The following describes the purpose and goals of this agent group:++{{SYSTEM_PROMPT}}+</group_description>++<group_participants>The following agents are available in this group:++{{GROUP_MEMBERS}}+</group_participants>++<identity_rules>+- NEVER expose or display agent IDs to users - always refer to agents by their names+</identity_rules>`;++/**+ * Agent info for group supervisor context+ */+export interface GroupSupervisorAgentInfo {+ id: string;+ title?: string | null;+}++/**+ * Build group members XML for group-supervisor systemRole+ *+ * @param agents - List of available agents in the group+ * @returns Formatted XML string for {{GROUP_MEMBERS}} placeholder+ *+ * @example+ * ```typescript+ * const agents = [+ * { id: 'agt_xxx', title: '创意总监' },+ * { id: 'agt_yyy', title: '设计师' },+ * ];+ * const xml = buildGroupMembersXml(agents);+ * // Returns:+ * // <member name="创意总监" id="agt_xxx" />+ * // <member name="设计师" id="agt_yyy" />+ * ```+ */+export const buildGroupMembersXml = (agents: GroupSupervisorAgentInfo[]): string => {+ return agents+ .map((agent) => ` <member name="${agent.title || agent.id}" id="${agent.id}" />`)+ .join('\n');+};++/**+ * Format group members list for {{GROUP_MEMBERS}} placeholder replacement+ * Uses XML format consistent with group-supervisor systemRole+ *+ * @param members - List of group members+ * @param currentAgentId - Current agent's ID (will be marked with "you" attribute)+ * @returns Formatted members string in XML format for template replacement+ *+ * @example+ * ```typescript+ * const members = [+ * { id: 'agt_supervisor', name: 'Supervisor', role: 'supervisor' },+ * { id: 'agt_editor', name: 'Editor', role: 'participant' },+ * ];+ * const formatted = formatGroupMembers(members, 'agt_editor');+ * // Returns:+ * // <member name="Supervisor" id="agt_supervisor" />+ * // <member name="Editor" id="agt_editor" you="true" />+ * ```+ */+export const formatGroupMembers = (+ members: GroupContextMemberInfo[],+ currentAgentId?: string,+): string => {+ return members+ .map((m) => {+ const youAttr = m.id === currentAgentId ? ' you="true"' : '';+ return ` <member name="${m.name}" id="${m.id}"${youAttr} />`;+ })+ .join('\n');+};diff --git a/packages/prompts/src/prompts/agentGroup/index.test.ts b/packages/prompts/src/prompts/agentGroup/index.test.tsnew file mode 100644index 00000000000..358e2fb49c8--- /dev/null+++ b/packages/prompts/src/prompts/agentGroup/index.test.ts@@ -0,0 +1,113 @@+import { describe, expect, it } from 'vitest';++import { formatAgentProfile } from './agentProfile';+import { buildGroupMembersXml, formatGroupMembers, groupContextTemplate } from './groupContext';++describe('formatAgentProfile', () => {+ it('should format agent with all fields', () => {+ const agent = {+ description: 'Expert in backend development',+ id: 'agent-backend',+ model: 'gpt-4',+ systemRole: 'You are a backend developer expert.',+ title: 'Backend Developer',+ };++ expect(formatAgentProfile(agent)).toMatchSnapshot();+ });++ it('should use default title when title is missing', () => {+ const agent = {+ id: 'agent-123',+ title: null,+ };++ expect(formatAgentProfile(agent)).toMatchSnapshot();+ });++ it('should show N/A for missing optional fields', () => {+ const agent = {+ id: 'agent-123',+ };++ expect(formatAgentProfile(agent)).toMatchSnapshot();+ });++ it('should truncate systemRole longer than 500 characters', () => {+ const longSystemRole = 'A'.repeat(600);+ const agent = {+ id: 'agent-123',+ systemRole: longSystemRole,+ title: 'Test Agent',+ };++ const result = formatAgentProfile(agent);+ expect(result).toContain('A'.repeat(500));+ expect(result).toContain('... (truncated)');+ expect(result).not.toContain('A'.repeat(501));+ });++ it('should not truncate systemRole with exactly 500 characters', () => {+ const exactSystemRole = 'B'.repeat(500);+ const agent = {+ id: 'agent-123',+ systemRole: exactSystemRole,+ };++ const result = formatAgentProfile(agent);+ expect(result).toContain('B'.repeat(500));+ expect(result).not.toContain('... (truncated)');+ });+});++describe('groupContextTemplate', () => {+ it('should match snapshot', () => {+ expect(groupContextTemplate).toMatchSnapshot();+ });+});++describe('formatGroupMembers', () => {+ it('should format members list in XML format', () => {+ const members = [+ { id: 'agt_supervisor', name: 'Supervisor', role: 'supervisor' as const },+ { id: 'agt_writer', name: 'Writer', role: 'participant' as const },+ { id: 'agt_editor', name: 'Editor', role: 'participant' as const },+ ];++ expect(formatGroupMembers(members)).toMatchSnapshot();+ });++ it('should mark current agent with you attribute', () => {+ const members = [+ { id: 'agt_supervisor', name: 'Supervisor', role: 'supervisor' as const },+ { id: 'agt_editor', name: 'Editor', role: 'participant' as const },+ ];++ expect(formatGroupMembers(members, 'agt_editor')).toMatchSnapshot();+ });++ it('should handle empty members array', () => {+ expect(formatGroupMembers([])).toMatchSnapshot();+ });+});++describe('buildGroupMembersXml', () => {+ it('should build XML for group supervisor agents', () => {+ const agents = [+ { id: 'agt_xxx', title: '创意总监' },+ { id: 'agt_yyy', title: '设计师' },+ ];++ expect(buildGroupMembersXml(agents)).toMatchSnapshot();+ });++ it('should use agent id as fallback when title is missing', () => {+ const agents = [{ id: 'agt_xxx', title: null }, { id: 'agt_yyy' }];++ expect(buildGroupMembersXml(agents)).toMatchSnapshot();+ });++ it('should handle empty agents array', () => {+ expect(buildGroupMembersXml([])).toMatchSnapshot();+ });+});diff --git a/packages/prompts/src/prompts/agentGroup/index.ts b/packages/prompts/src/prompts/agentGroup/index.tsnew file mode 100644index 00000000000..c91f1c5de20--- /dev/null+++ b/packages/prompts/src/prompts/agentGroup/index.ts@@ -0,0 +1,14 @@+/**+ * Agent Group Prompts+ *+ * Utility functions and templates for multi-agent group orchestration scenarios.+ */++export { type AgentProfileInfo, formatAgentProfile } from './agentProfile';+export {+ buildGroupMembersXml,+ formatGroupMembers,+ type GroupContextMemberInfo,+ groupContextTemplate,+ type GroupSupervisorAgentInfo,+} from './groupContext';diff --git a/packages/prompts/src/prompts/index.ts b/packages/prompts/src/prompts/index.tsindex 5ad8c8ae6f7..eb62c0e6a35 100644--- a/packages/prompts/src/prompts/index.ts+++ b/packages/prompts/src/prompts/index.ts@@ -1,3 +1,5 @@+export * from './agentBuilder';+export * from './agentGroup';export * from './chatMessages';export * from './files';export * from './groupChat';diff --git a/packages/prompts/src/prompts/plugin/index.ts b/packages/prompts/src/prompts/plugin/index.tsindex a3d1e9b5cb4..8ee6d950bce 100644--- a/packages/prompts/src/prompts/plugin/index.ts+++ b/packages/prompts/src/prompts/plugin/index.ts@@ -7,3 +7,5 @@ ${toolsPrompts(tools)}return prompt.trim();};++export { type API, apiPrompt, type Tool, toolPrompt, toolsPrompts } from './tools';\ No newline at end of filediff --git a/packages/types/src/discover/assistants.ts b/packages/types/src/discover/assistants.tsindex 46fda44cc71..a63b0ba1eec 100644--- a/packages/types/src/discover/assistants.ts+++ b/packages/types/src/discover/assistants.ts@@ -35,18 +35,23 @@ export enum AssistantNavKey {Overview = 'overview',Related = 'related',SystemRole = 'systemRole',- Version = 'version'+ Version = 'version',}+export type AgentStatus = 'published' | 'unpublished' | 'archived' | 'deprecated';+export interface DiscoverAssistantItem extends Omit<LobeAgentSettings, 'meta'>, MetaData {author: string;category?: AssistantCategory;createdAt: string;homepage: string;identifier: string;+ installCount?: number;knowledgeCount: number;pluginCount: number;+ status?: AgentStatus;tokenUsage: number;+ userName?: string;}export type AssistantMarketSource = 'legacy' | 'new';@@ -73,6 +78,7 @@ export interface AssistantListResponse {export interface DiscoverAssistantDetail extends DiscoverAssistantItem {currentVersion?: string;+ editorData?: any;examples?: FewShots;related: DiscoverAssistantItem[];summary?: string;@@ -83,6 +89,6 @@ export interface DiscoverAssistantVersion {createdAt?: string;isLatest?: boolean;isValidated?: boolean;- status?: 'published' | 'unpublished' | 'archived' | 'deprecated';+ status?: AgentStatus;version: string;}diff --git a/packages/types/src/discover/index.ts b/packages/types/src/discover/index.tsindex f776a539639..bfeef3ca258 100644--- a/packages/types/src/discover/index.ts+++ b/packages/types/src/discover/index.ts@@ -1,3 +1,5 @@+import { DiscoverAssistantItem } from './assistants';+export * from './assistants';export * from './mcp';export * from './models';@@ -11,6 +13,7 @@ export enum DiscoverTab {Models = 'model',Plugins = 'plugin',Providers = 'provider',+ User = 'user',}export type IdentifiersResponse = {@@ -31,3 +34,31 @@ export enum CacheRevalidate {List = 3600,Details = 43_200,}++/**+ * User profile information for discover pages+ */+export interface DiscoverUserInfo {+ avatarUrl: string | null;+ bannerUrl: string | null;+ createdAt: string;+ description: string | null;+ displayName: string | null;+ id: number;+ namespace: string;+ socialLinks: {+ github?: string;+ twitter?: string;+ website?: string;+ } | null;+ type: string | null;+ userName: string | null;+}++/**+ * User profile with their published agents+ */+export interface DiscoverUserProfile {+ agents: DiscoverAssistantItem[];+ user: DiscoverUserInfo;+}