Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: add the agents and agents group fork feature (#11652)

Shinji-Lib1c3b83e42aa
diff --git a/package.json b/package.json
index 536569b5707..016549c7a4c 100644
--- a/package.json
+++ b/package.json
@@ -205,7 +205,7 @@
"@lobehub/desktop-ipc-typings": "workspace:*",
"@lobehub/editor": "^3.11.0",
"@lobehub/icons": "^4.0.2",
- "@lobehub/market-sdk": "0.29.0",
+ "@lobehub/market-sdk": "0.29.1",
"@lobehub/tts": "^4.0.2",
"@lobehub/ui": "^4.22.0",
"@modelcontextprotocol/sdk": "^1.25.1",
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.ts
index 1c608a36773..3fc2946af64 100644
--- a/packages/database/src/models/agent.ts
+++ b/packages/database/src/models/agent.ts
@@ -1,6 +1,6 @@
import { getAgentPersistConfig } from '@lobechat/builtin-agents';
import { INBOX_SESSION_ID } from '@lobechat/const';
-import { and, desc, eq, ilike, inArray, isNull, or } from 'drizzle-orm';
+import { and, desc, eq, ilike, inArray, isNull, or, sql } from 'drizzle-orm';
import type { PartialDeep } from 'type-fest';
import { merge } from '@/utils/merge';
@@ -379,6 +379,23 @@ export class AgentModel {
return result?.id ?? null;
};
+ /**
+ * Get an agent by the forkedFromIdentifier stored in params
+ * @param forkedFromIdentifier - The source agent's market identifier
+ * @returns agent id if exists, null otherwise
+ */
+ getAgentByForkedFromIdentifier = async (forkedFromIdentifier: string): Promise<string | null> => {
+ const result = await this.db.query.agents.findFirst({
+ columns: { id: true },
+ orderBy: (agents, { desc }) => [desc(agents.updatedAt)],
+ where: and(
+ eq(agents.userId, this.userId),
+ sql`${agents.params}->>'forkedFromIdentifier' = ${forkedFromIdentifier}`,
+ ),
+ });
+ return result?.id ?? null;
+ };
+
updateConfig = async (agentId: string, data: PartialDeep<AgentItem> | undefined | null) => {
if (!data || Object.keys(data).length === 0) return;
diff --git a/packages/database/src/models/chatGroup.ts b/packages/database/src/models/chatGroup.ts
index a4f5d2cae01..431aa8fdc85 100644
--- a/packages/database/src/models/chatGroup.ts
+++ b/packages/database/src/models/chatGroup.ts
@@ -1,4 +1,4 @@
-import { and, desc, eq, inArray } from 'drizzle-orm';
+import { and, desc, eq, inArray, sql } from 'drizzle-orm';
import {
ChatGroupAgentItem,
@@ -35,6 +35,23 @@ export class ChatGroupModel {
});
}
+ /**
+ * Get a chat group by the forkedFromIdentifier stored in config
+ * @param forkedFromIdentifier - The source group's market identifier
+ * @returns group id if exists, null otherwise
+ */
+ async getGroupByForkedFromIdentifier(forkedFromIdentifier: string): Promise<string | null> {
+ const result = await this.db.query.chatGroups.findFirst({
+ columns: { id: true },
+ orderBy: [desc(chatGroups.updatedAt)],
+ where: and(
+ eq(chatGroups.userId, this.userId),
+ sql`${chatGroups.config}->>'forkedFromIdentifier' = ${forkedFromIdentifier}`,
+ ),
+ });
+ return result?.id ?? null;
+ }
+
async queryWithMemberDetails(): Promise<any[]> {
const groups = await this.query();
if (groups.length === 0) return [];
diff --git a/packages/database/src/types/chatGroup.ts b/packages/database/src/types/chatGroup.ts
index 083acbdb115..d990215ef41 100644
--- a/packages/database/src/types/chatGroup.ts
+++ b/packages/database/src/types/chatGroup.ts
@@ -1,5 +1,6 @@
export interface ChatGroupConfig {
allowDM?: boolean;
+ forkedFromIdentifier?: string;
openingMessage?: string;
openingQuestions?: string[];
revealDM?: boolean;
diff --git a/packages/types/package.json b/packages/types/package.json
index d328155d413..5a89ba33e44 100644
--- a/packages/types/package.json
+++ b/packages/types/package.json
@@ -8,7 +8,7 @@
"@lobechat/python-interpreter": "workspace:*",
"@lobechat/web-crawler": "workspace:*",
"@lobehub/chat-plugin-sdk": "^1.32.4",
- "@lobehub/market-sdk": "0.29.0",
+ "@lobehub/market-sdk": "0.29.1",
"@lobehub/market-types": "^1.12.3",
"model-bank": "workspace:*",
"type-fest": "^4.41.0",
diff --git a/packages/types/src/agentGroup/index.ts b/packages/types/src/agentGroup/index.ts
index 785fe28426a..d7831a9e054 100644
--- a/packages/types/src/agentGroup/index.ts
+++ b/packages/types/src/agentGroup/index.ts
@@ -13,6 +13,7 @@ export interface LobeChatGroupMetaConfig {
export interface LobeChatGroupChatConfig {
allowDM?: boolean;
+ forkedFromIdentifier?: string;
openingMessage?: string;
openingQuestions?: string[];
revealDM?: boolean;
@@ -25,6 +26,7 @@ export type LobeChatGroupConfig = LobeChatGroupChatConfig;
// Zod schema for ChatGroupConfig (database insert)
export const ChatGroupConfigSchema = z.object({
allowDM: z.boolean().optional(),
+ forkedFromIdentifier: z.string().optional(),
openingMessage: z.string().optional(),
openingQuestions: z.array(z.string()).optional(),
revealDM: z.boolean().optional(),
diff --git a/packages/types/src/discover/assistants.ts b/packages/types/src/discover/assistants.ts
index 5f052eddf31..12858f42eb8 100644
--- a/packages/types/src/discover/assistants.ts
+++ b/packages/types/src/discover/assistants.ts
@@ -48,6 +48,15 @@ export interface DiscoverAssistantItem extends Omit<LobeAgentSettings, 'meta'>,
author: string;
category?: AssistantCategory;
createdAt: string;
+ /**
+ * Fork count - number of times this agent has been forked
+ */
+ forkCount?: number;
+ /**
+ * Forked from agent ID - ID of the source agent if this is a fork
+ * null means this is an original agent
+ */
+ forkedFromAgentId?: number | null;
homepage: string;
identifier: string;
installCount?: number;
diff --git a/packages/types/src/discover/fork.ts b/packages/types/src/discover/fork.ts
new file mode 100644
index 00000000000..8abcd1dbce9
--- /dev/null
+++ b/packages/types/src/discover/fork.ts
@@ -0,0 +1,163 @@
+/**
+ * Fork-related types for agents and agent groups
+ */
+
+/**
+ * Fork request parameters for Agent
+ */
+export interface AgentForkRequest {
+ /** New agent identifier (required, must be globally unique) */
+ identifier: string;
+ /** New agent name (optional, defaults to "{original name} (Fork)") */
+ name?: string;
+ /** Status (optional, defaults to 'published') */
+ status?: 'published' | 'unpublished' | 'archived' | 'deprecated';
+ /** Version number to fork (optional, defaults to current version) */
+ versionNumber?: number;
+ /** Visibility (optional, defaults to 'public') */
+ visibility?: 'public' | 'private' | 'internal';
+}
+
+/**
+ * Fork response for Agent
+ */
+export interface AgentForkResponse {
+ /** Newly created agent */
+ agent: {
+ createdAt: string;
+ forkedFromAgentId: number;
+ id: number;
+ identifier: string;
+ name: string;
+ ownerId: number;
+ updatedAt: string;
+ };
+ /** Source agent information */
+ source: {
+ agentId: number;
+ identifier: string;
+ versionNumber: number;
+ };
+ /** Newly created version */
+ version: {
+ agentId: number;
+ createdAt: string;
+ id: number;
+ versionNumber: number;
+ };
+}
+
+/**
+ * Fork item for list display
+ */
+export interface AgentForkItem {
+ createdAt: string;
+ forkCount: number;
+ id: number;
+ identifier: string;
+ name: string;
+ ownerId: number;
+ ownerName?: string;
+ status?: string;
+ visibility?: string;
+}
+
+/**
+ * Forks list response
+ */
+export interface AgentForksResponse {
+ forks: AgentForkItem[];
+ totalCount: number;
+}
+
+/**
+ * Fork source response
+ */
+export interface AgentForkSourceResponse {
+ source: AgentForkItem | null;
+}
+
+/**
+ * Fork request parameters for Agent Group
+ */
+export interface AgentGroupForkRequest {
+ /** New group identifier (required, must be globally unique) */
+ identifier: string;
+ /** New group name (optional, defaults to "{original name} (Fork)") */
+ name?: string;
+ /** Status (optional, defaults to 'published') */
+ status?: 'published' | 'unpublished' | 'archived' | 'deprecated';
+ /** Version number to fork (optional, defaults to current version) */
+ versionNumber?: number;
+ /** Visibility (optional, defaults to 'public') */
+ visibility?: 'public' | 'private' | 'internal';
+}
+
+/**
+ * Fork response for Agent Group
+ */
+export interface AgentGroupForkResponse {
+ /** Newly created agent group */
+ group: {
+ createdAt: string;
+ forkedFromGroupId: number;
+ id: number;
+ identifier: string;
+ name: string;
+ ownerId: number;
+ updatedAt: string;
+ };
+ /** Newly created group version */
+ groupVersion: {
+ agentGroupId: number;
+ createdAt: string;
+ id: number;
+ versionNumber: number;
+ };
+ /** Copied member agents */
+ memberAgents: Array<{
+ id: number;
+ identifier: string;
+ name: string;
+ role: string;
+ }>;
+ /** Copied member versions */
+ memberVersions: Array<{
+ agentForGroupId: number;
+ id: number;
+ versionNumber: number;
+ }>;
+ /** Source group information */
+ source: {
+ groupId: number;
+ identifier: string;
+ versionNumber: number;
+ };
+}
+
+/**
+ * Fork item for Agent Group list display
+ */
+export interface AgentGroupForkItem {
+ createdAt: string;
+ forkCount: number;
+ id: number;
+ identifier: string;
+ name: string;
+ ownerId: number;
+}
+
+/**
+ * Agent Group forks list response
+ */
+export interface AgentGroupForksResponse {
+ forks: AgentGroupForkItem[];
+ totalCount: number;
+}
+
+/**
+ * Agent Group fork source response
+ */
+export interface AgentGroupForkSourceResponse {
+ source: AgentGroupForkItem | null;
+}
diff --git a/packages/types/src/discover/groupAgents.ts b/packages/types/src/discover/groupAgents.ts
index dc6938fa0b6..d9fc238ed25 100644
--- a/packages/types/src/discover/groupAgents.ts
+++ b/packages/types/src/discover/groupAgents.ts
@@ -42,6 +42,10 @@ export type GroupAgentCategory =
* Group Agent Config - similar to LobeAgentConfig but for groups
*/
export interface GroupAgentConfig {
+ /**
+ * Additional configuration
+ */
+ [key: string]: any;
/**
* Opening message when starting a conversation with the group
*/
@@ -54,10 +58,6 @@ export interface GroupAgentConfig {
* System role/prompt for the group
*/
systemRole?: string;
- /**
- * Additional configuration
- */
- [key: string]: any;
}
/**
@@ -71,6 +71,15 @@ export interface DiscoverGroupAgentItem extends MetaData {
config?: GroupAgentConfig;
createdAt: string;
description?: string;
+ /**
+ * Fork count - number of times this agent group has been forked
+ */
+ forkCount?: number;
+ /**
+ * Forked from group ID - ID of the source agent group if this is a fork
+ * null means this is an original agent group
+ */
+ forkedFromGroupId?: number | null;
homepage?: string;
identifier: string;
installCount?: number;
diff --git a/packages/types/src/discover/index.ts b/packages/types/src/discover/index.ts
index dd6f5ba3b29..67610030027 100644
--- a/packages/types/src/discover/index.ts
+++ b/packages/types/src/discover/index.ts
@@ -2,6 +2,7 @@ import { DiscoverAssistantItem } from './assistants';
import { DiscoverGroupAgentItem } from './groupAgents';
export * from './assistants';
+export * from './fork';
export * from './groupAgents';
export * from './mcp';
export * from './models';
@@ -66,5 +67,13 @@ export interface DiscoverUserInfo {
export interface DiscoverUserProfile {
agentGroups?: DiscoverGroupAgentItem[];
agents: DiscoverAssistantItem[];
+ /**
+ * Agent groups forked by the user
+ */
+ forkedAgentGroups?: DiscoverGroupAgentItem[];
+ /**
+ * Agents forked by the user
+ */
+ forkedAgents?: DiscoverAssistantItem[];
user: DiscoverUserInfo;
}
diff --git a/src/app/[variants]/(main)/community/(detail)/agent/features/Header.tsx b/src/app/[variants]/(main)/community/(detail)/agent/features/Header.tsx
index 6dfa3ce2347..9c688d96362 100644
--- a/src/app/[variants]/(main)/community/(detail)/agent/features/Header.tsx
+++ b/src/app/[variants]/(main)/community/(detail)/agent/features/Header.tsx
@@ -19,6 +19,8 @@ import {
BookmarkIcon,
CoinsIcon,
DotIcon,
+ GitBranchIcon,
+ GitForkIcon,
HeartIcon,
} from 'lucide-react';
import qs from 'query-string';
@@ -29,6 +31,7 @@ import useSWR from 'swr';
import urlJoin from 'url-join';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
+import { marketApiService } from '@/services/marketApi';
import { socialService } from '@/services/social';
import { formatIntergerNumber } from '@/utils/format';
@@ -57,6 +60,8 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
pluginCount,
knowledgeCount,
userName,
+ forkCount,
+ forkedFromAgentId,
} = useDetailContext();
const { mobile = isMobile } = useResponsive();
const { isAuthenticated, signIn, session } = useMarketAuth();
@@ -85,6 +90,13 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
);
const isLiked = likeStatus?.isLiked ?? false;
+ // Fetch fork source info
+ const { data: forkSource } = useSWR(
+ identifier && forkedFromAgentId ? ['fork-source', identifier] : null,
+ () => marketApiService.getAgentForkSource(identifier!),
+ { revalidateOnFocus: false },
+ );
+
const handleFavoriteClick = async () => {
if (!isAuthenticated) {
await signIn();
@@ -223,6 +235,31 @@ const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
template={'MMM DD, YYYY'}
/>
</Flexbox>
+
+ {/* Fork information */}
+ {(forkSource?.source || (forkCount && forkCount > 0)) && (
+ <Flexbox align={'center'} gap={12} horizontal>
+ {forkSource?.source && (
+ <Flexbox align={'center'} gap={6} horizontal>
+ <Icon icon={GitForkIcon} size={'small'} />
+ <Text className={styles.time} type={'secondary'}>
+ {t('fork.forkedFrom')}:{' '}
+ <Link to={urlJoin('/community/agent', forkSource.source.identifier)}>
+ {forkSource.source.name}
+ </Link>
+ </Text>
+ </Flexbox>
+ )}
+ {forkCount && forkCount > 0 && (
+ <Flexbox align={'center'} gap={6} horizontal>
+ <Icon icon={GitBranchIcon} size={'small'} />
+ <Text className={styles.time} type={'secondary'}>
+ {forkCount} {t('fork.forks')}
+ </Text>
+ </Flexbox>
+ )}
+ </Flexbox>
+ )}
</Flexbox>
</Flexbox>
<TooltipGroup>
diff --git a/src/app/[variants]/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx b/src/app/[variants]/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx
new file mode 100644
index 00000000000..96be27cd57b
--- /dev/null
+++ b/src/app/[variants]/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx
@@ -0,0 +1,133 @@
+'use client';
+
+import { Button } from '@lobehub/ui';
+import { App } from 'antd';
+import { createStaticStyles } from 'antd-style';
+import { customAlphabet } from 'nanoid/non-secure';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+
+import { SESSION_CHAT_URL } from '@/const/url';
+import { agentService } from '@/services/agent';
+import { discoverService } from '@/services/discover';
+import { marketApiService } from '@/services/marketApi';
+import { useAgentStore } from '@/store/agent';
+import { useHomeStore } from '@/store/home';
+
+import { useDetailContext } from '../../DetailProvider';
+
+const styles = createStaticStyles(({ css }) => ({
+ buttonGroup: css`
+ width: 100%;
+ `,
+}));
+
+/**
+ * Generate a market identifier (8-character lowercase alphanumeric string)
+ */
+const generateMarketIdentifier = () => {
+ const alphabet = '0123456789abcdefghijklmnopqrstuvwxyz';
+ const generate = customAlphabet(alphabet, 8);
+ return generate();
+};
+
+const ForkAndChat = memo<{ mobile?: boolean }>(({ mobile }) => {
+ const { identifier, title, config, avatar, backgroundColor, description, tags, editorData } =
+ useDetailContext();
+ const [isLoading, setIsLoading] = useState(false);
+ const createAgent = useAgentStore((s) => s.createAgent);
+ const refreshAgentList = useHomeStore((s) => s.refreshAgentList);
+ const { message } = App.useApp();
+ const navigate = useNavigate();
+ const { t } = useTranslation('discover');
+
+ const meta = {
+ avatar,
+ backgroundColor,
+ description,
+ marketIdentifier: identifier,
+ tags,
+ title,
+ };
+
+ const handleForkAndChat = async () => {
+ try {
+ setIsLoading(true);
+
+ // Step 1: Check if user has already forked this agent
+ const existingAgentId = await agentService.getAgentByForkedFromIdentifier(identifier!);
+
+ if (existingAgentId) {
+ // User has already forked this agent, navigate to existing fork
+ message.info(t('fork.alreadyForked'));
+ navigate(SESSION_CHAT_URL(existingAgentId, mobile));
+ return;
+ }
+
+ // Generate a unique identifier for the forked agent
+ const newIdentifier = generateMarketIdentifier();
+
+ // Step 2: Fork the agent via Market API
+ const forkResult = await marketApiService.forkAgent(identifier!, {
+ identifier: newIdentifier,
+ name: title,
+ status: 'published',
+ visibility: 'public',
+ });
+
+ // Step 3: Create agent config with forked data
+ if (!config) throw new Error('Agent config is missing');
+
+ const agentData = {
+ config: {
+ ...config,
+ editorData,
+ ...meta,
+ marketIdentifier: forkResult.agent.identifier,
+ params: {
+ ...config.params,
+ forkedFromIdentifier: identifier, // Store the source agent identifier
+ },
+ title: forkResult.agent.name,
+ },
+ };
+
+ // Step 4: Add to local agent list
+ const result = await createAgent(agentData);
+ await refreshAgentList();
+
+ // Step 5: Report fork event (using 'add' event type)
+ discoverService.reportAgentEvent({
+ event: 'add',
+ identifier: forkResult.agent.identifier,
+ source: location.pathname,
+ });
+
+ message.success(t('fork.success'));
+
+ // Step 6: Navigate to chat
+ navigate(SESSION_CHAT_URL(result!.agentId || result!.sessionId, mobile));
+ } catch (error: any) {
+ console.error('Fork failed:', error);
+ message.error(t('fork.failed'));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return (
+ <Button
+ block
+ className={styles.buttonGroup}
+ loading={isLoading}
+ onClick={handleForkAndChat}
+ size={'large'}
+ type={'primary'}
+ >
+ {t('fork.forkAndChat')}
+ </Button>
+ );
+});
+
+export default ForkAndChat;
diff --git a/src/app/[variants]/(main)/community/(detail)/agent/features/Sidebar/ActionButton/index.tsx b/src/app/[variants]/(main)/community/(detail)/agent/features/Sidebar/ActionButton/index.tsx
index f2934ff298d..b861bd3adf7 100644
--- a/src/app/[variants]/(main)/community/(detail)/agent/features/Sidebar/ActionButton/index.tsx
+++ b/src/app/[variants]/(main)/community/(detail)/agent/features/Sidebar/ActionButton/index.tsx
@@ -8,13 +8,13 @@ import { OFFICIAL_URL } from '@/const/url';
import ShareButton from '../../../../features/ShareButton';
import { useDetailContext } from '../../DetailProvider';
-import AddAgent from './AddAgent';
+import ForkAndChat from './ForkAndChat';
const ActionButton = memo<{ mobile?: boolean }>(({ mobile }) => {
const { avatar, description, tags, title, identifier } = useDetailContext();
return (
<Flexbox align={'center'} gap={8} horizontal>
- <AddAgent mobile={mobile} />
+ <ForkAndChat mobile={mobile} />
<ShareButton
meta={{
avatar: avatar,
diff --git a/src/app/[variants]/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/ForkGroupAndChat.tsx b/src/app/[variants]/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/ForkGroupAndChat.tsx
new file mode 100644
index 00000000000..c73be741ce1
--- /dev/null
+++ b/src/app/[variants]/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/ForkGroupAndChat.tsx
@@ -0,0 +1,208 @@
+'use client';
+
+import { Button } from '@lobehub/ui';
+import { App } from 'antd';
+import { createStaticStyles } from 'antd-style';
+import { customAlphabet } from 'nanoid/non-secure';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+import urlJoin from 'url-join';
+
+import { chatGroupService } from '@/services/chatGroup';
+import { discoverService } from '@/services/discover';
+import { marketApiService } from '@/services/marketApi';
+import { useAgentGroupStore } from '@/store/agentGroup';
+
+import { useDetailContext } from '../../DetailProvider';
+
+const styles = createStaticStyles(({ css }) => ({
+ buttonGroup: css`
+ width: 100%;
+ `,
+}));
+
+/**
+ * Generate a market identifier (8-character lowercase alphanumeric string)
+ */
+const generateMarketIdentifier = () => {
+ const alphabet = '0123456789abcdefghijklmnopqrstuvwxyz';
+ const generate = customAlphabet(alphabet, 8);
+ return generate();
+};
+
+const ForkGroupAndChat = memo<{ mobile?: boolean }>(() => {
+ const {
+ avatar,
+ backgroundColor,
+ description,
+ tags,
+ title,
+ config,
+ identifier,
+ memberAgents = [],
+ } = useDetailContext();
+ const [isLoading, setIsLoading] = useState(false);
+ const { message } = App.useApp();
+ const { t } = useTranslation('discover');
+ const navigate = useNavigate();
+ const loadGroups = useAgentGroupStore((s) => s.loadGroups);
+
+ const meta = {
+ avatar,
+ backgroundColor,
+ description,
+ tags,
+ title,
+ };
+
+ const handleForkAndChat = async () => {
+ try {
+ setIsLoading(true);
+
+ // Step 1: Check if user has already forked this group
+ const existingGroupId = await chatGroupService.getGroupByForkedFromIdentifier(identifier!);
+
+ if (existingGroupId) {
+ // User has already forked this group, navigate to existing fork
+ message.info(t('fork.alreadyForked'));
+ navigate(urlJoin('/group', existingGroupId));
+ return;
+ }
+
+ if (!config) {
+ message.error(
+ t('groupAgents.noConfig', { defaultValue: 'Group configuration not available' }),
+ );
+ return;
+ }
+
+ // Generate a unique identifier for the forked group
+ const newIdentifier = generateMarketIdentifier();
+
+ // Step 2: Fork the group via Market API
+ const forkResult = await marketApiService.forkAgentGroup(identifier!, {
+ identifier: newIdentifier,
+ name: title,
+ status: 'published',
+ visibility: 'public',
+ });
+
+ // Step 3: Find supervisor from memberAgents
+ const supervisorMember = memberAgents.find((member: any) => {
+ const agent = member.agent || member;
+ const role = member.role || agent.role;
+ return role === 'supervisor';
+ });
+
+ // Prepare supervisor config
+ let supervisorConfig;
+ if (supervisorMember) {
+ const member = supervisorMember as any;
+ const agent = member.agent || member;
+ const currentVersion = member.currentVersion || member;
+ const rawConfig = {
+ avatar: currentVersion.avatar,
+ backgroundColor: currentVersion.backgroundColor,
+ description: currentVersion.description,
+ model: currentVersion.config?.model || currentVersion.model,
+ params: currentVersion.config?.params || currentVersion.params,
+ provider: currentVersion.config?.provider || currentVersion.provider,
+ systemRole:
+ currentVersion.config?.systemRole ||
+ currentVersion.config?.systemPrompt ||
+ currentVersion.systemRole ||
+ currentVersion.content,
+ tags: currentVersion.tags,
+ title: currentVersion.name || agent.name || 'Supervisor',
+ };
+ // Filter out null/undefined values
+ supervisorConfig = Object.fromEntries(
+ // eslint-disable-next-line eqeqeq, @typescript-eslint/no-unused-vars
+ Object.entries(rawConfig).filter(([_, v]) => v != null),
+ );
+ }
+
+ // Step 4: Prepare group config
+ const groupConfig = {
+ config: {
+ ...config,
+ forkedFromIdentifier: identifier, // Store the source group identifier
+ },
+ // Group content is the supervisor's systemRole (for backward compatibility)
+ content: supervisorConfig?.systemRole || config.systemRole,
+ ...meta,
+ };
+
+ // Step 5: Prepare member agents from market data
+ // Filter out supervisor role as it will be created separately using supervisorConfig
+ const members = memberAgents
+ .filter((member: any) => {
+ const agent = member.agent || member;
+ const role = member.role || agent.role;
+ return role !== 'supervisor';
+ })
+ .map((member: any) => {
+ const agent = member.agent || member;
+ const currentVersion = member.currentVersion || member;
+ return {
+ avatar: currentVersion.avatar,
+ backgroundColor: currentVersion.backgroundColor,
+ description: currentVersion.description,
+ model: currentVersion.config?.model || currentVersion.model,
+ plugins: currentVersion.plugins,
+ provider: currentVersion.config?.provider || currentVersion.provider,
+ systemRole:
+ currentVersion.config?.systemRole ||
+ currentVersion.config?.systemPrompt ||
+ currentVersion.systemRole ||
+ currentVersion.content,
+ tags: currentVersion.tags,
+ title: currentVersion.name || agent.name,
+ };
+ });
+
+ // Step 6: Create group with all members in one request
+ const result = await chatGroupService.createGroupWithMembers(
+ groupConfig,
+ members,
+ supervisorConfig,
+ );
+
+ // Refresh group list
+ await loadGroups();
+
+ // Step 7: Report fork event (using 'add' event type)
+ discoverService.reportAgentEvent({
+ event: 'add',
+ identifier: forkResult.group.identifier,
+ source: location.pathname,
+ });
+
+ message.success(t('fork.success'));
+
+ // Step 8: Navigate to chat
+ navigate(urlJoin('/group', result.groupId));
+ } catch (error: any) {
+ console.error('Fork group failed:', error);
+ message.error(t('fork.failed'));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return (
+ <Button
+ block
+ className={styles.buttonGroup}
+ loading={isLoading}
+ onClick={handleForkAndChat}
+ size={'large'}
+ type={'primary'}
+ >
+ {t('fork.forkAndChat')}
+ </Button>
+ );
+});
+
+export default ForkGroupAndChat;
diff --git a/src/app/[variants]/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/index.tsx b/src/app/[variants]/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/index.tsx
index 85a87af62d9..8f66d59c7ca 100644
--- a/src/app/[variants]/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/index.tsx
+++ b/src/app/[variants]/(main)/community/(detail)/group_agent/features/Sidebar/ActionButton/index.tsx
@@ -8,14 +8,14 @@ import { OFFICIAL_URL } from '@/const/url';
import ShareButton from '../../../../features/ShareButton';
import { useDetailContext } from '../../DetailProvider';
-import AddGroupAgent from './AddGroupAgent';
+import ForkGroupAndChat from './ForkGroupAndChat';
const ActionButton = memo<{ mobile?: boolean }>(({ mobile }) => {
const { avatar, title, description, tags, identifier } = useDetailContext();
return (
<Flexbox align={'center'} gap={8} horizontal>
- <AddGroupAgent mobile={mobile} />
+ <ForkGroupAndChat mobile={mobile} />
{identifier && (
<ShareButton
meta={{
diff --git a/src/app/[variants]/(main)/community/(detail)/user/features/DetailProvider.tsx b/src/app/[variants]/(main)/community/(detail)/user/features/DetailProvider.tsx
index 7716e5a096a..5d3d9cd7ece 100644
--- a/src/app/[variants]/(main)/community/(detail)/user/features/DetailProvider.tsx
+++ b/src/app/[variants]/(main)/community/(detail)/user/features/DetailProvider.tsx
@@ -13,6 +13,8 @@ export interface UserDetailContextConfig {
agentCount: number;
agentGroups?: DiscoverGroupAgentItem[];
agents: DiscoverAssistantItem[];
+ forkedAgentGroups?: DiscoverGroupAgentItem[];
+ forkedAgents?: DiscoverAssistantItem[];
groupCount: number;
isOwner: boolean;
mobile?: boolean;
diff --git a/src/app/[variants]/(main)/community/(detail)/user/features/UserContent.tsx b/src/app/[variants]/(main)/community/(detail)/user/features/UserContent.tsx
index 0563b731b1c..f9645fe02a8 100644
--- a/src/app/[variants]/(main)/community/(detail)/user/features/UserContent.tsx
+++ b/src/app/[variants]/(main)/community/(detail)/user/features/UserContent.tsx
@@ -3,16 +3,23 @@
import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
+import { useUserDetailContext } from './DetailProvider';
import UserAgentList from './UserAgentList';
import UserFavoriteAgents from './UserFavoriteAgents';
import UserFavoritePlugins from './UserFavoritePlugins';
+import UserForkedAgentGroups from './UserForkedAgentGroups';
+import UserForkedAgents from './UserForkedAgents';
import UserGroupList from './UserGroupList';
const UserContent = memo(() => {
+ const { forkedAgents, forkedAgentGroups } = useUserDetailContext();
+
return (
<Flexbox gap={32}>
<UserAgentList />
<UserGroupList />
+ <UserForkedAgents agents={forkedAgents} />
+ <UserForkedAgentGroups agentGroups={forkedAgentGroups} />
<UserFavoriteAgents />
<UserFavoritePlugins />
</Flexbox>
diff --git a/src/app/[variants]/(main)/community/(detail)/user/features/UserForkedAgentGroups.tsx b/src/app/[variants]/(main)/community/(detail)/user/features/UserForkedAgentGroups.tsx
new file mode 100644
index 00000000000..d635202da69
--- /dev/null
+++ b/src/app/[variants]/(main)/community/(detail)/user/features/UserForkedAgentGroups.tsx
@@ -0,0 +1,63 @@
+'use client';
+
+import { Flexbox, Grid, Tag, Text } from '@lobehub/ui';
+import { Pagination } from 'antd';
+import { GitForkIcon } from 'lucide-react';
+import { memo, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { type DiscoverGroupAgentItem } from '@/types/discover';
+
+import UserGroupCard from './UserGroupCard';
+
+interface UserForkedAgentGroupsProps {
+ agentGroups?: DiscoverGroupAgentItem[];
+ pageSize?: number;
+ rows?: number;
+}
+
+const UserForkedAgentGroups = memo<UserForkedAgentGroupsProps>(
+ ({ agentGroups = [], rows = 4, pageSize = 10 }) => {
+ const { t } = useTranslation('discover');
+ const [currentPage, setCurrentPage] = useState(1);
+
+ const paginatedGroups = useMemo(() => {
+ const startIndex = (currentPage - 1) * pageSize;
+ return agentGroups.slice(startIndex, startIndex + pageSize);
+ }, [agentGroups, currentPage, pageSize]);
+
+ if (agentGroups.length === 0) return null;
+
+ const showPagination = agentGroups.length > pageSize;
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox align={'center'} gap={8} horizontal>
+ <GitForkIcon size={16} />
+ <Text fontSize={16} weight={500}>
+ {t('user.forkedAgentGroups')}
+ </Text>
+ <Tag>{agentGroups.length}</Tag>
+ </Flexbox>
+ <Grid rows={rows} width={'100%'}>
+ {paginatedGroups.map((group, index) => (
+ <UserGroupCard key={group.identifier || index} {...group} />
+ ))}
+ </Grid>
+ {showPagination && (
+ <Flexbox align={'center'} justify={'center'}>
+ <Pagination
+ current={currentPage}
+ onChange={(page) => setCurrentPage(page)}
+ pageSize={pageSize}
+ showSizeChanger={false}
+ total={agentGroups.length}
+ />
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+export default UserForkedAgentGroups;
diff --git a/src/app/[variants]/(main)/community/(detail)/user/features/UserForkedAgents.tsx b/src/app/[variants]/(main)/community/(detail)/user/features/UserForkedAgents.tsx
new file mode 100644
index 00000000000..3d6cc3493d6
--- /dev/null
+++ b/src/app/[variants]/(main)/community/(detail)/user/features/UserForkedAgents.tsx
@@ -0,0 +1,61 @@
+'use client';
+
+import { Flexbox, Grid, Tag, Text } from '@lobehub/ui';
+import { Pagination } from 'antd';
+import { GitForkIcon } from 'lucide-react';
+import { memo, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { type DiscoverAssistantItem } from '@/types/discover';
+
+import UserAgentCard from './UserAgentCard';
+
+interface UserForkedAgentsProps {
+ agents?: DiscoverAssistantItem[];
+ pageSize?: number;
+ rows?: number;
+}
+
+const UserForkedAgents = memo<UserForkedAgentsProps>(({ agents = [], rows = 4, pageSize = 10 }) => {
+ const { t } = useTranslation('discover');
+ const [currentPage, setCurrentPage] = useState(1);
+
+ const paginatedAgents = useMemo(() => {
+ const startIndex = (currentPage - 1) * pageSize;
+ return agents.slice(startIndex, startIndex + pageSize);
+ }, [agents, currentPage, pageSize]);
+
+ if (agents.length === 0) return null;
+
+ const showPagination = agents.length > pageSize;
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox align={'center'} gap={8} horizontal>
+ <GitForkIcon size={16} />
+ <Text fontSize={16} weight={500}>
+ {t('user.forkedAgents')}
+ </Text>
+ <Tag>{agents.length}</Tag>
+ </Flexbox>
+ <Grid rows={rows} width={'100%'}>
+ {paginatedAgents.map((agent, index) => (
+ <UserAgentCard key={agent.identifier || index} {...agent} />
+ ))}
+ </Grid>
+ {showPagination && (
+ <Flexbox align={'center'} justify={'center'}>
+ <Pagination
+ current={currentPage}
+ onChange={(page) => setCurrentPage(page)}
+ pageSize={pageSize}
+ showSizeChanger={false}
+ total={agents.length}
+ />
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+});
+
+export default UserForkedAgents;
diff --git a/src/app/[variants]/(main)/community/(detail)/user/index.tsx b/src/app/[variants]/(main)/community/(detail)/user/index.tsx
index 8a082cb7b61..76172406e24 100644
--- a/src/app/[variants]/(main)/community/(detail)/user/index.tsx
+++ b/src/app/[variants]/(main)/community/(detail)/user/index.tsx
@@ -61,12 +61,14 @@ const UserDetailPage = memo<UserDetailPageProps>(({ mobile }) => {
const contextConfig = useMemo(() => {
if (!data || !data.user) return null;
- const { user, agents, agentGroups } = data;
+ const { user, agents, agentGroups, forkedAgents, forkedAgentGroups } = data;
const totalInstalls = agents.reduce((sum, agent) => sum + (agent.installCount || 0), 0);
return {
agentCount: agents.length,
agentGroups: agentGroups || [],
agents,
+ forkedAgentGroups: forkedAgentGroups || [],
+ forkedAgents: forkedAgents || [],
groupCount: agentGroups?.length || 0,
isOwner,
mobile,
diff --git a/src/locales/default/discover.ts b/src/locales/default/discover.ts
index b2882e0e332..020097f36b6 100644
--- a/src/locales/default/discover.ts
+++ b/src/locales/default/discover.ts
@@ -150,383 +150,754 @@ export default {
'footer.desc':
'Evolve with AI users worldwide. Become a creator to submit your agents and skills to the LobeHub Community.',
'footer.title': 'Share your creation on LobeHub Community today',
+
+ 'fork.alreadyForked': 'You have already forked this agent. Navigating to your fork...',
+
+ 'fork.failed': 'Fork failed. Please try again.',
+
+ // Fork related
+ 'fork.forkAndChat': 'Fork & Chat',
+
+ 'fork.forkedFrom': 'Forked from',
+
+ 'fork.forks': 'forks',
+
+ 'fork.forksCount': '{{count}} fork',
+
+ 'fork.forksCount_other': '{{count}} forks',
+
+ 'fork.success': 'Forked successfully!',
+
+ 'fork.viewAllForks': 'View all forks',
+
'home.communityAgents': 'Community Agents',
+
'home.featuredAssistants': 'Featured Agents',
+
'home.featuredModels': 'Featured Models',
+
'home.featuredPlugins': 'Featured Skills',
+
'home.featuredProviders': 'Featured Providers',
+
'home.featuredTools': 'Featured Skills',
+
'home.more': 'Discover More',
+
'isClaimed': 'Claimed',
+
'isFeatured': 'Featured',
+
'isOfficial': 'Officially Verified',
+
'like': 'Like',
+
'mcp.categories.all.description': 'All MCP Servers',
+
'mcp.categories.all.name': 'All',
+
'mcp.categories.business.description': 'Business and Enterprise Services',
+
'mcp.categories.business.name': 'Business Services',
+
'mcp.categories.developer.description': 'Developer-related Tools and Services',
+
'mcp.categories.developer.name': 'Developer Tools',
+
'mcp.categories.discover.description': 'Recommended and trending MCP servers',
+
'mcp.categories.discover.name': 'Discover',
+
'mcp.categories.gaming-entertainment.description': 'Games, Entertainment, and Leisure Activities',
+
'mcp.categories.gaming-entertainment.name': 'Gaming & Entertainment',
+
'mcp.categories.health-wellness.description': 'Health, Fitness, and Wellness',
+
'mcp.categories.health-wellness.name': 'Health & Wellness',
+
'mcp.categories.lifestyle.description': 'Personal Lifestyle, Habits, and Daily Activities',
+
'mcp.categories.lifestyle.name': 'Lifestyle',
+
'mcp.categories.media-generate.description': 'Media Generation, Editing, and Processing',
+
'mcp.categories.media-generate.name': 'Media Generation',
+
'mcp.categories.news.description': 'News Aggregation, Reporting, and Information Services',
+
'mcp.categories.news.name': 'News & Information',
+
'mcp.categories.productivity.description': 'Task Management, Notes, and Productivity Tools',
+
'mcp.categories.productivity.name': 'Productivity Tools',
+
'mcp.categories.science-education.description':
'Scientific Research, Learning, and Educational Tools',
+
'mcp.categories.science-education.name': 'Science & Education',
+
'mcp.categories.social.description': 'Social Networks and Communication',
+
'mcp.categories.social.name': 'Social Media',
+
'mcp.categories.stocks-finance.description': 'Financial Markets, Trading, and Investment',
+
'mcp.categories.stocks-finance.name': 'Stocks & Finance',
+
'mcp.categories.tools.description': 'General-purpose Practical Tools and Services',
+
'mcp.categories.tools.name': 'Utility Tools',
+
'mcp.categories.travel-transport.description': 'Travel Planning and Transportation',
+
'mcp.categories.travel-transport.name': 'Travel & Transport',
+
'mcp.categories.weather.description': 'Weather Forecasting and Meteorological Services',
+
'mcp.categories.weather.name': 'Weather',
+
'mcp.categories.web-search.description': 'Web Search and Information Retrieval',
+
'mcp.categories.web-search.name': 'Information Retrieval',
+
'mcp.details.connectionType.hybrid.desc':
'This service can run locally or in the cloud depending on configuration or usage scenario, offering dual operation capability.',
+
'mcp.details.connectionType.hybrid.title': 'Hybrid Service',
+
'mcp.details.connectionType.local.desc':
'This server can only run on the client’s local device, requiring installation and relying on local resources.',
+
'mcp.details.connectionType.local.title': 'Local Service',
+
'mcp.details.connectionType.remote.desc':
'This server is hosted remotely because it mainly depends on remote services and does not rely on the local environment.',
+
'mcp.details.connectionType.remote.title': 'Cloud Service',
+
'mcp.details.deployment.args': 'Arguments',
+
'mcp.details.deployment.checkCommand': 'Check Command',
+
'mcp.details.deployment.command': 'Command',
+
'mcp.details.deployment.commandLine': 'System Dependencies',
+
'mcp.details.deployment.connection': 'Connection Method',
+
'mcp.details.deployment.connectionType': 'Connection Type',
+
'mcp.details.deployment.description': 'Skill Installation and Deployment Method',
+
'mcp.details.deployment.descriptionPlaceholder': 'Optional Description',
+
'mcp.details.deployment.empty': 'No Deployment Options Available',
+
'mcp.details.deployment.env': 'Environment Variables',
+
'mcp.details.deployment.guide': 'Installation Guide',
+
'mcp.details.deployment.installation': 'Install via {{method}}',
+
'mcp.details.deployment.installationMethod': 'Installation Method',
+
'mcp.details.deployment.other': 'Other Settings',
+
'mcp.details.deployment.packageName': 'Package Name',
+
'mcp.details.deployment.platform.steps.claude':
'- Open the **Claude Desktop** app\n- Go to **Settings**, then select **Developer**\n- Click **Edit Configuration**\n- Open the **claude_desktop_config.json** file\n- Copy and paste the server configuration into the existing file, then save',
+
'mcp.details.deployment.platform.steps.cline':
'- Open VS Code with the Cline extension installed\n- Click the Cline icon in the sidebar\n- Select **MCP Servers** from the dropdown menu\n- In the **Remote Servers** tab, enter the server name and your MCP server URL\n- Click **Add Server** to connect',
+
'mcp.details.deployment.platform.steps.cursor':
'- Navigate to **Settings**, then select Cursor settings\n- Choose **MCP** on the left\n- Click **Add New Global MCP Server** at the top right\n- Copy and paste the server configuration into the existing file, then save',
+
'mcp.details.deployment.platform.steps.lobeChat':
'- Open the **LobeHub Desktop** app\n- Go to **Settings** - **Default Agent**\n- Then select **Skill Settings** - **Custom Skills**\n- Click **Quick Import JSON Configuration**\n- Copy and paste the server configuration into the text box, then install',
+
'mcp.details.deployment.platform.steps.openai':
'- Open your **OpenAI app** or development environment\n- Configure MCP tools in the **Responses API**\n- Add MCP blocks to the **tools** array in API requests\n- Set **server_url** to your MCP server endpoint\n- Include required authentication headers (API key, token, etc.)\n- Use the `allowed_tools` parameter to restrict exposed tools\n- Set `require_approval` to control tool execution approval',
+
'mcp.details.deployment.platform.steps.vscode':
'- Open VS Code\n- Open the command palette (`Ctrl+Shift+P` / `Cmd+Shift+P`)\n- Type **MCP: Add Server** and select it\n- Choose to add to workspace or user settings\n- Copy and paste the server configuration',
+
'mcp.details.deployment.platform.title': 'Install on {{platform}}',
+
'mcp.details.deployment.recommended': 'Recommended',
+
'mcp.details.deployment.systemDependencies': 'System Dependencies',
+
'mcp.details.deployment.table.description': 'Description',
+
'mcp.details.deployment.table.name': 'Name',
+
'mcp.details.deployment.table.required': 'Required',
+
'mcp.details.deployment.table.type': 'Type',
+
'mcp.details.deployment.title': 'Installation Method',
+
'mcp.details.githubBadge.desc':
'LobeHub regularly scans code repositories and documentation to: - Confirm MCP server operational status.\n- Extract server features such as tools, resources, prompts, and required parameters.\n- Our badge helps users quickly assess MCP server security, feature set, and installation instructions. Please copy the following code into your `README.md` file:',
+
'mcp.details.nav.needHelp': 'Need Help?',
+
'mcp.details.nav.reportIssue': 'Report Issue',
+
'mcp.details.nav.viewSourceCode': 'View Source Code',
+
'mcp.details.overview.title': 'Overview',
+
'mcp.details.related.listTitle': 'Related MCP Servers',
+
'mcp.details.related.more': 'View More',
+
'mcp.details.related.title': 'Related Recommendations',
+
'mcp.details.schema.mode.docs': 'Documentation',
+
'mcp.details.schema.prompts.arguments': 'Parameter Configuration',
+
'mcp.details.schema.prompts.desc': 'Interactive templates triggered by user selection',
+
'mcp.details.schema.prompts.empty': 'No Prompts Available',
+
'mcp.details.schema.prompts.instructions': 'Instruction Description',
+
'mcp.details.schema.prompts.table.description': 'Description',
+
'mcp.details.schema.prompts.table.name': 'Name',
+
'mcp.details.schema.prompts.table.required': 'Required',
+
'mcp.details.schema.prompts.title': 'Prompt List',
+
'mcp.details.schema.resources.desc': 'Context data attached and managed by the client',
+
'mcp.details.schema.resources.empty': 'No Resources Available',
+
'mcp.details.schema.resources.table.description': 'Description',
+
'mcp.details.schema.resources.table.mineType': 'MIME Type',
+
'mcp.details.schema.resources.table.name': 'Name',
+
'mcp.details.schema.resources.table.uri': 'URI',
+
'mcp.details.schema.resources.title': 'Resource List',
+
'mcp.details.schema.title': 'Skill Features',
+
'mcp.details.schema.tools.desc':
'Functional interfaces exposed to large language models (LLM) to perform operations',
+
'mcp.details.schema.tools.empty': 'No Tools Available',
+
'mcp.details.schema.tools.inputSchema': 'Input Description',
+
'mcp.details.schema.tools.instructions': 'Instruction Description',
+
'mcp.details.schema.tools.table.description': 'Description',
+
'mcp.details.schema.tools.table.name': 'Name',
+
'mcp.details.schema.tools.table.required': 'Required',
+
'mcp.details.schema.tools.table.type': 'Type',
+
'mcp.details.schema.tools.title': 'Tool List',
+
'mcp.details.score.claimed.desc':
'This MCP Server has been claimed by the owner, ensuring its ownership and management.',
+
'mcp.details.score.claimed.title': 'Claimed by Owner',
+
'mcp.details.score.deployMoreThanManual.desc':
'This MCP Server offers installation methods friendlier than Manual, allowing users to deploy and use it easily.',
+
'mcp.details.score.deployMoreThanManual.title': 'Offers Friendly Installation Methods',
+
'mcp.details.score.deployment.desc':
'This MCP Server provides at least one installation method, allowing users to deploy and use it.',
+
'mcp.details.score.deployment.descWithCount':
'This MCP Server provides {{number}} installation methods, allowing users to deploy and use it.',
+
'mcp.details.score.deployment.title': 'Provides At Least One Installation Method',
+
'mcp.details.score.license.desc': 'This repository contains a LICENSE file.',
+
'mcp.details.score.license.descWithlicense': 'This repository is licensed under {{license}}.',
+
'mcp.details.score.license.title': 'Has LICENSE',
+
'mcp.details.score.listTitle': 'Score Details',
+
'mcp.details.score.notClaimed.desc':
'If you are the owner of this MCP Server, you can claim it by the following methods.',
+
'mcp.details.score.notClaimed.title': 'Not Claimed by Owner',
+
'mcp.details.score.prompts.desc':
'This MCP Server provides prompts, allowing users to interact with the service.',
+
'mcp.details.score.prompts.descWithCount':
'This MCP Server provides {{number}} prompts, allowing users to interact with the service.',
+
'mcp.details.score.prompts.title': 'Includes Prompts',
+
'mcp.details.score.readme.desc': 'This repository contains a README.md file.',
+
'mcp.details.score.readme.title': 'Has README',
+
'mcp.details.score.resources.desc':
'This MCP Server provides resources, allowing users to attach and manage context data.',
+
'mcp.details.score.resources.descWithCount':
'This MCP Server provides {{number}} resources, allowing users to attach and manage context data.',
+
'mcp.details.score.resources.title': 'Includes Resources',
+
'mcp.details.score.title': 'Score',
+
'mcp.details.score.tools.desc':
'The service must provide at least one tool, allowing users to perform specific operations.',
+
'mcp.details.score.tools.descWithCount':
'This MCP Server provides {{number}} tool features, allowing users to perform specific operations.',
+
'mcp.details.score.tools.title': 'Includes At Least One Tool',
+
'mcp.details.score.validated.desc':
'This MCP Server has passed installation validation, ensuring its quality and reliability.',
+
'mcp.details.score.validated.title': 'Validated',
+
'mcp.details.scoreLevel.a.desc':
'This MCP Server has been rigorously validated, providing comprehensive features and a high-quality user experience.',
+
'mcp.details.scoreLevel.a.fullTitle': 'Excellent Skill',
+
'mcp.details.scoreLevel.a.title': 'Premium',
+
'mcp.details.scoreLevel.b.desc':
'This MCP Server offers good features and user experience but may need improvements in some areas.',
+
'mcp.details.scoreLevel.b.fullTitle': 'Good Functionality',
+
'mcp.details.scoreLevel.b.title': 'Good',
+
'mcp.details.scoreLevel.f.desc':
'This MCP Server is incomplete or of low quality; users are advised to use it cautiously.',
+
'mcp.details.scoreLevel.f.fullTitle': 'Poor Quality',
+
'mcp.details.scoreLevel.f.title': 'Poor',
+
'mcp.details.settings.capabilities.prompts': 'Prompts',
+
'mcp.details.settings.capabilities.resources': 'Resources',
+
'mcp.details.settings.capabilities.title': 'Skill Capabilities',
+
'mcp.details.settings.capabilities.tools': 'Tools',
+
'mcp.details.settings.configuration.title': 'Skill Configuration',
+
'mcp.details.settings.connection.args': 'Startup Arguments',
+
'mcp.details.settings.connection.command': 'Startup Command',
+
'mcp.details.settings.connection.title': 'Connection Information',
+
'mcp.details.settings.connection.type': 'Connection Type',
+
'mcp.details.settings.connection.url': 'Service URL',
+
'mcp.details.settings.saveSettings': 'Save Settings',
+
'mcp.details.settings.title': 'Skill Settings',
+
'mcp.details.sidebar.install': 'Install MCP Server',
+
'mcp.details.sidebar.meta.homepage': 'Official Homepage',
+
'mcp.details.sidebar.meta.installCount': 'Install Count',
+
'mcp.details.sidebar.meta.language': 'Source Language',
+
'mcp.details.sidebar.meta.license': 'License',
+
'mcp.details.sidebar.meta.published': 'Published Date',
+
'mcp.details.sidebar.meta.repo': 'Source Repository',
+
'mcp.details.sidebar.meta.stars': 'Stars',
+
'mcp.details.sidebar.meta.title': 'Details',
+
'mcp.details.sidebar.meta.updated': 'Last Updated',
+
'mcp.details.sidebar.moreServerConfig': 'View Details',
+
'mcp.details.sidebar.recommendServers': 'Related MCP',
+
'mcp.details.sidebar.serverConfig': 'Installation Configuration',
+
'mcp.details.sidebar.toc': 'Table of Contents',
+
'mcp.details.summary.title': 'What can you do with this MCP Server?',
+
'mcp.details.totalScore.description': 'Total score calculated based on various indicators',
+
'mcp.details.totalScore.legend.aGrade': 'Grade A ({{minPercent}}-100%)',
+
'mcp.details.totalScore.legend.bGrade': 'Grade B ({{minPercent}}-{{maxPercent}}%)',
+
'mcp.details.totalScore.legend.fGrade': 'Grade F (0-{{maxPercent}}%)',
+
'mcp.details.totalScore.pointsFormat': '{{score}}/{{total}} points',
+
'mcp.details.totalScore.popover.completedOptional': '✅ Completed Optional Items ({{count}})',
+
'mcp.details.totalScore.popover.completedRequired': '✅ Completed Required Items ({{count}})',
+
'mcp.details.totalScore.popover.incompleteOptional': '⏸️ Incomplete Optional Items ({{count}})',
+
'mcp.details.totalScore.popover.incompleteRequired': '❌ Incomplete Required Items ({{count}})',
+
'mcp.details.totalScore.popover.title': 'Score Details',
+
'mcp.details.totalScore.ratingFormat': 'Rating: {{level}}',
+
'mcp.details.totalScore.scoreInfo.items': 'Items',
+
'mcp.details.totalScore.scoreInfo.points': 'Points',
+
'mcp.details.totalScore.scoreInfo.requiredItems': 'Required Items',
+
'mcp.details.totalScore.title': 'Total Score',
+
'mcp.details.versions.table.isLatest': 'Latest Version',
+
'mcp.details.versions.table.isValidated': 'Validated',
+
'mcp.details.versions.table.publishAt': 'Published Date',
+
'mcp.details.versions.table.version': 'Version',
+
'mcp.details.versions.title': 'Version History',
+
'mcp.hero.desc':
'An open-source, deployable MCP Server community—helping AI systems access file systems, databases, APIs, and other key resources.',
+
'mcp.hero.subTitle': 'Open-source, ready to run',
+
'mcp.hero.title': 'Open-source MCP Community for AI',
+
'mcp.sorts.createdAt': 'Recently Added',
+
'mcp.sorts.installCount': 'Install Count',
+
'mcp.sorts.isFeatured': 'Featured Skills',
+
'mcp.sorts.isValidated': 'Validated Skills',
+
'mcp.sorts.promptsCount': 'Number of Prompts',
+
'mcp.sorts.ratingCount': 'Number of Ratings',
+
'mcp.sorts.recommended': 'Recommended',
+
'mcp.sorts.resourcesCount': 'Number of Resources',
+
'mcp.sorts.toolsCount': 'Number of Tools',
+
'mcp.sorts.updatedAt': 'Recently Updated',
+
'mcp.title': 'MCP Community',
+
'mcp.unvalidated.desc': 'This MCP Server has not been validated yet',
+
'mcp.unvalidated.title': 'Unvalidated',
+
'mcp.validated.desc': 'This MCP Server has been validated to ensure its quality and reliability.',
+
'mcp.validated.descWithDate':
'This MCP Server was validated on {{date}} to ensure its quality and reliability.',
+
'mcp.validated.title': 'Validated',
+
'mcpEmpty.description': 'Try adjusting filters or searching with different keywords.',
+
'mcpEmpty.search': 'No matching MCP Servers found',
+
'mcpEmpty.title': 'No MCP Servers found',
+
'models.abilities': 'Model Capabilities',
+
'models.chat': 'Start Conversation',
+
'models.contentLength': 'Maximum Context Length',
+
'models.details.overview.title': 'Overview',
+
'models.details.related.listTitle': 'Related Models',
+
'models.details.related.more': 'View More',
+
'models.details.related.title': 'Related Recommendations',
+
'models.empty.description': 'Try adjusting the filters to see more models',
+
'models.empty.search': 'No matching models found',
+
'models.empty.title': 'No models available',
+
'models.free': 'Free',
+
'models.guide': 'Configuration Guide',
+
'models.list': 'Model List',
+
'models.more': 'More',
+
'models.parameterList.defaultValue': 'Default Value',
+
'models.parameterList.docs': 'View Documentation',
+
'models.parameterList.frequency_penalty.desc':
'This setting adjusts the frequency at which the model reuses specific vocabulary that has already appeared in the input. Higher values reduce the likelihood of such repetition, while negative values have the opposite effect. Vocabulary penalties do not increase with frequency of occurrence. Negative values encourage vocabulary reuse.',
+
'models.parameterList.frequency_penalty.title': 'Frequency Penalty',
+
'models.parameterList.max_tokens.desc':
'This setting defines the maximum length that the model can generate in a single response. Setting a higher value allows the model to produce longer replies, while a lower value restricts the length of the response, making it more concise. Adjusting this value appropriately based on different application scenarios can help achieve the desired response length and level of detail.',
+
'models.parameterList.max_tokens.title': 'Single Response Limit',
+
'models.parameterList.presence_penalty.desc':
'This setting aims to control the reuse of vocabulary based on its frequency in the input. It attempts to use less of those words that appear more frequently in the input, with usage frequency proportional to occurrence frequency. Vocabulary penalties increase with frequency of occurrence. Negative values encourage vocabulary reuse.',
+
'models.parameterList.presence_penalty.title': 'Topic Freshness',
+
'models.parameterList.range': 'Range',
+
'models.parameterList.reasoning_effort.desc':
'This setting controls the intensity of reasoning the model applies before generating a response. Low intensity prioritizes response speed and saves tokens, while high intensity provides more comprehensive reasoning but consumes more tokens and slows down response time. The default value is medium, balancing reasoning accuracy with response speed.',
+
'models.parameterList.reasoning_effort.title': 'Reasoning Intensity',
+
'models.parameterList.temperature.desc':
"This setting affects the diversity of the model's responses. Lower values lead to more predictable and typical responses, while higher values encourage more diverse and less common responses. When set to 0, the model always gives the same response to a given input.",
+
'models.parameterList.temperature.title': 'Randomness',
+
'models.parameterList.title': 'Model Parameters',
+
'models.parameterList.top_p.desc':
"This setting limits the model's selection to a certain proportion of the most likely vocabulary: only selecting those top words whose cumulative probability reaches P. Lower values make the model's responses more predictable, while the default setting allows the model to choose from the entire range of vocabulary.",
+
'models.parameterList.top_p.title': 'Nucleus Sampling',
+
'models.parameterList.type': 'Type',
+
'models.providerInfo.apiTooltip': 'LobeHub supports using a custom API key for this provider.',
+
'models.providerInfo.input': 'Input Price',
+
'models.providerInfo.inputTooltip': 'Cost per million tokens',
+
'models.providerInfo.latency': 'Latency',
+
'models.providerInfo.latencyTooltip':
'Average response time for the provider to send the first token',
+
'models.providerInfo.maxOutput': 'Maximum Output Length',
+
'models.providerInfo.maxOutputTooltip': 'Maximum number of tokens this endpoint can generate',
+
'models.providerInfo.officialTooltip': 'LobeHub Official Service',
+
'models.providerInfo.output': 'Output Price',
+
'models.providerInfo.outputTooltip': 'Cost per million tokens',
+
'models.providerInfo.streamCancellationTooltip': 'This provider supports stream cancellation.',
+
'models.providerInfo.throughput': 'Throughput',
+
'models.providerInfo.throughputTooltip':
'Average number of tokens transmitted per second for stream requests',
+
'models.sorts.contextWindowTokens': 'Context Length',
+
'models.sorts.identifier': 'Model ID',
+
'models.sorts.inputPrice': 'Input Price',
+
'models.sorts.outputPrice': 'Output Price',
+
'models.sorts.providerCount': 'Number of Providers',
+
'models.sorts.releasedAt': 'Recently Released',
+
'models.suggestions': 'Related Models',
+
'models.supportedProviders': 'Providers Supporting This Model',
+
'plugins.builtinTag': 'Built-in',
+
'plugins.community': 'Community Skills',
+
'plugins.details.settings.title': 'Skill Settings',
+
'plugins.details.summary.title': 'What can you do with this skill?',
+
'plugins.details.tools.title': 'Skill Tools',
+
'plugins.install': 'Install Skill',
+
'plugins.installed': 'Installed',
+
'plugins.legacyTag': 'Legacy',
+
'plugins.list': 'Skill List',
+
'plugins.meta.description': 'Description',
+
'plugins.meta.parameter': 'Parameter',
+
'plugins.meta.title': 'Tool Parameters',
+
'plugins.meta.type': 'Type',
+
'plugins.more': 'More',
+
'plugins.official': 'Official Skills',
+
'plugins.recentSubmits': 'Recently Updated',
+
'plugins.sorts.createdAt': 'Recently Published',
+
'plugins.sorts.identifier': 'Skill ID',
+
'plugins.sorts.title': 'Skill Name',
+
'plugins.suggestions': 'Related Recommendations',
+
'providers.config': 'Configure Provider',
+
'providers.details.guide.title': 'Integration guide',
+
'providers.details.overview.title': 'Overview',
+
'providers.details.related.listTitle': 'Related Providers',
+
'providers.details.related.more': 'View More',
+
'providers.details.related.title': 'Related Recommendations',
+
'providers.empty.description': 'Try adjusting filters to see more Providers.',
+
'providers.empty.search': 'No matching Providers found',
+
'providers.empty.title': 'No Providers found',
+
'providers.list': 'Provider list',
+
'providers.modelCount': '{{count}} models',
+
'providers.modelName': 'Model Name',
+
'providers.modelSite': 'Model Documentation',
+
'providers.more': 'More',
+
'providers.officialSite': 'Official Website',
+
'providers.showAllModels': 'Show All Models',
+
'providers.sorts.default': 'Default',
+
'providers.sorts.identifier': 'Provider ID',
+
'providers.sorts.modelCount': 'Number of Models',
+
'providers.suggestions': 'Related Providers',
+
'providers.supportedModels': 'Supported Models',
+
'publishedTime': 'Published',
+
'search.placeholder': 'Search by name, description, or keywords...',
+
'search.result': '{{count}} results about <highlight>{{keyword}}</highlight>',
+
'search.searching': 'Searching...',
+
'tab.assistant': 'Agent',
+
'tab.home': 'Home',
+
'tab.model': 'Model',
+
'tab.plugin': 'Skill',
+
'tab.provider': 'Provider',
+
'tab.user': 'User',
+
'user.agents': 'Agents',
+
'user.downloads': 'Downloads',
+
'user.editProfile': 'Edit Profile',
+
'user.favoriteAgents': 'Saved Agents',
+
'user.favoritePlugins': 'Saved Skills',
+
'user.follow': 'Follow',
+
'user.followers': 'Followers',
+
'user.following': 'Following',
+
+ 'user.forkedAgentGroups': 'Forked Agent Groups',
+
+ // User fork lists
+ 'user.forkedAgents': 'Forked Agents',
+
'user.login': 'Become a Creator',
+
'user.logout': 'Logout',
+
'user.myProfile': 'My Profile',
+
'user.noAgents': 'This user hasn’t published any Agents yet',
+
'user.noFavoriteAgents': 'No saved Agents yet',
+
'user.noFavoritePlugins': 'No saved Skills yet',
+
+ 'user.noForkedAgentGroups': 'No forked Agent Groups yet',
+
+ 'user.noForkedAgents': 'No forked Agents yet',
+
'user.publishedAgents': 'Created Agents',
+
'user.tabs.favorites': 'Favorites',
+
+ 'user.tabs.forkedAgents': 'Forked',
+
'user.tabs.publishedAgents': 'Created',
+
'user.unfavorite': 'Unsave',
+
'user.unfavoriteFailed': 'Failed to unsave',
'user.unfavoriteSuccess': 'Unsaved',
'user.unfollow': 'Unfollow',
diff --git a/src/server/routers/lambda/agent.ts b/src/server/routers/lambda/agent.ts
index 07eccc7deac..23f0b3ac23f 100644
--- a/src/server/routers/lambda/agent.ts
+++ b/src/server/routers/lambda/agent.ts
@@ -169,6 +169,20 @@ export const agentRouter = router({
return ctx.agentModel.duplicate(input.agentId, input.newTitle);
}),
+ /**
+ * Get an agent by forkedFromIdentifier stored in params
+ * @returns agent id if exists, null otherwise
+ */
+ getAgentByForkedFromIdentifier: agentProcedure
+ .input(
+ z.object({
+ forkedFromIdentifier: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ return ctx.agentModel.getAgentByForkedFromIdentifier(input.forkedFromIdentifier);
+ }),
+
/**
* Get an agent by marketIdentifier
* @returns agent id if exists, null otherwise
diff --git a/src/server/routers/lambda/agentGroup.ts b/src/server/routers/lambda/agentGroup.ts
index 127be745980..1c27c2f8574 100644
--- a/src/server/routers/lambda/agentGroup.ts
+++ b/src/server/routers/lambda/agentGroup.ts
@@ -165,12 +165,14 @@ export const agentGroupRouter = router({
)
: undefined;
+ const normalizedConfig = ctx.agentGroupService.normalizeGroupConfig(
+ input.groupConfig.config as ChatGroupConfig | null,
+ );
+
const { group, supervisorAgentId } = await ctx.agentGroupRepo.createGroupWithSupervisor(
{
...input.groupConfig,
- config: ctx.agentGroupService.normalizeGroupConfig(
- input.groupConfig.config as ChatGroupConfig | null,
- ),
+ config: normalizedConfig,
},
memberAgentIds,
supervisorConfig as any,
@@ -213,6 +215,20 @@ export const agentGroupRouter = router({
return ctx.chatGroupModel.getGroupAgents(input.groupId);
}),
+ /**
+ * Get a group by forkedFromIdentifier stored in config
+ * @returns group id if exists, null otherwise
+ */
+ getGroupByForkedFromIdentifier: agentGroupProcedure
+ .input(
+ z.object({
+ forkedFromIdentifier: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ return ctx.chatGroupModel.getGroupByForkedFromIdentifier(input.forkedFromIdentifier);
+ }),
+
getGroupDetail: agentGroupProcedure
.input(z.object({ id: z.string() }))
.query(async ({ input, ctx }) => {
diff --git a/src/server/routers/lambda/market/agent.ts b/src/server/routers/lambda/market/agent.ts
index 865f1e691a5..ac64f0dddf9 100644
--- a/src/server/routers/lambda/market/agent.ts
+++ b/src/server/routers/lambda/market/agent.ts
@@ -163,31 +163,23 @@ const paginationSchema = z.object({
// Schema for the unified publish/create flow
const publishOrCreateSchema = z.object({
-
// Version data
-avatar: z.string().optional(),
-
+ avatar: z.string().optional(),
-category: z.string().optional(),
+ category: z.string().optional(),
-
-
+ changelog: z.string().optional(),
-changelog: z.string().optional(),
-
+ config: z.record(z.any()).optional(),
-config: z.record(z.any()).optional(),
-
+ description: z.string().optional(),
-description: z.string().optional(),
-
+ editorData: z.record(z.any()).optional(),
-editorData: z.record(z.any()).optional(),
-
-// Agent basic info
-identifier: z.string().optional(),
+ // Agent basic info
+ identifier: z.string().optional(),
// Optional - if not provided or not owned, will create new
-name: z.string(),
+ name: z.string(),
tags: z.array(z.string()).optional(),
tokenUsage: z.number().optional(),
});
@@ -320,11 +312,86 @@ export const agentRouter = router({
}
}),
+
/**
+ * Fork an agent
+ * POST /market/agent/:identifier/fork
+ */
+forkAgent: agentProcedure
+ .input(
+ z.object({
+ identifier: z.string(),
+ name: z.string().optional(),
+ sourceIdentifier: z.string(),
+ status: z.enum(['published', 'unpublished', 'archived', 'deprecated']).optional(),
+ versionNumber: z.number().optional(),
+ visibility: z.enum(['public', 'private', 'internal']).optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ log('forkAgent input: %O', input);
+
+ try {
+ // Call Market API directly to fork agent
+ const forkUrl = `${MARKET_BASE_URL}/api/v1/agents/${input.sourceIdentifier}/fork`;
+
+ const headers: Record<string, string> = {
+ 'Content-Type': 'application/json',
+ };
+
+ // Use trustedClientToken or accessToken for authentication
+ const userInfo = ctx.marketUserInfo as TrustedClientUserInfo | undefined;
+ const accessToken = (ctx as { marketOidcAccessToken?: string }).marketOidcAccessToken;
+
+ if (userInfo) {
+ const trustedClientToken = generateTrustedClientToken(userInfo);
+ if (trustedClientToken) {
+ headers['x-lobe-trust-token'] = trustedClientToken;
+ }
+ }
+
+ if (!headers['x-lobe-trust-token'] && accessToken) {
+ headers['Authorization'] = `Bearer ${accessToken}`;
+ }
+
+ const response = await fetch(forkUrl, {
+ body: JSON.stringify({
+ identifier: input.identifier,
+ name: input.name,
+ status: input.status,
+ versionNumber: input.versionNumber,
+ visibility: input.visibility,
+ }),
+ headers,
+ method: 'POST',
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ log('Fork agent failed: %s %s - %s', response.status, response.statusText, errorText);
+ throw new Error(`Failed to fork agent: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+ log('Fork agent success: %O', result);
+ return result;
+ } catch (error) {
+ log('Error forking agent: %O', error);
+ throw new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: error instanceof Error ? error.message : 'Failed to fork agent',
+ });
+ }
+ }),
+
+
+
+/**
* Get agent detail by identifier
* GET /market/agent/:identifier
*/
- getAgentDetail: agentProcedure
+getAgentDetail: agentProcedure
.input(z.object({ identifier: z.string() }))
.query(async ({ input, ctx }) => {
log('getAgentDetail input: %O', input);
@@ -342,11 +409,141 @@ export const agentRouter = router({
}
}),
- /**
+
+
+
+/**
+ * Get the fork source of an agent
+ * GET /market/agent/:identifier/fork-source
+ */
+getAgentForkSource: agentProcedure
+ .input(z.object({ identifier: z.string() }))
+ .query(async ({ input, ctx }) => {
+ log('getAgentForkSource input: %O', input);
+
+ try {
+ const forkSourceUrl = `${MARKET_BASE_URL}/api/v1/agents/${input.identifier}/fork-source`;
+
+ const headers: Record<string, string> = {
+ 'Content-Type': 'application/json',
+ };
+
+ const userInfo = ctx.marketUserInfo as TrustedClientUserInfo | undefined;
+ const accessToken = (ctx as { marketOidcAccessToken?: string }).marketOidcAccessToken;
+
+ if (userInfo) {
+ const trustedClientToken = generateTrustedClientToken(userInfo);
+ if (trustedClientToken) {
+ headers['x-lobe-trust-token'] = trustedClientToken;
+ }
+ }
+
+ if (!headers['x-lobe-trust-token'] && accessToken) {
+ headers['Authorization'] = `Bearer ${accessToken}`;
+ }
+
+ const response = await fetch(forkSourceUrl, {
+ headers,
+ method: 'GET',
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ log(
+ 'Get agent fork source failed: %s %s - %s',
+ response.status,
+ response.statusText,
+ errorText,
+ );
+ throw new Error(`Failed to get agent fork source: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+ return result;
+ } catch (error) {
+ log('Error getting agent fork source: %O', error);
+ throw new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: error instanceof Error ? error.message : 'Failed to get agent fork source',
+ });
+ }
+ }),
+
+
+
+
+
+
+/**
+ * Get all forks of an agent
+ * GET /market/agent/:identifier/forks
+ */
+getAgentForks: agentProcedure
+ .input(z.object({ identifier: z.string() }))
+ .query(async ({ input, ctx }) => {
+ log('getAgentForks input: %O', input);
+
+ try {
+ const forksUrl = `${MARKET_BASE_URL}/api/v1/agents/${input.identifier}/forks`;
+
+ const headers: Record<string, string> = {
+ 'Content-Type': 'application/json',
+ };
+
+ const userInfo = ctx.marketUserInfo as TrustedClientUserInfo | undefined;
+ const accessToken = (ctx as { marketOidcAccessToken?: string }).marketOidcAccessToken;
+
+ if (userInfo) {
+ const trustedClientToken = generateTrustedClientToken(userInfo);
+ if (trustedClientToken) {
+ headers['x-lobe-trust-token'] = trustedClientToken;
+ }
+ }
+
+ if (!headers['x-lobe-trust-token'] && accessToken) {
+ headers['Authorization'] = `Bearer ${accessToken}`;
+ }
+
+ const response = await fetch(forksUrl, {
+ headers,
+ method: 'GET',
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ log(
+ 'Get agent forks failed: %s %s - %s',
+ response.status,
+ response.statusText,
+ errorText,
+ );
+ throw new Error(`Failed to get agent forks: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+ return result;
+ } catch (error) {
+ log('Error getting agent forks: %O', error);
+ throw new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: error instanceof Error ? error.message : 'Failed to get agent forks',
+ });
+ }
+ }),
+
+
+
+
+
+
+
+/**
* Get own agents (requires authentication)
* GET /market/agent/own
*/
- getOwnAgents: agentProcedure.input(paginationSchema.optional()).query(async ({ input, ctx }) => {
+getOwnAgents: agentProcedure.input(paginationSchema.optional()).query(async ({ input, ctx }) => {
log('getOwnAgents input: %O', input);
try {
@@ -365,11 +562,16 @@ export const agentRouter = router({
}
}),
- /**
+
+
+
+
+
+/**
* Publish an agent (make it visible in marketplace)
* POST /market/agent/:identifier/publish
*/
- publishAgent: agentProcedure
+publishAgent: agentProcedure
.input(z.object({ identifier: z.string() }))
.mutation(async ({ input, ctx }) => {
log('publishAgent input: %O', input);
@@ -387,7 +589,11 @@ export const agentRouter = router({
}
}),
- /**
+
+
+
+
+/**
* Unified publish or create agent flow
* This procedure handles the complete publish logic:
* 1. Check if identifier exists and if current user is owner
@@ -396,7 +602,7 @@ export const agentRouter = router({
*
* Returns: { identifier, isNewAgent, success }
*/
- publishOrCreate: agentProcedure.input(publishOrCreateSchema).mutation(async ({ input, ctx }) => {
+publishOrCreate: agentProcedure.input(publishOrCreateSchema).mutation(async ({ input, ctx }) => {
log('publishOrCreate input: %O', input);
const { identifier: inputIdentifier, name, ...versionData } = input;
@@ -478,11 +684,13 @@ export const agentRouter = router({
}
}),
- /**
+
+
+/**
* Unpublish an agent (hide from marketplace, can be republished)
* POST /market/agent/:identifier/unpublish
*/
- unpublishAgent: agentProcedure
+unpublishAgent: agentProcedure
.input(z.object({ identifier: z.string() }))
.mutation(async ({ input, ctx }) => {
log('unpublishAgent input: %O', input);
diff --git a/src/server/routers/lambda/market/agentGroup.ts b/src/server/routers/lambda/market/agentGroup.ts
index 67ae3cb6587..715ed733713 100644
--- a/src/server/routers/lambda/market/agentGroup.ts
+++ b/src/server/routers/lambda/market/agentGroup.ts
@@ -200,13 +200,214 @@ export const agentGroupRouter = router({
}
}),
+
/**
+ * Fork an agent group
+ * POST /market/agent-group/:identifier/fork
+ */
+forkAgentGroup: agentGroupProcedure
+ .input(
+ z.object({
+ identifier: z.string(),
+ name: z.string().optional(),
+ sourceIdentifier: z.string(),
+ status: z.enum(['published', 'unpublished', 'archived', 'deprecated']).optional(),
+ versionNumber: z.number().optional(),
+ visibility: z.enum(['public', 'private', 'internal']).optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ log('forkAgentGroup input: %O', input);
+
+ try {
+ // Call Market API directly to fork agent group
+ const forkUrl = `${MARKET_BASE_URL}/api/v1/agent-groups/${input.sourceIdentifier}/fork`;
+
+ const headers: Record<string, string> = {
+ 'Content-Type': 'application/json',
+ };
+
+ // Use trustedClientToken or accessToken for authentication
+ const userInfo = ctx.marketUserInfo as TrustedClientUserInfo | undefined;
+ const accessToken = (ctx as { marketOidcAccessToken?: string }).marketOidcAccessToken;
+
+ if (userInfo) {
+ const trustedClientToken = generateTrustedClientToken(userInfo);
+ if (trustedClientToken) {
+ headers['x-lobe-trust-token'] = trustedClientToken;
+ }
+ }
+
+ if (!headers['x-lobe-trust-token'] && accessToken) {
+ headers['Authorization'] = `Bearer ${accessToken}`;
+ }
+
+ const response = await fetch(forkUrl, {
+ body: JSON.stringify({
+ identifier: input.identifier,
+ name: input.name,
+ status: input.status,
+ versionNumber: input.versionNumber,
+ visibility: input.visibility,
+ }),
+ headers,
+ method: 'POST',
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ log(
+ 'Fork agent group failed: %s %s - %s',
+ response.status,
+ response.statusText,
+ errorText,
+ );
+ throw new Error(`Failed to fork agent group: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+ log('Fork agent group success: %O', result);
+ return result;
+ } catch (error) {
+ log('Error forking agent group: %O', error);
+ throw new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: error instanceof Error ? error.message : 'Failed to fork agent group',
+ });
+ }
+ }),
+
+
+
+/**
+ * Get the fork source of an agent group
+ * GET /market/agent-group/:identifier/fork-source
+ */
+getAgentGroupForkSource: agentGroupProcedure
+ .input(z.object({ identifier: z.string() }))
+ .query(async ({ input, ctx }) => {
+ log('getAgentGroupForkSource input: %O', input);
+
+ try {
+ const forkSourceUrl = `${MARKET_BASE_URL}/api/v1/agent-groups/${input.identifier}/fork-source`;
+
+ const headers: Record<string, string> = {
+ 'Content-Type': 'application/json',
+ };
+
+ const userInfo = ctx.marketUserInfo as TrustedClientUserInfo | undefined;
+ const accessToken = (ctx as { marketOidcAccessToken?: string }).marketOidcAccessToken;
+
+ if (userInfo) {
+ const trustedClientToken = generateTrustedClientToken(userInfo);
+ if (trustedClientToken) {
+ headers['x-lobe-trust-token'] = trustedClientToken;
+ }
+ }
+
+ if (!headers['x-lobe-trust-token'] && accessToken) {
+ headers['Authorization'] = `Bearer ${accessToken}`;
+ }
+
+ const response = await fetch(forkSourceUrl, {
+ headers,
+ method: 'GET',
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ log(
+ 'Get agent group fork source failed: %s %s - %s',
+ response.status,
+ response.statusText,
+ errorText,
+ );
+ throw new Error(`Failed to get agent group fork source: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+ return result;
+ } catch (error) {
+ log('Error getting agent group fork source: %O', error);
+ throw new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: error instanceof Error ? error.message : 'Failed to get agent group fork source',
+ });
+ }
+ }),
+
+
+
+
+/**
+ * Get all forks of an agent group
+ * GET /market/agent-group/:identifier/forks
+ */
+getAgentGroupForks: agentGroupProcedure
+ .input(z.object({ identifier: z.string() }))
+ .query(async ({ input, ctx }) => {
+ log('getAgentGroupForks input: %O', input);
+
+ try {
+ const forksUrl = `${MARKET_BASE_URL}/api/v1/agent-groups/${input.identifier}/forks`;
+
+ const headers: Record<string, string> = {
+ 'Content-Type': 'application/json',
+ };
+
+ const userInfo = ctx.marketUserInfo as TrustedClientUserInfo | undefined;
+ const accessToken = (ctx as { marketOidcAccessToken?: string }).marketOidcAccessToken;
+
+ if (userInfo) {
+ const trustedClientToken = generateTrustedClientToken(userInfo);
+ if (trustedClientToken) {
+ headers['x-lobe-trust-token'] = trustedClientToken;
+ }
+ }
+
+ if (!headers['x-lobe-trust-token'] && accessToken) {
+ headers['Authorization'] = `Bearer ${accessToken}`;
+ }
+
+ const response = await fetch(forksUrl, {
+ headers,
+ method: 'GET',
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ log(
+ 'Get agent group forks failed: %s %s - %s',
+ response.status,
+ response.statusText,
+ errorText,
+ );
+ throw new Error(`Failed to get agent group forks: ${response.statusText}`);
+ }
+
+ const result = await response.json();
+ return result;
+ } catch (error) {
+ log('Error getting agent group forks: %O', error);
+ throw new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: error instanceof Error ? error.message : 'Failed to get agent group forks',
+ });
+ }
+ }),
+
+
+
+/**
* Unified publish or create agent group flow
* 1. Check if identifier exists and if current user is owner
* 2. If not owner or no identifier, create new group
* 3. Create new version for the group if updating
*/
- publishOrCreate: agentGroupProcedure
+publishOrCreate: agentGroupProcedure
.input(publishOrCreateGroupSchema)
.mutation(async ({ input, ctx }) => {
log('publishOrCreate input: %O', input);
@@ -294,3 +495,5 @@ export const agentGroupRouter = router({
}
}),
});
+
+export type AgentGroupRouter = typeof agentGroupRouter;
diff --git a/src/server/services/discover/index.ts b/src/server/services/discover/index.ts
index 164fc2f6157..5376ce5493c 100644
--- a/src/server/services/discover/index.ts
+++ b/src/server/services/discover/index.ts
@@ -1736,6 +1736,8 @@ export class DiscoverService {
locale,
})) as UserInfoResponse & {
agentGroups?: any[];
+ forkedAgentGroups?: any[];
+ forkedAgents?: any[];
};
if (!response?.user) {
@@ -1743,7 +1745,7 @@ export class DiscoverService {
return undefined;
}
- const { user, agents, agentGroups } = response;
+ const { user, agents, agentGroups, forkedAgents, forkedAgentGroups } = response;
// Transform agents to DiscoverAssistantItem format
const transformedAgents: DiscoverAssistantItem[] = (agents || []).map((agent: any) => ({
@@ -1783,9 +1785,55 @@ export class DiscoverService {
updatedAt: group.updatedAt,
}));
+ // Transform forkedAgents to DiscoverAssistantItem format
+ const transformedForkedAgents: DiscoverAssistantItem[] = (forkedAgents || []).map(
+ (agent: any) => ({
+ author: user.displayName || user.userName || user.namespace || '',
+ avatar: agent.avatar || '',
+ category: agent.category as any,
+ config: {} as any,
+ createdAt: agent.createdAt,
+ description: agent.description || '',
+ forkCount: agent.forkCount || 0,
+ forkedFromAgentId: agent.forkedFromAgentId || null,
+ homepage: `https://lobehub.com/discover/assistant/${agent.identifier}`,
+ identifier: agent.identifier,
+ installCount: agent.installCount,
+ knowledgeCount: agent.knowledgeCount || 0,
+ pluginCount: agent.pluginCount || 0,
+ schemaVersion: 1,
+ tags: agent.tags || [],
+ title: agent.name || agent.identifier,
+ tokenUsage: agent.tokenUsage || 0,
+ }),
+ );
+
+ // Transform forkedAgentGroups to DiscoverGroupAgentItem format
+ const transformedForkedAgentGroups = (forkedAgentGroups || []).map((group: any) => ({
+ author: user.displayName || user.userName || user.namespace || '',
+ avatar: group.avatar || '👥',
+ category: group.category as any,
+ createdAt: group.createdAt,
+ description: group.description || '',
+ forkCount: group.forkCount || 0,
+ forkedFromGroupId: group.forkedFromGroupId || null,
+ homepage: `https://lobehub.com/discover/group_agent/${group.identifier}`,
+ identifier: group.identifier,
+ installCount: group.installCount || 0,
+ isFeatured: group.isFeatured || false,
+ isOfficial: group.isOfficial || false,
+ memberCount: 0, // Will be populated from memberAgents in detail view
+ schemaVersion: 1,
+ tags: group.tags || [],
+ title: group.name || group.identifier,
+ updatedAt: group.updatedAt,
+ }));
+
const result: DiscoverUserProfile = {
agentGroups: transformedAgentGroups,
agents: transformedAgents,
+ forkedAgentGroups: transformedForkedAgentGroups,
+ forkedAgents: transformedForkedAgents,
user: {
avatarUrl: user.avatarUrl || null,
bannerUrl: user.meta?.bannerUrl || null,
@@ -1803,9 +1851,11 @@ export class DiscoverService {
};
log(
- 'getUserInfo: returning user profile with %d agents and %d groups',
+ 'getUserInfo: returning user profile with %d agents, %d groups, %d forked agents, %d forked groups',
result.agents.length,
result.agentGroups?.length || 0,
+ result.forkedAgents?.length || 0,
+ result.forkedAgentGroups?.length || 0,
);
return result;
} catch (error) {
diff --git a/src/services/agent.ts b/src/services/agent.ts
index e78a5aa929f..8162d2f7766 100644
--- a/src/services/agent.ts
+++ b/src/services/agent.ts
@@ -76,6 +76,14 @@ class AgentService {
return lambdaClient.agent.getAgentByMarketIdentifier.query({ marketIdentifier });
};
+ /**
+ * Get an agent by forkedFromIdentifier stored in params
+ * @returns agent id if exists, null otherwise
+ */
+ getAgentByForkedFromIdentifier = async (forkedFromIdentifier: string): Promise<string | null> => {
+ return lambdaClient.agent.getAgentByForkedFromIdentifier.query({ forkedFromIdentifier });
+ };
+
/**
* Create a new agent with session.
* Automatically normalizes market agent config (handles model as object).
diff --git a/src/services/chatGroup/index.ts b/src/services/chatGroup/index.ts
index 822d28be082..313fcd7c0f4 100644
--- a/src/services/chatGroup/index.ts
+++ b/src/services/chatGroup/index.ts
@@ -33,6 +33,14 @@ export interface SupervisorConfig {
}
class ChatGroupService {
+ /**
+ * Get a group by forkedFromIdentifier stored in config
+ * @returns group id if exists, null otherwise
+ */
+ getGroupByForkedFromIdentifier = async (forkedFromIdentifier: string): Promise<string | null> => {
+ return lambdaClient.group.getGroupByForkedFromIdentifier.query({ forkedFromIdentifier });
+ };
+
/**
* Create a group with a supervisor agent.
* The supervisor agent is automatically created as a virtual agent.
diff --git a/src/services/marketApi.ts b/src/services/marketApi.ts
index 4be04e6ff77..af16aeaecd4 100644
--- a/src/services/marketApi.ts
+++ b/src/services/marketApi.ts
@@ -5,6 +5,16 @@ import {
} from '@lobehub/market-sdk';
import { lambdaClient } from '@/libs/trpc/client';
+import type {
+ AgentForkRequest,
+ AgentForkResponse,
+ AgentForkSourceResponse,
+ AgentForksResponse,
+ AgentGroupForkRequest,
+ AgentGroupForkResponse,
+ AgentGroupForkSourceResponse,
+ AgentGroupForksResponse,
+} from '@/types/discover';
interface GetOwnAgentsParams {
page?: number;
@@ -101,6 +111,74 @@ export class MarketApiService {
async getOwnAgents(params?: GetOwnAgentsParams): Promise<AgentListResponse> {
return lambdaClient.market.agent.getOwnAgents.query(params) as Promise<AgentListResponse>;
}
+
+ // ==================== Fork Agent API ====================
+
+ /**
+ * Fork an agent
+ * @param sourceIdentifier - Source agent identifier
+ * @param forkData - Fork request parameters
+ */
+ async forkAgent(
+ sourceIdentifier: string,
+ forkData: AgentForkRequest,
+ ): Promise<AgentForkResponse> {
+ return lambdaClient.market.agent.forkAgent.mutate({
+ sourceIdentifier,
+ ...forkData,
+ });
+ }
+
+ /**
+ * Get all forks of an agent
+ * @param identifier - Agent identifier
+ */
+ async getAgentForks(identifier: string): Promise<AgentForksResponse> {
+ return lambdaClient.market.agent.getAgentForks.query({ identifier });
+ }
+
+ /**
+ * Get the fork source of an agent
+ * @param identifier - Agent identifier
+ * @returns Fork source information (null if not a fork)
+ */
+ async getAgentForkSource(identifier: string): Promise<AgentForkSourceResponse> {
+ return lambdaClient.market.agent.getAgentForkSource.query({ identifier });
+ }
+
+ // ==================== Fork Agent Group API ====================
+
+ /**
+ * Fork an agent group
+ * @param sourceIdentifier - Source agent group identifier
+ * @param forkData - Fork request parameters
+ */
+ async forkAgentGroup(
+ sourceIdentifier: string,
+ forkData: AgentGroupForkRequest,
+ ): Promise<AgentGroupForkResponse> {
+ return lambdaClient.market.agentGroup.forkAgentGroup.mutate({
+ sourceIdentifier,
+ ...forkData,
+ });
+ }
+
+ /**
+ * Get all forks of an agent group
+ * @param identifier - Agent group identifier
+ */
+ async getAgentGroupForks(identifier: string): Promise<AgentGroupForksResponse> {
+ return lambdaClient.market.agentGroup.getAgentGroupForks.query({ identifier });
+ }
+
+ /**
+ * Get the fork source of an agent group
+ * @param identifier - Agent group identifier
+ * @returns Fork source information (null if not a fork)
+ */
+ async getAgentGroupForkSource(identifier: string): Promise<AgentGroupForkSourceResponse> {
+ return lambdaClient.market.agentGroup.getAgentGroupForkSource.query({ identifier });
+ }
}
export const marketApiService = new MarketApiService();