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: improve group prompt context engine and fix group supervisor response issue (#11490)

Arvin Xu7d066eb7d18d
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index a9272b4d26b..cb28d42047d 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -61,18 +61,16 @@
"builtins.lobe-group-agent-builder.inspector.title": "Title",
"builtins.lobe-group-agent-builder.title": "Group Builder Expert",
"builtins.lobe-group-management.apiName.broadcast": "All speak",
- "builtins.lobe-group-management.apiName.createAgent": "Add group member",
"builtins.lobe-group-management.apiName.createWorkflow": "Plan workflow",
- "builtins.lobe-group-management.apiName.executeTask": "Execute task",
+ "builtins.lobe-group-management.apiName.executeAgentTask": "Execute agent task",
+ "builtins.lobe-group-management.apiName.executeAgentTasks": "Execute parallel agent tasks",
"builtins.lobe-group-management.apiName.getAgentInfo": "Get member info",
"builtins.lobe-group-management.apiName.interrupt": "Interrupt task",
- "builtins.lobe-group-management.apiName.inviteAgent": "Invite member",
- "builtins.lobe-group-management.apiName.removeAgent": "Remove member",
- "builtins.lobe-group-management.apiName.searchAgent": "Find relevant experts",
"builtins.lobe-group-management.apiName.speak": "Designated member speaks",
"builtins.lobe-group-management.apiName.summarize": "Summarize conversation",
"builtins.lobe-group-management.apiName.vote": "Start vote",
"builtins.lobe-group-management.inspector.broadcast.title": "Following Agents speak:",
+ "builtins.lobe-group-management.inspector.executeAgentTasks.title": "Assigning tasks to:",
"builtins.lobe-group-management.inspector.speak.title": "Designated Agent speaks:",
"builtins.lobe-group-management.title": "Group Coordinator",
"builtins.lobe-gtd.apiName.clearTodos": "Clear todos",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index 3d49ee519e5..ed56a6937b0 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -61,18 +61,16 @@
"builtins.lobe-group-agent-builder.inspector.title": "标题",
"builtins.lobe-group-agent-builder.title": "群组构建专家",
"builtins.lobe-group-management.apiName.broadcast": "所有人发言",
- "builtins.lobe-group-management.apiName.createAgent": "添加群组成员",
"builtins.lobe-group-management.apiName.createWorkflow": "规划工作流",
- "builtins.lobe-group-management.apiName.executeTask": "执行任务",
+ "builtins.lobe-group-management.apiName.executeAgentTask": "执行 Agent 任务",
+ "builtins.lobe-group-management.apiName.executeAgentTasks": "并行执行 Agent 任务",
"builtins.lobe-group-management.apiName.getAgentInfo": "获取成员信息",
"builtins.lobe-group-management.apiName.interrupt": "中断任务",
- "builtins.lobe-group-management.apiName.inviteAgent": "邀请成员",
- "builtins.lobe-group-management.apiName.removeAgent": "移除成员",
- "builtins.lobe-group-management.apiName.searchAgent": "寻找相关专家",
"builtins.lobe-group-management.apiName.speak": "指定成员发言",
"builtins.lobe-group-management.apiName.summarize": "总结对话",
"builtins.lobe-group-management.apiName.vote": "发起投票",
"builtins.lobe-group-management.inspector.broadcast.title": "以下 Agent 发言:",
+ "builtins.lobe-group-management.inspector.executeAgentTasks.title": "分配任务给:",
"builtins.lobe-group-management.inspector.speak.title": "指定 Agent 发言:",
"builtins.lobe-group-management.title": "群组协调",
"builtins.lobe-gtd.apiName.clearTodos": "清除待办",
diff --git a/locales/zh-CN/tool.json b/locales/zh-CN/tool.json
index f7512f9c926..44817e4439c 100644
--- a/locales/zh-CN/tool.json
+++ b/locales/zh-CN/tool.json
@@ -15,6 +15,8 @@
"agentGroupManagement.executeTask.thread": "线程 ID",
"agentGroupManagement.executeTask.timeout": "执行超时",
"agentGroupManagement.executeTask.tokens": "令牌使用量",
+ "agentGroupManagement.executeTasks.intervention.instructionPlaceholder": "执行此任务的详细指令...",
+ "agentGroupManagement.executeTasks.intervention.titlePlaceholder": "任务标题...",
"codeInterpreter-legacy.error": "执行出错",
"codeInterpreter-legacy.executing": "正在执行...",
"codeInterpreter-legacy.files": "文件:",
diff --git a/packages/builtin-agents/src/agents/group-supervisor/index.ts b/packages/builtin-agents/src/agents/group-supervisor/index.ts
index d969f72ad20..817bd68add8 100644
--- a/packages/builtin-agents/src/agents/group-supervisor/index.ts
+++ b/packages/builtin-agents/src/agents/group-supervisor/index.ts
@@ -1,3 +1,4 @@
+import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-builder';
import { GroupManagementIdentifier } from '@lobechat/builtin-tool-group-management';
import { GTDIdentifier } from '@lobechat/builtin-tool-gtd';
@@ -20,6 +21,11 @@ const resolveSystemRole = (ctx: GroupSupervisorContext): string => {
* - Strategically coordinating agent participation
* - Ensuring natural conversation flow
* - Matching user queries to appropriate agent expertise
+ *
+ * Tools:
+ * - GroupManagement: orchestration (speak, broadcast, executeAgentTask, etc.)
+ * - GroupAgentBuilder: member management (searchAgent, inviteAgent, createAgent, etc.)
+ * - GTD: task tracking
*/
export const GROUP_SUPERVISOR: BuiltinAgentDefinition = {
runtime: (ctx) => {
@@ -33,7 +39,12 @@ export const GROUP_SUPERVISOR: BuiltinAgentDefinition = {
chatConfig: {
enableHistoryCount: false,
},
- plugins: [GroupManagementIdentifier, GTDIdentifier, ...(ctx.plugins || [])],
+ plugins: [
+ GroupManagementIdentifier,
+ GroupAgentBuilderIdentifier,
+ GTDIdentifier,
+ ...(ctx.plugins || []),
+ ],
systemRole: resolveSystemRole(groupSupervisorContext),
};
},
diff --git a/packages/builtin-agents/src/agents/group-supervisor/systemRole.ts b/packages/builtin-agents/src/agents/group-supervisor/systemRole.ts
index a47fa71c4d1..5c23d1fc4d9 100644
--- a/packages/builtin-agents/src/agents/group-supervisor/systemRole.ts
+++ b/packages/builtin-agents/src/agents/group-supervisor/systemRole.ts
@@ -46,13 +46,6 @@ export const supervisorSystemRole = `You are LobeAI, an intelligent team coordin
- **Efficiency**: Use broadcast for parallel opinions, speak for sequential dependencies.
</orchestration_guidelines>
-<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>
-
<constraints>
- Only invoke agents defined in the participants list
- Never fabricate agent IDs or capabilities
diff --git a/packages/builtin-tool-cloud-sandbox/src/client/Inspector/EditLocalFile/index.tsx b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/EditLocalFile/index.tsx
new file mode 100644
index 00000000000..bed7cef4813
--- /dev/null
+++ b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/EditLocalFile/index.tsx
@@ -0,0 +1,93 @@
+'use client';
+
+import { type BuiltinInspectorProps } from '@lobechat/types';
+import { Icon, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { Minus, Plus } from 'lucide-react';
+import { type ReactNode, memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import { type EditLocalFileState } from '../../../types';
+import { FilePathDisplay } from '../../components/FilePathDisplay';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ separator: css`
+ margin-inline: 2px;
+ color: ${cssVar.colorTextQuaternary};
+ `,
+}));
+
+interface EditLocalFileParams {
+ file_path: string;
+ new_string: string;
+ old_string: string;
+}
+
+export const EditLocalFileInspector = memo<
+ BuiltinInspectorProps<EditLocalFileParams, EditLocalFileState>
+>(({ args, partialArgs, isArgumentsStreaming, pluginState, isLoading }) => {
+ const { t } = useTranslation('plugin');
+
+ const filePath = args?.file_path || partialArgs?.file_path || '';
+
+ // During argument streaming
+ if (isArgumentsStreaming) {
+ if (!filePath)
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.editLocalFile')}</span>
+ </div>
+ );
+
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.editLocalFile')}: </span>
+ <FilePathDisplay filePath={filePath} />
+ </div>
+ );
+ }
+
+ // Build stats parts with colors and icons
+ const linesAdded = pluginState?.linesAdded ?? 0;
+ const linesDeleted = pluginState?.linesDeleted ?? 0;
+
+ const statsParts: ReactNode[] = [];
+ if (linesAdded > 0) {
+ statsParts.push(
+ <Text as={'span'} code color={cssVar.colorSuccess} fontSize={12} key="added">
+ <Icon icon={Plus} size={12} />
+ {linesAdded}
+ </Text>,
+ );
+ }
+ if (linesDeleted > 0) {
+ statsParts.push(
+ <Text as={'span'} code color={cssVar.colorError} fontSize={12} key="deleted">
+ <Icon icon={Minus} size={12} />
+ {linesDeleted}
+ </Text>,
+ );
+ }
+
+ return (
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.editLocalFile')}: </span>
+ <FilePathDisplay filePath={filePath} />
+ {!isLoading && statsParts.length > 0 && (
+ <>
+ {' '}
+ {statsParts.map((part, index) => (
+ <span key={index}>
+ {index > 0 && <span className={styles.separator}> / </span>}
+ {part}
+ </span>
+ ))}
+ </>
+ )}
+ </div>
+ );
+});
+
+EditLocalFileInspector.displayName = 'EditLocalFileInspector';
diff --git a/packages/builtin-tool-cloud-sandbox/src/client/Inspector/GlobLocalFiles/index.tsx b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/GlobLocalFiles/index.tsx
new file mode 100644
index 00000000000..379bd3ccdf2
--- /dev/null
+++ b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/GlobLocalFiles/index.tsx
@@ -0,0 +1,73 @@
+'use client';
+
+import { type BuiltinInspectorProps } from '@lobechat/types';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { Check, X } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import { type GlobFilesState } from '../../../types';
+
+const styles = createStaticStyles(({ css }) => ({
+ statusIcon: css`
+ margin-block-end: -2px;
+ margin-inline-start: 4px;
+ `,
+}));
+
+interface GlobFilesParams {
+ path?: string;
+ pattern: string;
+}
+
+export const GlobLocalFilesInspector = memo<BuiltinInspectorProps<GlobFilesParams, GlobFilesState>>(
+ ({ args, partialArgs, isArgumentsStreaming, pluginState, isLoading }) => {
+ const { t } = useTranslation('plugin');
+
+ const pattern = args?.pattern || partialArgs?.pattern || '';
+
+ // During argument streaming
+ if (isArgumentsStreaming) {
+ if (!pattern)
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.globLocalFiles')}</span>
+ </div>
+ );
+
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.globLocalFiles')}: </span>
+ <span className={highlightTextStyles.primary}>{pattern}</span>
+ </div>
+ );
+ }
+
+ // Check if glob was successful
+ const totalCount = pluginState?.totalCount ?? 0;
+ const hasResults = totalCount > 0;
+
+ return (
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
+ <span style={{ marginInlineStart: 2 }}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.globLocalFiles')}: </span>
+ {pattern && <span className={highlightTextStyles.primary}>{pattern}</span>}
+ {isLoading ? null : pluginState ? (
+ hasResults ? (
+ <>
+ <span style={{ marginInlineStart: 4 }}>({totalCount})</span>
+ <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />
+ </>
+ ) : (
+ <X className={styles.statusIcon} color={cssVar.colorError} size={14} />
+ )
+ ) : null}
+ </span>
+ </div>
+ );
+ },
+);
+
+GlobLocalFilesInspector.displayName = 'GlobLocalFilesInspector';
diff --git a/packages/builtin-tool-cloud-sandbox/src/client/Inspector/GrepContent/index.tsx b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/GrepContent/index.tsx
new file mode 100644
index 00000000000..8ac8ee529b1
--- /dev/null
+++ b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/GrepContent/index.tsx
@@ -0,0 +1,69 @@
+'use client';
+
+import { type BuiltinInspectorProps } from '@lobechat/types';
+import { Text } from '@lobehub/ui';
+import { cssVar, cx } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import { type GrepContentState } from '../../../types';
+
+interface GrepContentParams {
+ include?: string;
+ path?: string;
+ pattern: string;
+}
+
+export const GrepContentInspector = memo<
+ BuiltinInspectorProps<GrepContentParams, GrepContentState>
+>(({ args, partialArgs, isArgumentsStreaming, pluginState, isLoading }) => {
+ const { t } = useTranslation('plugin');
+
+ const pattern = args?.pattern || partialArgs?.pattern || '';
+
+ // During argument streaming
+ if (isArgumentsStreaming) {
+ if (!pattern)
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.grepContent')}</span>
+ </div>
+ );
+
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.grepContent')}: </span>
+ <span className={highlightTextStyles.primary}>{pattern}</span>
+ </div>
+ );
+ }
+
+ // Check result count
+ const resultCount = pluginState?.totalMatches ?? 0;
+ const hasResults = resultCount > 0;
+
+ return (
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.grepContent')}: </span>
+ {pattern && <span className={highlightTextStyles.primary}>{pattern}</span>}
+ {!isLoading &&
+ pluginState &&
+ (hasResults ? (
+ <span style={{ marginInlineStart: 4 }}>({resultCount})</span>
+ ) : (
+ <Text
+ as={'span'}
+ color={cssVar.colorTextDescription}
+ fontSize={12}
+ style={{ marginInlineStart: 4 }}
+ >
+ ({t('builtins.lobe-local-system.inspector.noResults')})
+ </Text>
+ ))}
+ </div>
+ );
+});
+
+GrepContentInspector.displayName = 'GrepContentInspector';
diff --git a/packages/builtin-tool-cloud-sandbox/src/client/Inspector/ListLocalFiles/index.tsx b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/ListLocalFiles/index.tsx
new file mode 100644
index 00000000000..029a5b58013
--- /dev/null
+++ b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/ListLocalFiles/index.tsx
@@ -0,0 +1,68 @@
+'use client';
+
+import { type BuiltinInspectorProps } from '@lobechat/types';
+import { Text } from '@lobehub/ui';
+import { cssVar, cx } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import { type ListLocalFilesState } from '../../../types';
+import { FilePathDisplay } from '../../components/FilePathDisplay';
+
+interface ListLocalFilesParams {
+ path: string;
+}
+
+export const ListLocalFilesInspector = memo<
+ BuiltinInspectorProps<ListLocalFilesParams, ListLocalFilesState>
+>(({ args, partialArgs, isArgumentsStreaming, pluginState, isLoading }) => {
+ const { t } = useTranslation('plugin');
+
+ const path = args?.path || partialArgs?.path || '';
+
+ // During argument streaming
+ if (isArgumentsStreaming) {
+ if (!path)
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.listLocalFiles')}</span>
+ </div>
+ );
+
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.listLocalFiles')}: </span>
+ <FilePathDisplay filePath={path} isDirectory />
+ </div>
+ );
+ }
+
+ // Show result count if available
+ const resultCount = pluginState?.files?.length ?? 0;
+ const hasResults = resultCount > 0;
+
+ return (
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.listLocalFiles')}: </span>
+ <FilePathDisplay filePath={path} isDirectory />
+ {!isLoading &&
+ pluginState?.files &&
+ (hasResults ? (
+ <span style={{ marginInlineStart: 4 }}>({resultCount})</span>
+ ) : (
+ <Text
+ as={'span'}
+ color={cssVar.colorTextDescription}
+ fontSize={12}
+ style={{ marginInlineStart: 4 }}
+ >
+ ({t('builtins.lobe-local-system.inspector.noResults')})
+ </Text>
+ ))}
+ </div>
+ );
+});
+
+ListLocalFilesInspector.displayName = 'ListLocalFilesInspector';
diff --git a/packages/builtin-tool-cloud-sandbox/src/client/Inspector/ReadLocalFile/index.tsx b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/ReadLocalFile/index.tsx
new file mode 100644
index 00000000000..d9120d422e1
--- /dev/null
+++ b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/ReadLocalFile/index.tsx
@@ -0,0 +1,74 @@
+'use client';
+
+import { type BuiltinInspectorProps } from '@lobechat/types';
+import { createStaticStyles, cx } from 'antd-style';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import { type ReadLocalFileState } from '../../../types';
+import { FilePathDisplay } from '../../components/FilePathDisplay';
+
+const styles = createStaticStyles(({ css }) => ({
+ lineRange: css`
+ flex-shrink: 0;
+ margin-inline-start: 4px;
+ opacity: 0.7;
+ `,
+}));
+
+interface ReadLocalFileParams {
+ end_line?: number;
+ path: string;
+ start_line?: number;
+}
+
+export const ReadLocalFileInspector = memo<
+ BuiltinInspectorProps<ReadLocalFileParams, ReadLocalFileState>
+>(({ args, partialArgs, isArgumentsStreaming, isLoading }) => {
+ const { t } = useTranslation('plugin');
+
+ const filePath = args?.path || partialArgs?.path || '';
+ const startLine = args?.start_line || partialArgs?.start_line;
+ const endLine = args?.end_line || partialArgs?.end_line;
+
+ // Format line range display, e.g., "L1-L200"
+ const lineRangeText = useMemo(() => {
+ if (startLine === undefined && endLine === undefined) return null;
+ const start = startLine ?? 1;
+ const end = endLine;
+ if (end !== undefined) {
+ return `L${start}-L${end}`;
+ }
+ return `L${start}`;
+ }, [startLine, endLine]);
+
+ // During argument streaming
+ if (isArgumentsStreaming) {
+ if (!filePath)
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.readLocalFile')}</span>
+ </div>
+ );
+
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.readLocalFile')}: </span>
+ <FilePathDisplay filePath={filePath} />
+ {lineRangeText && <span className={styles.lineRange}>{lineRangeText}</span>}
+ </div>
+ );
+ }
+
+ return (
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.readLocalFile')}: </span>
+ <FilePathDisplay filePath={filePath} />
+ {lineRangeText && <span className={styles.lineRange}>{lineRangeText}</span>}
+ </div>
+ );
+});
+
+ReadLocalFileInspector.displayName = 'ReadLocalFileInspector';
diff --git a/packages/builtin-tool-cloud-sandbox/src/client/Inspector/SearchLocalFiles/index.tsx b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/SearchLocalFiles/index.tsx
new file mode 100644
index 00000000000..dde7d7608ae
--- /dev/null
+++ b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/SearchLocalFiles/index.tsx
@@ -0,0 +1,70 @@
+'use client';
+
+import { type BuiltinInspectorProps } from '@lobechat/types';
+import { Text } from '@lobehub/ui';
+import { cssVar, cx } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import { type SearchLocalFilesState } from '../../../types';
+
+interface SearchLocalFilesParams {
+ path?: string;
+ query: string;
+}
+
+export const SearchLocalFilesInspector = memo<
+ BuiltinInspectorProps<SearchLocalFilesParams, SearchLocalFilesState>
+>(({ args, partialArgs, isArgumentsStreaming, pluginState, isLoading }) => {
+ const { t } = useTranslation('plugin');
+
+ const query = args?.query || partialArgs?.query || '';
+
+ // During argument streaming
+ if (isArgumentsStreaming) {
+ if (!query)
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.searchLocalFiles')}</span>
+ </div>
+ );
+
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.searchLocalFiles')}: </span>
+ <span className={highlightTextStyles.primary}>{query}</span>
+ </div>
+ );
+ }
+
+ // Check if search returned results
+ const resultCount = pluginState?.results?.length ?? 0;
+ const hasResults = resultCount > 0;
+
+ return (
+ <div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
+ <span style={{ marginInlineStart: 2 }}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.searchLocalFiles')}: </span>
+ {query && <span className={highlightTextStyles.primary}>{query}</span>}
+ {!isLoading &&
+ pluginState?.results &&
+ (hasResults ? (
+ <span style={{ marginInlineStart: 4 }}>({resultCount})</span>
+ ) : (
+ <Text
+ as={'span'}
+ color={cssVar.colorTextDescription}
+ fontSize={12}
+ style={{ marginInlineStart: 4 }}
+ >
+ ({t('builtins.lobe-local-system.inspector.noResults')})
+ </Text>
+ ))}
+ </span>
+ </div>
+ );
+});
+
+SearchLocalFilesInspector.displayName = 'SearchLocalFilesInspector';
diff --git a/packages/builtin-tool-cloud-sandbox/src/client/Inspector/WriteLocalFile/index.tsx b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/WriteLocalFile/index.tsx
new file mode 100644
index 00000000000..7d65863a20b
--- /dev/null
+++ b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/WriteLocalFile/index.tsx
@@ -0,0 +1,57 @@
+'use client';
+
+import { type BuiltinInspectorProps } from '@lobechat/types';
+import { Icon, Text } from '@lobehub/ui';
+import { cssVar, cx } from 'antd-style';
+import { Plus } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import { type WriteLocalFileState } from '../../../types';
+import { FilePathDisplay } from '../../components/FilePathDisplay';
+
+interface WriteLocalFileParams {
+ content: string;
+ path: string;
+}
+
+export const WriteLocalFileInspector = memo<
+ BuiltinInspectorProps<WriteLocalFileParams, WriteLocalFileState>
+>(({ args, partialArgs, isArgumentsStreaming }) => {
+ const { t } = useTranslation('plugin');
+
+ const filePath = args?.path || partialArgs?.path || '';
+ const content = args?.content || partialArgs?.content || '';
+
+ // Calculate lines from content
+ const lines = content ? content.split('\n').length : 0;
+
+ // During argument streaming without path
+ if (isArgumentsStreaming && !filePath) {
+ return (
+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.writeLocalFile')}</span>
+ </div>
+ );
+ }
+
+ return (
+ <div
+ className={cx(inspectorTextStyles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}
+ >
+ <span>{t('builtins.lobe-cloud-sandbox.apiName.writeLocalFile')}: </span>
+ <FilePathDisplay filePath={filePath} />
+ {lines > 0 && (
+ <Text as={'span'} code color={cssVar.colorSuccess} fontSize={12}>
+ {' '}
+ <Icon icon={Plus} size={12} />
+ {lines}
+ </Text>
+ )}
+ </div>
+ );
+});
+
+WriteLocalFileInspector.displayName = 'WriteLocalFileInspector';
diff --git a/packages/builtin-tool-cloud-sandbox/src/client/Inspector/index.ts b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/index.ts
index 096f9c3fc0c..5baa5340ae7 100644
--- a/packages/builtin-tool-cloud-sandbox/src/client/Inspector/index.ts
+++ b/packages/builtin-tool-cloud-sandbox/src/client/Inspector/index.ts
@@ -1,11 +1,25 @@
import { CloudSandboxApiName } from '../../types';
+import { EditLocalFileInspector } from './EditLocalFile';
import { ExecuteCodeInspector } from './ExecuteCode';
+import { GlobLocalFilesInspector } from './GlobLocalFiles';
+import { GrepContentInspector } from './GrepContent';
+import { ListLocalFilesInspector } from './ListLocalFiles';
+import { ReadLocalFileInspector } from './ReadLocalFile';
import { RunCommandInspector } from './RunCommand';
+import { SearchLocalFilesInspector } from './SearchLocalFiles';
+import { WriteLocalFileInspector } from './WriteLocalFile';
/**
* Code Interpreter Inspector Components Registry
*/
export const CloudSandboxInspectors = {
+ [CloudSandboxApiName.editLocalFile]: EditLocalFileInspector,
[CloudSandboxApiName.executeCode]: ExecuteCodeInspector,
+ [CloudSandboxApiName.globLocalFiles]: GlobLocalFilesInspector,
+ [CloudSandboxApiName.grepContent]: GrepContentInspector,
+ [CloudSandboxApiName.listLocalFiles]: ListLocalFilesInspector,
+ [CloudSandboxApiName.readLocalFile]: ReadLocalFileInspector,
[CloudSandboxApiName.runCommand]: RunCommandInspector,
+ [CloudSandboxApiName.searchLocalFiles]: SearchLocalFilesInspector,
+ [CloudSandboxApiName.writeLocalFile]: WriteLocalFileInspector,
};
diff --git a/packages/builtin-tool-cloud-sandbox/src/client/Render/WriteFile/index.tsx b/packages/builtin-tool-cloud-sandbox/src/client/Render/WriteFile/index.tsx
index 0e96865e48b..ae777ef7f30 100644
--- a/packages/builtin-tool-cloud-sandbox/src/client/Render/WriteFile/index.tsx
+++ b/packages/builtin-tool-cloud-sandbox/src/client/Render/WriteFile/index.tsx
@@ -1,54 +1,73 @@
'use client';
-import { CheckCircleFilled, CloseCircleFilled } from '@ant-design/icons';
import { type BuiltinRenderProps } from '@lobechat/types';
-import { Flexbox, Text } from '@lobehub/ui';
-import { createStaticStyles, cssVar } from 'antd-style';
+import { Block, Highlighter } from '@lobehub/ui';
import { memo } from 'react';
import { type WriteLocalFileState } from '../../../types';
-const styles = createStaticStyles(({ css }) => ({
- container: css`
- overflow: hidden;
- padding-inline: 8px 0;
- `,
- statusIcon: css`
- font-size: 12px;
- `,
-}));
-
interface WriteLocalFileParams {
content: string;
createDirectories?: boolean;
path: string;
}
+/**
+ * Get file extension from path
+ */
+const getFileExtension = (path: string): string => {
+ const parts = path.split('.');
+ return parts.length > 1 ? parts.pop()?.toLowerCase() || 'text' : 'text';
+};
+
+/**
+ * Map file extension to Highlighter language
+ */
+const getLanguageFromExtension = (ext: string): string => {
+ const languageMap: Record<string, string> = {
+ css: 'css',
+ go: 'go',
+ html: 'html',
+ java: 'java',
+ js: 'javascript',
+ json: 'json',
+ jsx: 'jsx',
+ md: 'markdown',
+ py: 'python',
+ rs: 'rust',
+ scss: 'scss',
+ sh: 'bash',
+ sql: 'sql',
+ ts: 'typescript',
+ tsx: 'tsx',
+ xml: 'xml',
+ yaml: 'yaml',
+ yml: 'yaml',
+ };
+ return languageMap[ext] || 'text';
+};
+
const WriteFile = memo<BuiltinRenderProps<WriteLocalFileParams, WriteLocalFileState>>(
- ({ args, pluginState }) => {
- const isSuccess = pluginState?.success;
+ ({ args }) => {
+ if (!args?.content) {
+ return null;
+ }
+
+ const ext = getFileExtension(args.path);
+ const language = getLanguageFromExtension(ext);
return (
- <Flexbox className={styles.container} gap={8}>
- <Flexbox align={'center'} gap={8} horizontal>
- {pluginState === undefined ? null : isSuccess ? (
- <CheckCircleFilled
- className={styles.statusIcon}
- style={{ color: cssVar.colorSuccess }}
- />
- ) : (
- <CloseCircleFilled className={styles.statusIcon} style={{ color: cssVar.colorError }} />
- )}
- <Text as={'span'} code fontSize={12}>
- {isSuccess ? `✅ Written to ${args.path}` : `❌ Failed to write ${args.path}`}
- </Text>
- {pluginState?.bytesWritten !== undefined && (
- <Text as={'span'} code fontSize={12} type={'secondary'}>
- ({pluginState.bytesWritten} bytes)
- </Text>
- )}
- </Flexbox>
- </Flexbox>
+ <Block padding={8} variant={'outlined'}>
+ <Highlighter
+ language={language}
+ showLanguage
+ style={{ maxHeight: 400, overflow: 'auto' }}
+ variant={'borderless'}
+ wrap
+ >
+ {args.content}
+ </Highlighter>
+ </Block>
);
},
);
diff --git a/packages/builtin-tool-cloud-sandbox/src/client/components/FilePathDisplay.tsx b/packages/builtin-tool-cloud-sandbox/src/client/components/FilePathDisplay.tsx
new file mode 100644
index 00000000000..0a8c53d44ae
--- /dev/null
+++ b/packages/builtin-tool-cloud-sandbox/src/client/components/FilePathDisplay.tsx
@@ -0,0 +1,52 @@
+'use client';
+
+import { MaterialFileTypeIcon } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import path from 'path-browserify-esm';
+import { memo, useMemo } from 'react';
+
+const styles = createStaticStyles(({ css }) => ({
+ icon: css`
+ flex-shrink: 0;
+ margin-inline-end: 4px;
+ `,
+ text: css`
+ color: ${cssVar.colorText};
+ `,
+}));
+
+interface FilePathDisplayProps {
+ filePath: string;
+ isDirectory?: boolean;
+}
+
+export const FilePathDisplay = memo<FilePathDisplayProps>(({ filePath, isDirectory }) => {
+ const { displayPath, name } = useMemo(() => {
+ if (!filePath) return { displayPath: '', name: '' };
+ const { base, dir } = path.parse(filePath);
+ const parentDir = path.basename(dir);
+ return {
+ displayPath: parentDir ? `${parentDir}/${base}` : base,
+ name: base,
+ };
+ }, [filePath]);
+
+ if (!filePath) return null;
+
+ return (
+ <>
+ {name && (
+ <MaterialFileTypeIcon
+ className={styles.icon}
+ filename={name}
+ size={16}
+ type={isDirectory ? 'folder' : 'file'}
+ variant={'raw'}
+ />
+ )}
+ {displayPath && <span className={styles.text}>{displayPath}</span>}
+ </>
+ );
+});
+
+FilePathDisplay.displayName = 'FilePathDisplay';
diff --git a/packages/builtin-tool-group-management/src/client/Inspector/ExecuteTasks/index.tsx b/packages/builtin-tool-group-management/src/client/Inspector/ExecuteTasks/index.tsx
new file mode 100644
index 00000000000..70d4d78092c
--- /dev/null
+++ b/packages/builtin-tool-group-management/src/client/Inspector/ExecuteTasks/index.tsx
@@ -0,0 +1,90 @@
+'use client';
+
+import { DEFAULT_AVATAR } from '@lobechat/const';
+import type { AgentGroupMember, BuiltinInspectorProps } from '@lobechat/types';
+import { Avatar, Flexbox } from '@lobehub/ui';
+import { createStaticStyles, cx, useTheme } from 'antd-style';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+import { shinyTextStyles } from '@/styles';
+
+import type { ExecuteTasksParams } from '../../../types';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ root: css`
+ overflow: hidden;
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ `,
+ title: css`
+ flex-shrink: 0;
+ color: ${cssVar.colorTextSecondary};
+ white-space: nowrap;
+ `,
+}));
+
+export const ExecuteTasksInspector = memo<BuiltinInspectorProps<ExecuteTasksParams>>(
+ ({ args, partialArgs, isArgumentsStreaming }) => {
+ const { t } = useTranslation('plugin');
+
+ const tasks = args?.tasks || partialArgs?.tasks || [];
+ const agentIds = useMemo(() => tasks.map((task) => task.agentId).filter(Boolean), [tasks]);
+
+ // Get active group ID and agents from store
+ const activeGroupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
+ const groupAgents = useAgentGroupStore((s) =>
+ activeGroupId ? agentGroupSelectors.getGroupAgents(activeGroupId)(s) : [],
+ );
+ const theme = useTheme();
+
+ // Get agent details for the task targets
+ const agents = useMemo(() => {
+ if (!agentIds.length || !groupAgents.length) return [];
+ return agentIds
+ .map((id) => groupAgents.find((agent) => agent.id === id))
+ .filter((agent): agent is AgentGroupMember => !!agent);
+ }, [agentIds, groupAgents]);
+
+ // Transform agents to Avatar.Group format
+ const avatarItems = useMemo(
+ () =>
+ agents.map((agent) => ({
+ avatar: agent.avatar || DEFAULT_AVATAR,
+ background: agent.backgroundColor || theme.colorBgContainer,
+ key: agent.id,
+ title: agent.title || undefined,
+ })),
+ [agents, theme.colorBgContainer],
+ );
+
+ if (isArgumentsStreaming && agents.length === 0) {
+ return (
+ <div className={cx(styles.root, shinyTextStyles.shinyText)}>
+ <span>{t('builtins.lobe-group-management.apiName.executeAgentTasks')}</span>
+ </div>
+ );
+ }
+
+ return (
+ <Flexbox
+ align={'center'}
+ className={cx(styles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}
+ gap={8}
+ horizontal
+ >
+ <span className={styles.title}>
+ {t('builtins.lobe-group-management.inspector.executeAgentTasks.title')}
+ </span>
+ {avatarItems.length > 0 && <Avatar.Group items={avatarItems} shape={'circle'} size={24} />}
+ </Flexbox>
+ );
+ },
+);
+
+ExecuteTasksInspector.displayName = 'ExecuteTasksInspector';
+
+export default ExecuteTasksInspector;
diff --git a/packages/builtin-tool-group-management/src/client/Inspector/index.ts b/packages/builtin-tool-group-management/src/client/Inspector/index.ts
index a4385b51250..da292910bf8 100644
--- a/packages/builtin-tool-group-management/src/client/Inspector/index.ts
+++ b/packages/builtin-tool-group-management/src/client/Inspector/index.ts
@@ -2,6 +2,7 @@ import { type BuiltinInspector } from '@lobechat/types';
import { GroupManagementApiName } from '../../types';
import { BroadcastInspector } from './Broadcast';
+import { ExecuteTasksInspector } from './ExecuteTasks';
import { SpeakInspector } from './Speak';
/**
@@ -12,5 +13,6 @@ import { SpeakInspector } from './Speak';
*/
export const GroupManagementInspectors: Record<string, BuiltinInspector> = {
[GroupManagementApiName.broadcast]: BroadcastInspector as BuiltinInspector,
+ [GroupManagementApiName.executeAgentTasks]: ExecuteTasksInspector as BuiltinInspector,
[GroupManagementApiName.speak]: SpeakInspector as BuiltinInspector,
};
diff --git a/packages/builtin-tool-group-management/src/client/Intervention/ExecuteTasks.tsx b/packages/builtin-tool-group-management/src/client/Intervention/ExecuteTasks.tsx
new file mode 100644
index 00000000000..2c5148d4c61
--- /dev/null
+++ b/packages/builtin-tool-group-management/src/client/Intervention/ExecuteTasks.tsx
@@ -0,0 +1,237 @@
+'use client';
+
+import { DEFAULT_AVATAR } from '@lobechat/const';
+import { BuiltinInterventionProps } from '@lobechat/types';
+import { Avatar, Flexbox, Icon, Tooltip } from '@lobehub/ui';
+import { Collapse, Input, InputNumber } from 'antd';
+import { createStaticStyles, useTheme } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { Clock, Trash2 } from 'lucide-react';
+import { ChangeEvent, memo, useCallback, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+
+import type { ExecuteTasksParams, TaskItem } from '../../types';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ agentTitle: css`
+ font-size: 14px;
+ font-weight: 500;
+ color: ${cssVar.colorText};
+ `,
+ container: css`
+ padding-block: 12px;
+ border-radius: ${cssVar.borderRadius};
+ `,
+ deleteButton: css`
+ cursor: pointer;
+ color: ${cssVar.colorTextTertiary};
+ transition: color 0.2s;
+
+ &:hover {
+ color: ${cssVar.colorError};
+ }
+ `,
+ taskCard: css`
+ .ant-collapse-header {
+ padding-block: 8px !important;
+ padding-inline: 12px !important;
+ }
+
+ .ant-collapse-content-box {
+ padding: 12px !important;
+ }
+ `,
+ taskTitle: css`
+ font-size: 13px;
+ font-weight: 500;
+ color: ${cssVar.colorText};
+ `,
+ timeoutInput: css`
+ width: 100px;
+ `,
+}));
+
+const DEFAULT_TIMEOUT = 1_800_000; // 30 minutes
+
+interface TaskEditorProps {
+ index: number;
+ onChange: (index: number, updates: Partial<TaskItem>) => void;
+ onDelete: (index: number) => void;
+ task: TaskItem;
+}
+
+const TaskEditor = memo<TaskEditorProps>(({ task, index, onChange, onDelete }) => {
+ const { t } = useTranslation('tool');
+ const theme = useTheme();
+
+ // Get agent info from store
+ const activeGroupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
+ const agent = useAgentGroupStore((s) =>
+ task.agentId && activeGroupId
+ ? agentGroupSelectors.getAgentByIdFromGroup(activeGroupId, task.agentId)(s)
+ : undefined,
+ );
+
+ const handleTitleChange = useCallback(
+ (e: ChangeEvent<HTMLInputElement>) => {
+ onChange(index, { title: e.target.value });
+ },
+ [index, onChange],
+ );
+
+ const handleInstructionChange = useCallback(
+ (e: ChangeEvent<HTMLTextAreaElement>) => {
+ onChange(index, { instruction: e.target.value });
+ },
+ [index, onChange],
+ );
+
+ const handleTimeoutChange = useCallback(
+ (value: number | null) => {
+ if (value !== null) {
+ onChange(index, { timeout: value * 60 * 1000 });
+ }
+ },
+ [index, onChange],
+ );
+
+ const handleDelete = useCallback(() => {
+ onDelete(index);
+ }, [index, onDelete]);
+
+ const header = (
+ <Flexbox align={'center'} gap={8} horizontal justify={'space-between'}>
+ <Flexbox align={'center'} flex={1} gap={8} horizontal style={{ minWidth: 0 }}>
+ <Avatar
+ avatar={agent?.avatar || DEFAULT_AVATAR}
+ background={agent?.backgroundColor || theme.colorBgContainer}
+ shape={'square'}
+ size={24}
+ />
+ <span className={styles.taskTitle}>{task.title || agent?.title || 'Task'}</span>
+ </Flexbox>
+ <Flexbox align={'center'} gap={8} horizontal onClick={(e) => e.stopPropagation()}>
+ <Tooltip title={t('agentGroupManagement.executeTask.intervention.timeout')}>
+ <Clock size={14} />
+ </Tooltip>
+ <InputNumber
+ className={styles.timeoutInput}
+ max={120}
+ min={1}
+ onChange={handleTimeoutChange}
+ size={'small'}
+ suffix={t('agentGroupManagement.executeTask.intervention.timeoutUnit')}
+ value={Math.round((task.timeout || DEFAULT_TIMEOUT) / 60_000)}
+ variant={'filled'}
+ />
+ <Icon
+ className={styles.deleteButton}
+ icon={Trash2}
+ onClick={handleDelete}
+ size={{ size: 16 }}
+ />
+ </Flexbox>
+ </Flexbox>
+ );
+
+ return (
+ <Collapse
+ className={styles.taskCard}
+ defaultActiveKey={[index]}
+ items={[
+ {
+ children: (
+ <Flexbox gap={12}>
+ <Input
+ onChange={handleTitleChange}
+ placeholder={t('agentGroupManagement.executeTasks.intervention.titlePlaceholder')}
+ value={task.title}
+ />
+ <Input.TextArea
+ autoSize={{ maxRows: 8, minRows: 4 }}
+ onChange={handleInstructionChange}
+ placeholder={t(
+ 'agentGroupManagement.executeTasks.intervention.instructionPlaceholder',
+ )}
+ value={task.instruction}
+ />
+ </Flexbox>
+ ),
+ key: index,
+ label: header,
+ },
+ ]}
+ />
+ );
+});
+
+/**
+ * ExecuteTasks Intervention Component
+ *
+ * Allows users to review and modify multiple tasks before execution.
+ */
+const ExecuteTasksIntervention = memo<BuiltinInterventionProps<ExecuteTasksParams>>(
+ ({ args, onArgsChange, registerBeforeApprove }) => {
+ // Local state
+ const [tasks, setTasks] = useState<TaskItem[]>(args?.tasks || []);
+ const [hasChanges, setHasChanges] = useState(false);
+
+ // Sync local state when args change externally
+ useEffect(() => {
+ if (!hasChanges) {
+ setTasks(args?.tasks || []);
+ }
+ }, [args?.tasks, hasChanges]);
+
+ // Handle task change
+ const handleTaskChange = useCallback((index: number, updates: Partial<TaskItem>) => {
+ setTasks((prev) => {
+ const newTasks = [...prev];
+ newTasks[index] = { ...newTasks[index], ...updates };
+ return newTasks;
+ });
+ setHasChanges(true);
+ }, []);
+
+ // Handle task delete
+ const handleTaskDelete = useCallback((index: number) => {
+ setTasks((prev) => prev.filter((_, i) => i !== index));
+ setHasChanges(true);
+ }, []);
+
+ // Save changes before approval
+ useEffect(() => {
+ if (!registerBeforeApprove) return;
+
+ const cleanup = registerBeforeApprove('executeTasks', async () => {
+ if (hasChanges && onArgsChange) {
+ await onArgsChange({ ...args, tasks });
+ }
+ });
+
+ return cleanup;
+ }, [registerBeforeApprove, hasChanges, tasks, args, onArgsChange]);
+
+ return (
+ <Flexbox className={styles.container} gap={12}>
+ {tasks.map((task, index) => (
+ <TaskEditor
+ index={index}
+ key={task.agentId || index}
+ onChange={handleTaskChange}
+ onDelete={handleTaskDelete}
+ task={task}
+ />
+ ))}
+ </Flexbox>
+ );
+ },
+ isEqual,
+);
+
+ExecuteTasksIntervention.displayName = 'ExecuteTasksIntervention';
+
+export default ExecuteTasksIntervention;
diff --git a/packages/builtin-tool-group-management/src/client/Intervention/index.ts b/packages/builtin-tool-group-management/src/client/Intervention/index.ts
index 4a494bed1e1..b41b7502960 100644
--- a/packages/builtin-tool-group-management/src/client/Intervention/index.ts
+++ b/packages/builtin-tool-group-management/src/client/Intervention/index.ts
@@ -2,6 +2,7 @@ import { BuiltinIntervention } from '@lobechat/types';
import { GroupManagementApiName } from '../../types';
import ExecuteTaskIntervention from './ExecuteTask';
+import ExecuteTasksIntervention from './ExecuteTasks';
/**
* Group Management Tool Intervention Components Registry
@@ -10,7 +11,9 @@ import ExecuteTaskIntervention from './ExecuteTask';
* before the tool is executed.
*/
export const GroupManagementInterventions: Record<string, BuiltinIntervention> = {
- [GroupManagementApiName.executeTask]: ExecuteTaskIntervention as BuiltinIntervention,
+ [GroupManagementApiName.executeAgentTask]: ExecuteTaskIntervention as BuiltinIntervention,
+ [GroupManagementApiName.executeAgentTasks]: ExecuteTasksIntervention as BuiltinIntervention,
};
export { default as ExecuteTaskIntervention } from './ExecuteTask';
+export { default as ExecuteTasksIntervention } from './ExecuteTasks';
diff --git a/packages/builtin-tool-group-management/src/client/Render/index.ts b/packages/builtin-tool-group-management/src/client/Render/index.ts
index f05eff79e5e..c3bf239e2e0 100644
--- a/packages/builtin-tool-group-management/src/client/Render/index.ts
+++ b/packages/builtin-tool-group-management/src/client/Render/index.ts
@@ -8,7 +8,7 @@ import SpeakRender from './Speak';
*/
export const GroupManagementRenders = {
[GroupManagementApiName.broadcast]: BroadcastRender,
- [GroupManagementApiName.executeTask]: ExecuteTaskRender,
+ [GroupManagementApiName.executeAgentTask]: ExecuteTaskRender,
[GroupManagementApiName.speak]: SpeakRender,
};
diff --git a/packages/builtin-tool-group-management/src/client/Streaming/ExecuteTask/index.tsx b/packages/builtin-tool-group-management/src/client/Streaming/ExecuteTask/index.tsx
new file mode 100644
index 00000000000..17afba152b8
--- /dev/null
+++ b/packages/builtin-tool-group-management/src/client/Streaming/ExecuteTask/index.tsx
@@ -0,0 +1,69 @@
+'use client';
+
+import { DEFAULT_AVATAR } from '@lobechat/const';
+import type { BuiltinStreamingProps } from '@lobechat/types';
+import { Avatar, Flexbox, Markdown } from '@lobehub/ui';
+import { createStaticStyles, useTheme } from 'antd-style';
+import { memo } from 'react';
+
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+
+import type { ExecuteTaskParams } from '../../../types';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ agentTitle: css`
+ font-size: 14px;
+ font-weight: 500;
+ color: ${cssVar.colorText};
+ `,
+ container: css`
+ padding: 12px;
+ border-radius: 8px;
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ task: css`
+ font-size: 13px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+}));
+
+export const ExecuteTaskStreaming = memo<BuiltinStreamingProps<ExecuteTaskParams>>(({ args }) => {
+ const { agentId, task } = args || {};
+ const theme = useTheme();
+
+ // Get active group ID and agent from store
+ const activeGroupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
+ const agent = useAgentGroupStore((s) =>
+ activeGroupId && agentId
+ ? agentGroupSelectors.getAgentByIdFromGroup(activeGroupId, agentId)(s)
+ : undefined,
+ );
+
+ if (!task) return null;
+
+ return (
+ <div className={styles.container}>
+ <Flexbox gap={8}>
+ <Flexbox align={'center'} gap={8} horizontal>
+ <Avatar
+ avatar={agent?.avatar || DEFAULT_AVATAR}
+ background={agent?.backgroundColor || theme.colorBgContainer}
+ shape={'square'}
+ size={24}
+ />
+ <span className={styles.agentTitle}>{agent?.title || 'Agent'}</span>
+ </Flexbox>
+ <div className={styles.task}>
+ <Markdown animated variant={'chat'}>
+ {task}
+ </Markdown>
+ </div>
+ </Flexbox>
+ </div>
+ );
+});
+
+ExecuteTaskStreaming.displayName = 'ExecuteTaskStreaming';
+
+export default ExecuteTaskStreaming;
diff --git a/packages/builtin-tool-group-management/src/client/Streaming/ExecuteTasks/index.tsx b/packages/builtin-tool-group-management/src/client/Streaming/ExecuteTasks/index.tsx
new file mode 100644
index 00000000000..2f12098ae03
--- /dev/null
+++ b/packages/builtin-tool-group-management/src/client/Streaming/ExecuteTasks/index.tsx
@@ -0,0 +1,87 @@
+'use client';
+
+import { DEFAULT_AVATAR } from '@lobechat/const';
+import type { AgentGroupMember, BuiltinStreamingProps } from '@lobechat/types';
+import { Avatar, Flexbox, Markdown } from '@lobehub/ui';
+import { createStaticStyles, useTheme } from 'antd-style';
+import { memo, useMemo } from 'react';
+
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+
+import type { ExecuteTasksParams } from '../../../types';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ container: css`
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ `,
+ instruction: css`
+ font-size: 13px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ taskCard: css`
+ padding: 12px;
+ border-radius: 8px;
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ taskTitle: css`
+ font-size: 13px;
+ font-weight: 500;
+ color: ${cssVar.colorText};
+ `,
+}));
+
+export const ExecuteTasksStreaming = memo<BuiltinStreamingProps<ExecuteTasksParams>>(({ args }) => {
+ const { tasks } = args || {};
+ const theme = useTheme();
+
+ // Get active group ID and agents from store
+ const activeGroupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
+ const groupAgents = useAgentGroupStore((s) =>
+ activeGroupId ? agentGroupSelectors.getGroupAgents(activeGroupId)(s) : [],
+ );
+
+ // Get agent details for each task
+ const tasksWithAgents = useMemo(() => {
+ if (!tasks?.length || !groupAgents.length) return [];
+ return tasks.map((task) => ({
+ ...task,
+ agent: groupAgents.find((agent) => agent.id === task.agentId) as AgentGroupMember | undefined,
+ }));
+ }, [tasks, groupAgents]);
+
+ if (!tasksWithAgents.length) return null;
+
+ return (
+ <div className={styles.container}>
+ {tasksWithAgents.map((task, index) => (
+ <div className={styles.taskCard} key={task.agentId || index}>
+ <Flexbox gap={8}>
+ <Flexbox align={'center'} gap={8} horizontal>
+ <Avatar
+ avatar={task.agent?.avatar || DEFAULT_AVATAR}
+ background={task.agent?.backgroundColor || theme.colorBgContainer}
+ shape={'square'}
+ size={20}
+ />
+ <span className={styles.taskTitle}>{task.title || task.agent?.title || 'Task'}</span>
+ </Flexbox>
+ {task.instruction && (
+ <div className={styles.instruction}>
+ <Markdown animated variant={'chat'}>
+ {task.instruction}
+ </Markdown>
+ </div>
+ )}
+ </Flexbox>
+ </div>
+ ))}
+ </div>
+ );
+});
+
+ExecuteTasksStreaming.displayName = 'ExecuteTasksStreaming';
+
+export default ExecuteTasksStreaming;
diff --git a/packages/builtin-tool-group-management/src/client/Streaming/index.ts b/packages/builtin-tool-group-management/src/client/Streaming/index.ts
index 88a094f5598..4c1d9f5e523 100644
--- a/packages/builtin-tool-group-management/src/client/Streaming/index.ts
+++ b/packages/builtin-tool-group-management/src/client/Streaming/index.ts
@@ -2,6 +2,8 @@ import type { BuiltinStreaming } from '@lobechat/types';
import { GroupManagementApiName } from '../../types';
import { BroadcastStreaming } from './Broadcast';
+import { ExecuteTaskStreaming } from './ExecuteTask';
+import { ExecuteTasksStreaming } from './ExecuteTasks';
import { SpeakStreaming } from './Speak';
/**
@@ -12,5 +14,7 @@ import { SpeakStreaming } from './Speak';
*/
export const GroupManagementStreamings: Record<string, BuiltinStreaming> = {
[GroupManagementApiName.broadcast]: BroadcastStreaming as BuiltinStreaming,
+ [GroupManagementApiName.executeAgentTask]: ExecuteTaskStreaming as BuiltinStreaming,
+ [GroupManagementApiName.executeAgentTasks]: ExecuteTasksStreaming as BuiltinStreaming,
[GroupManagementApiName.speak]: SpeakStreaming as BuiltinStreaming,
};
diff --git a/packages/builtin-tool-group-management/src/executor.test.ts b/packages/builtin-tool-group-management/src/executor.test.ts
index 8ff62871e33..33b53d35cd4 100644
--- a/packages/builtin-tool-group-management/src/executor.test.ts
+++ b/packages/builtin-tool-group-management/src/executor.test.ts
@@ -8,29 +8,12 @@ import type {
import { groupManagementExecutor } from './executor';
// Mock agentGroupStore
-const mockAddAgentsToGroup = vi.fn();
-const mockRemoveAgentFromGroup = vi.fn();
-
vi.mock('@/store/agentGroup', () => ({
agentGroupSelectors: {
getAgentByIdFromGroup: vi.fn(() => () => undefined),
},
useAgentGroupStore: {
- getState: () => ({
- addAgentsToGroup: mockAddAgentsToGroup,
- removeAgentFromGroup: mockRemoveAgentFromGroup,
- }),
- },
-}));
-
-// Mock agentService
-const mockQueryAgents = vi.fn();
-const mockCreateAgent = vi.fn();
-
-vi.mock('@/services/agent', () => ({
- agentService: {
- createAgent: (...args: any[]) => mockCreateAgent(...args),
- queryAgents: (...args: any[]) => mockQueryAgents(...args),
+ getState: () => ({}),
},
}));
@@ -288,78 +271,6 @@ describe('GroupManagementExecutor', () => {
});
});
- describe('searchAgent', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it('should return community not supported message when source is community', async () => {
- const ctx = createMockContext();
-
- const result = await groupManagementExecutor.searchAgent(
- { query: 'test', source: 'community' },
- ctx,
- );
-
- expect(result.success).toBe(true);
- expect(result.content).toContain('Community agent search is not yet supported');
- expect(result.state).toEqual({ agents: [], source: 'community', total: 0 });
- });
-
- it('should search user agents and return formatted results', async () => {
- mockQueryAgents.mockResolvedValue([
- { id: 'agent-1', title: 'Code Assistant', description: 'Helps with coding', avatar: '🤖' },
- { id: 'agent-2', title: 'Writer', description: null, avatar: null },
- ]);
-
- const ctx = createMockContext();
- const result = await groupManagementExecutor.searchAgent({ query: 'test' }, ctx);
-
- expect(result.success).toBe(true);
- expect(mockQueryAgents).toHaveBeenCalledWith({ keyword: 'test', limit: 10 });
- expect(result.content).toContain('Found 2 agents');
- expect(result.content).toContain('Code Assistant');
- expect(result.content).toContain('Writer');
- expect(result.state.agents).toHaveLength(2);
- expect(result.state.total).toBe(2);
- });
-
- it('should return no results message when no agents found', async () => {
- mockQueryAgents.mockResolvedValue([]);
-
- const ctx = createMockContext();
- const result = await groupManagementExecutor.searchAgent({ query: 'nonexistent' }, ctx);
-
- expect(result.success).toBe(true);
- expect(result.content).toContain('No agents found matching "nonexistent"');
- expect(result.state).toEqual({ agents: [], query: 'nonexistent', total: 0 });
- });
-
- it('should pass limit to queryAgents', async () => {
- mockQueryAgents.mockResolvedValue([
- { id: 'agent-1', title: 'Agent 1' },
- { id: 'agent-2', title: 'Agent 2' },
- ]);
-
- const ctx = createMockContext();
- const result = await groupManagementExecutor.searchAgent({ query: 'test', limit: 2 }, ctx);
-
- expect(result.success).toBe(true);
- expect(mockQueryAgents).toHaveBeenCalledWith({ keyword: 'test', limit: 2 });
- expect(result.state.agents).toHaveLength(2);
- });
-
- it('should handle errors gracefully', async () => {
- mockQueryAgents.mockRejectedValue(new Error('Network error'));
-
- const ctx = createMockContext();
- const result = await groupManagementExecutor.searchAgent({ query: 'test' }, ctx);
-
- expect(result.success).toBe(false);
- expect(result.content).toBe('Failed to search agents: Network error');
- });
- });
-
describe('getAgentInfo', () => {
it('should return error when no groupId in context', async () => {
const ctx = createMockContext();
@@ -372,221 +283,7 @@ describe('GroupManagementExecutor', () => {
});
});
- describe('inviteAgent', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it('should return error when no groupId in context', async () => {
- const ctx = createMockContext();
-
- const result = await groupManagementExecutor.inviteAgent({ agentId: 'agent-1' }, ctx);
-
- expect(result.success).toBe(false);
- expect(result.content).toBe('No group context available');
- });
-
- it('should successfully invite agent when groupId is available', async () => {
- mockAddAgentsToGroup.mockResolvedValue(undefined);
-
- const ctx: BuiltinToolContext = {
- ...createMockContext(),
- groupId: 'test-group-id',
- };
-
- const result = await groupManagementExecutor.inviteAgent({ agentId: 'agent-1' }, ctx);
-
- expect(result.success).toBe(true);
- expect(mockAddAgentsToGroup).toHaveBeenCalledWith('test-group-id', ['agent-1']);
- expect(result.content).toBe('Agent "agent-1" has been invited to the group.');
- expect(result.state).toEqual({ agentId: 'agent-1', type: 'inviteAgent' });
- });
-
- it('should handle errors during invitation', async () => {
- mockAddAgentsToGroup.mockRejectedValue(new Error('Database error'));
-
- const ctx: BuiltinToolContext = {
- ...createMockContext(),
- groupId: 'test-group-id',
- };
-
- const result = await groupManagementExecutor.inviteAgent({ agentId: 'agent-1' }, ctx);
-
- expect(result.success).toBe(false);
- expect(result.content).toBe('Failed to invite agent "agent-1": Database error');
- });
- });
-
- describe('removeAgent', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it('should return error when no groupId in context', async () => {
- const ctx = createMockContext();
-
- const result = await groupManagementExecutor.removeAgent({ agentId: 'agent-1' }, ctx);
-
- expect(result.success).toBe(false);
- expect(result.content).toBe('No group context available');
- });
-
- it('should successfully remove agent when groupId is available', async () => {
- mockRemoveAgentFromGroup.mockResolvedValue(undefined);
-
- const ctx: BuiltinToolContext = {
- ...createMockContext(),
- groupId: 'test-group-id',
- };
-
- const result = await groupManagementExecutor.removeAgent({ agentId: 'agent-1' }, ctx);
-
- expect(result.success).toBe(true);
- expect(mockRemoveAgentFromGroup).toHaveBeenCalledWith('test-group-id', 'agent-1');
- expect(result.content).toBe('Agent "agent-1" has been removed from the group.');
- expect(result.state).toEqual({ agentId: 'agent-1', type: 'removeAgent' });
- });
-
- it('should handle errors during removal', async () => {
- mockRemoveAgentFromGroup.mockRejectedValue(new Error('Agent not found'));
-
- const ctx: BuiltinToolContext = {
- ...createMockContext(),
- groupId: 'test-group-id',
- };
-
- const result = await groupManagementExecutor.removeAgent({ agentId: 'agent-1' }, ctx);
-
- expect(result.success).toBe(false);
- expect(result.content).toBe('Failed to remove agent "agent-1": Agent not found');
- });
- });
-
- describe('createAgent', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it('should return error when no groupId in context', async () => {
- const ctx = createMockContext();
-
- const result = await groupManagementExecutor.createAgent(
- { title: 'New Agent', systemRole: 'You are a helpful assistant' },
- ctx,
- );
-
- expect(result.success).toBe(false);
- expect(result.content).toBe('No group context available');
- });
-
- it('should successfully create a virtual agent and add to group', async () => {
- mockCreateAgent.mockResolvedValue({
- agentId: 'new-agent-id',
- sessionId: 'new-session-id',
- });
-
- const ctx: BuiltinToolContext = {
- ...createMockContext(),
- groupId: 'test-group-id',
- };
-
- const result = await groupManagementExecutor.createAgent(
- {
- avatar: '🤖',
- description: 'A helpful coding assistant',
- systemRole: 'You are a coding expert',
- title: 'Code Helper',
- },
- ctx,
- );
-
- expect(result.success).toBe(true);
- expect(mockCreateAgent).toHaveBeenCalledWith({
- config: {
- avatar: '🤖',
- description: 'A helpful coding assistant',
- systemRole: 'You are a coding expert',
- title: 'Code Helper',
- virtual: true,
- },
- groupId: 'test-group-id',
- });
- expect(result.content).toBe('Agent "Code Helper" has been created and added to the group.');
- expect(result.state).toEqual({
- agentId: 'new-agent-id',
- title: 'Code Helper',
- type: 'createAgent',
- });
- });
-
- it('should handle case when agentId is not returned', async () => {
- mockCreateAgent.mockResolvedValue({
- sessionId: 'new-session-id',
- // No agentId returned
- });
-
- const ctx: BuiltinToolContext = {
- ...createMockContext(),
- groupId: 'test-group-id',
- };
-
- const result = await groupManagementExecutor.createAgent(
- { title: 'New Agent', systemRole: 'Test' },
- ctx,
- );
-
- expect(result.success).toBe(false);
- expect(result.content).toBe('Failed to create agent: No agent ID returned');
- });
-
- it('should handle errors during creation', async () => {
- mockCreateAgent.mockRejectedValue(new Error('Database connection failed'));
-
- const ctx: BuiltinToolContext = {
- ...createMockContext(),
- groupId: 'test-group-id',
- };
-
- const result = await groupManagementExecutor.createAgent(
- { title: 'New Agent', systemRole: 'Test' },
- ctx,
- );
-
- expect(result.success).toBe(false);
- expect(result.content).toBe('Failed to create agent: Database connection failed');
- });
-
- it('should create agent with minimal params (only required fields)', async () => {
- mockCreateAgent.mockResolvedValue({
- agentId: 'minimal-agent-id',
- sessionId: 'minimal-session-id',
- });
-
- const ctx: BuiltinToolContext = {
- ...createMockContext(),
- groupId: 'test-group-id',
- };
-
- const result = await groupManagementExecutor.createAgent(
- { title: 'Minimal Agent', systemRole: 'Basic assistant' },
- ctx,
- );
-
- expect(result.success).toBe(true);
- expect(mockCreateAgent).toHaveBeenCalledWith({
- config: {
- avatar: undefined,
- description: undefined,
- systemRole: 'Basic assistant',
- title: 'Minimal Agent',
- virtual: true,
- },
- groupId: 'test-group-id',
- });
- });
- });
-
- describe('executeTask', () => {
+ describe('executeAgentTask', () => {
beforeEach(() => {
vi.clearAllMocks();
});
@@ -594,7 +291,7 @@ describe('GroupManagementExecutor', () => {
it('should return stop=true to terminate supervisor execution', async () => {
const ctx = createMockContext();
- const result = await groupManagementExecutor.executeTask(
+ const result = await groupManagementExecutor.executeAgentTask(
{ agentId: 'agent-1', task: 'Do something' },
ctx,
);
@@ -606,7 +303,7 @@ describe('GroupManagementExecutor', () => {
agentId: 'agent-1',
task: 'Do something',
timeout: undefined,
- type: 'executeTask',
+ type: 'executeAgentTask',
});
});
@@ -628,7 +325,7 @@ describe('GroupManagementExecutor', () => {
registerAfterCompletion,
);
- await groupManagementExecutor.executeTask(
+ await groupManagementExecutor.executeAgentTask(
{ agentId: 'agent-1', task: 'Do something', timeout: 30000 },
ctx,
);
@@ -653,7 +350,7 @@ describe('GroupManagementExecutor', () => {
it('should not fail when groupOrchestration is not available', async () => {
const ctx = createMockContext();
- const result = await groupManagementExecutor.executeTask(
+ const result = await groupManagementExecutor.executeAgentTask(
{ agentId: 'agent-1', task: 'Do something' },
ctx,
);
@@ -665,7 +362,7 @@ describe('GroupManagementExecutor', () => {
it('should include timeout in state when provided', async () => {
const ctx = createMockContext();
- const result = await groupManagementExecutor.executeTask(
+ const result = await groupManagementExecutor.executeAgentTask(
{ agentId: 'agent-1', task: 'Do something', timeout: 60000 },
ctx,
);
@@ -675,7 +372,7 @@ describe('GroupManagementExecutor', () => {
agentId: 'agent-1',
task: 'Do something',
timeout: 60000,
- type: 'executeTask',
+ type: 'executeAgentTask',
});
});
});
diff --git a/packages/builtin-tool-group-management/src/executor.ts b/packages/builtin-tool-group-management/src/executor.ts
index a9f5e4ee0fe..a8ab98b39f6 100644
--- a/packages/builtin-tool-group-management/src/executor.ts
+++ b/packages/builtin-tool-group-management/src/executor.ts
@@ -3,10 +3,11 @@
* Lobe Group Management Executor
*
* Handles all group management tool calls for multi-agent orchestration.
+ * Note: Member management (searchAgent, inviteAgent, createAgent, removeAgent)
+ * is handled by group-agent-builder. This executor focuses on orchestration.
*/
import {
BroadcastParams,
- CreateAgentParams,
CreateWorkflowParams,
DelegateParams,
ExecuteTaskParams,
@@ -14,9 +15,6 @@ import {
GroupManagementApiName,
GroupManagementIdentifier,
InterruptParams,
- InviteAgentParams,
- RemoveAgentParams,
- SearchAgentParams,
SpeakParams,
SummarizeParams,
VoteParams,
@@ -24,166 +22,13 @@ import {
import { formatAgentProfile } from '@lobechat/prompts';
import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';
-import { agentService } from '@/services/agent';
import { agentGroupSelectors, useAgentGroupStore } from '@/store/agentGroup';
class GroupManagementExecutor extends BaseExecutor<typeof GroupManagementApiName> {
readonly identifier = GroupManagementIdentifier;
protected readonly apiEnum = GroupManagementApiName;
- // ==================== Member Management ====================
-
- searchAgent = async (
- params: SearchAgentParams,
- _ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- const { query, limit = 10, source = 'user' } = params;
-
- // Currently only support searching user's own agents
- // Community search can be added in the future
- if (source === 'community') {
- return {
- content:
- 'Community agent search is not yet supported. Please use source="user" to search your own agents.',
- state: { agents: [], source, total: 0 },
- success: true,
- };
- }
-
- try {
- const results = await agentService.queryAgents({ keyword: query, limit });
-
- const agents = results.map((agent) => ({
- avatar: agent.avatar,
- description: agent.description,
- id: agent.id,
- title: agent.title,
- }));
-
- const total = agents.length;
-
- if (total === 0) {
- return {
- content: query
- ? `No agents found matching "${query}".`
- : 'No agents found. You can create a new agent or search with different keywords.',
- state: { agents: [], query, total: 0 },
- success: true,
- };
- }
-
- // Format agents list for LLM consumption
- const agentList = agents
- .map(
- (a, i) =>
- `${i + 1}. ${a.title || 'Untitled'} (ID: ${a.id})${a.description ? ` - ${a.description}` : ''}`,
- )
- .join('\n');
-
- return {
- content: `Found ${total} agent${total > 1 ? 's' : ''} matching "${query}":\n${agentList}`,
- state: { agents, query, total },
- success: true,
- };
- } catch (error) {
- return {
- content: `Failed to search agents: ${error instanceof Error ? error.message : 'Unknown error'}`,
- success: false,
- };
- }
- };
-
- inviteAgent = async (
- params: InviteAgentParams,
- ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- const { groupId } = ctx;
-
- if (!groupId) {
- return { content: 'No group context available', success: false };
- }
-
- try {
- await useAgentGroupStore.getState().addAgentsToGroup(groupId, [params.agentId]);
-
- return {
- content: `Agent "${params.agentId}" has been invited to the group.`,
- state: { agentId: params.agentId, type: 'inviteAgent' },
- success: true,
- };
- } catch (error) {
- return {
- content: `Failed to invite agent "${params.agentId}": ${error instanceof Error ? error.message : 'Unknown error'}`,
- success: false,
- };
- }
- };
-
- createAgent = async (
- params: CreateAgentParams,
- ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- const { groupId } = ctx;
-
- if (!groupId) {
- return { content: 'No group context available', success: false };
- }
-
- try {
- // Create a virtual agent (agents created by supervisor are virtual)
- const result = await agentService.createAgent({
- config: {
- avatar: params.avatar,
- description: params.description,
- systemRole: params.systemRole,
- title: params.title,
- virtual: true,
- },
- groupId,
- });
-
- if (!result.agentId) {
- return { content: 'Failed to create agent: No agent ID returned', success: false };
- }
-
- return {
- content: `Agent "${params.title}" has been created and added to the group.`,
- state: { agentId: result.agentId, title: params.title, type: 'createAgent' },
- success: true,
- };
- } catch (error) {
- return {
- content: `Failed to create agent: ${error instanceof Error ? error.message : 'Unknown error'}`,
- success: false,
- };
- }
- };
-
- removeAgent = async (
- params: RemoveAgentParams,
- ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- const { groupId } = ctx;
-
- if (!groupId) {
- return { content: 'No group context available', success: false };
- }
-
- try {
- await useAgentGroupStore.getState().removeAgentFromGroup(groupId, params.agentId);
-
- return {
- content: `Agent "${params.agentId}" has been removed from the group.`,
- state: { agentId: params.agentId, type: 'removeAgent' },
- success: true,
- };
- } catch (error) {
- return {
- content: `Failed to remove agent "${params.agentId}": ${error instanceof Error ? error.message : 'Unknown error'}`,
- success: false,
- };
- }
- };
+ // ==================== Agent Info ====================
getAgentInfo = async (
params: GetAgentInfoParams,
@@ -306,7 +151,7 @@ class GroupManagementExecutor extends BaseExecutor<typeof GroupManagementApiName
// ==================== Task Execution ====================
- executeTask = async (
+ executeAgentTask = async (
params: ExecuteTaskParams,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
@@ -333,7 +178,7 @@ class GroupManagementExecutor extends BaseExecutor<typeof GroupManagementApiName
skipCallSupervisor: params.skipCallSupervisor,
task: params.task,
timeout: params.timeout,
- type: 'executeTask',
+ type: 'executeAgentTask',
},
stop: true,
success: true,
diff --git a/packages/builtin-tool-group-management/src/manifest.ts b/packages/builtin-tool-group-management/src/manifest.ts
index 7a8886f0853..0a6db844063 100644
--- a/packages/builtin-tool-group-management/src/manifest.ts
+++ b/packages/builtin-tool-group-management/src/manifest.ts
@@ -8,100 +8,10 @@ export const GroupManagementIdentifier = 'lobe-group-management';
export const GroupManagementManifest: BuiltinToolManifest = {
/* eslint-disable sort-keys-fix/sort-keys-fix */
api: [
- // ==================== Member Management ====================
+ // ==================== Agent Info ====================
{
description:
- "Search for agents that can be invited to the group. Returns agents from both the user's collection and the community marketplace. Use this to find suitable agents before inviting them.",
- name: GroupManagementApiName.searchAgent,
- parameters: {
- properties: {
- query: {
- description:
- 'Search query to find agents by name, description, or capabilities. Leave empty to browse all available agents.',
- type: 'string',
- },
- source: {
- description:
- 'Filter by agent source: "user" for user\'s own agents, "community" for marketplace agents, or omit for all sources.',
- enum: ['user', 'community'],
- type: 'string',
- },
- limit: {
- default: 10,
- description: 'Maximum number of results to return (default: 10, max: 20).',
- maximum: 20,
- minimum: 1,
- type: 'number',
- },
- },
- required: [],
- type: 'object',
- },
- },
- {
- description:
- 'Invite an agent to join the current group. The agent must be found via searchAgent first. Once invited, the agent becomes available for orchestration.',
- name: GroupManagementApiName.inviteAgent,
- humanIntervention: 'always',
- parameters: {
- properties: {
- agentId: {
- description: 'The ID of the agent to invite. Get this from searchAgent results.',
- type: 'string',
- },
- },
- required: ['agentId'],
- type: 'object',
- },
- },
- {
- description:
- 'Create a new agent dynamically based on user requirements and add it to the group. Use this when no existing agent matches the needed expertise.',
- humanIntervention: 'required',
- name: GroupManagementApiName.createAgent,
- parameters: {
- properties: {
- title: {
- description: 'The display name for the new agent.',
- type: 'string',
- },
- description: {
- description: 'A brief description of what this agent does and its expertise.',
- type: 'string',
- },
- systemRole: {
- description:
- "The system prompt that defines the agent's behavior, personality, and capabilities.",
- type: 'string',
- },
- avatar: {
- description: "An emoji or image URL for the agent's avatar (optional).",
- type: 'string',
- },
- },
- required: ['title', 'systemRole'],
- type: 'object',
- },
- },
- {
- description:
- 'Remove an agent from the current group. The agent will no longer be available for orchestration but is not deleted from the system.',
- name: GroupManagementApiName.removeAgent,
- humanIntervention: 'always',
- parameters: {
- properties: {
- agentId: {
- description: 'The ID of the agent to remove from the group.',
- type: 'string',
- },
- },
- required: ['agentId'],
- type: 'object',
- },
- },
- {
- description:
- 'Get detailed information about a specific agent, including their capabilities, available tools, and configuration.',
+ 'Get detailed information about a specific agent, including their capabilities, available tools, and configuration. Use this to check if an agent has tools before deciding between speak vs executeAgentTask.',
name: GroupManagementApiName.getAgentInfo,
parameters: {
properties: {
@@ -194,8 +104,8 @@ export const GroupManagementManifest: BuiltinToolManifest = {
{
description:
'Assign an asynchronous task to an agent. The task runs in the background and results are returned to the conversation context upon completion. Ideal for longer operations.',
- name: GroupManagementApiName.executeTask,
- humanIntervention: 'always',
+ name: GroupManagementApiName.executeAgentTask,
+ humanIntervention: 'required',
parameters: {
properties: {
agentId: {
@@ -224,6 +134,52 @@ export const GroupManagementManifest: BuiltinToolManifest = {
type: 'object',
},
},
+ {
+ description:
+ 'Assign multiple tasks to different agents to run in parallel. Each agent works independently in their own context. Use this when you need multiple agents to work on different parts of a problem simultaneously.',
+ name: GroupManagementApiName.executeAgentTasks,
+ humanIntervention: 'required',
+ parameters: {
+ properties: {
+ tasks: {
+ description: 'Array of tasks, each assigned to a specific agent.',
+ items: {
+ properties: {
+ agentId: {
+ description: 'The ID of the agent to execute this task.',
+ type: 'string',
+ },
+ title: {
+ description: 'Brief title describing what this task does (shown in UI).',
+ type: 'string',
+ },
+ instruction: {
+ description:
+ 'Detailed instruction/prompt for the task execution. Be specific about expected deliverables.',
+ type: 'string',
+ },
+ timeout: {
+ description:
+ 'Optional timeout in milliseconds for this task (default: 1800000, 30 minutes).',
+ type: 'number',
+ },
+ },
+ required: ['agentId', 'title', 'instruction'],
+ type: 'object',
+ },
+ type: 'array',
+ },
+ skipCallSupervisor: {
+ default: false,
+ description:
+ 'If true, the orchestration will end after all tasks complete, without calling the supervisor again.',
+ type: 'boolean',
+ },
+ },
+ required: ['tasks'],
+ type: 'object',
+ },
+ },
{
description:
'Interrupt a running agent task. Use this to stop a task that is taking too long or is no longer needed.',
diff --git a/packages/builtin-tool-group-management/src/systemRole.ts b/packages/builtin-tool-group-management/src/systemRole.ts
index 22ccc5f2ca2..1ad6735939d 100644
--- a/packages/builtin-tool-group-management/src/systemRole.ts
+++ b/packages/builtin-tool-group-management/src/systemRole.ts
@@ -4,196 +4,275 @@
* This provides guidance for the Group Supervisor on how to effectively use
* the group management tools to orchestrate multi-agent conversations.
*/
-export const systemPrompt = `You have a Group Management tool with capabilities to orchestrate multi-agent group conversations. You can manage group members, coordinate communication, execute tasks, and control conversation flow.
+export const systemPrompt = `You are a Group Supervisor with tools to orchestrate multi-agent collaboration. Your primary responsibility is to coordinate agents effectively by choosing the right mode of interaction.
+
+<core_decision_framework>
+## The Critical Choice: Speaking vs Task Execution
+
+Before involving any agent, you MUST determine which mode is appropriate:
+
+### 🗣️ Speaking Mode (speak/broadcast)
+**Use when agents DON'T need to use tools** - agents share the group's conversation context.
+
+Characteristics:
+- Agent responds based on their expertise and knowledge
+- Agent sees the group conversation history
+- Response is immediate and synchronous
+- No tool/plugin invocation needed
+- Lightweight, quick interactions
+
+Best for:
+- Sharing opinions, perspectives, or advice
+- Answering questions from knowledge
+- Brainstorming and ideation
+- Reviewing/critiquing content presented in conversation
+- Quick consultations
+- Discussion and debate
+
+### ⚡ Task Execution Mode (executeAgentTask)
+**Use when agents NEED to use tools** - each agent gets an independent context window to complete their task autonomously.
+
+Characteristics:
+- Agent operates in isolated context (fresh conversation)
+- Agent CAN use their configured tools/plugins (web search, code execution, file operations, etc.)
+- Asynchronous execution - multiple agents can work in parallel
+- Each agent completes their task independently
+- Results are returned to the group when done
+
+Best for:
+- Web research and information gathering
+- Code writing, analysis, or execution
+- File processing or generation
+- API calls or external service interactions
+- Complex multi-step tasks requiring tool usage
+- Any task where the agent needs to "do something" not just "say something"
+
+## Decision Flowchart
+
+\`\`\`
+User Request
+ │
+ ▼
+Does the task require agents to USE TOOLS?
+(search web, write code, call APIs, process files, etc.)
+ │
+ ├─── YES ──→ executeAgentTask (independent context per agent)
+ │
+ └─── NO ───→ Does the task need multiple perspectives?
+ │
+ ├─── YES ──→ broadcast (parallel speaking)
+ │
+ └─── NO ───→ speak (single agent)
+\`\`\`
+</core_decision_framework>
<user_intent_analysis>
-Before responding, analyze the user's intent to determine if agent participation is appropriate:
-
-**Signals for Group Discussion (PROACTIVELY invoke agents):**
-- Open-ended questions: "What do you think about...", "Any ideas for...", "How should we..."
-- Requests for multiple perspectives: "I want to hear different opinions", "Let's discuss..."
-- Creative/brainstorming tasks: "Let's brainstorm...", "Help me come up with..."
-- Complex problems that benefit from diverse expertise
-- Implicit collaboration cues: questions in a multi-agent group context generally expect group participation
-- Ambiguous questions where multiple agents have relevant expertise
-
-**Signals for Single Agent or No Agent (be selective):**
-- Explicit single agent request: "Ask [Agent Name] to...", "Let [Agent Name] answer..."
-- Simple factual questions you can answer directly
-- Follow-up questions to a specific agent's previous response
-- Administrative requests (add/remove agents, etc.)
+Before responding, analyze the user's intent:
+
+**Signals for Task Execution (executeAgentTask):**
+- "Search for...", "Find information about...", "Research..."
+- "Write code to...", "Create a script that...", "Implement..."
+- "Analyze this file...", "Process this data..."
+- "Generate a report...", "Create documentation..."
+- Tasks that clearly require external tools or multi-step operations
+- When multiple agents need to work on different parts independently
+
+**Signals for Speaking (speak/broadcast):**
+- "What do you think about...", "Any ideas for...", "How should we..."
+- "Review this...", "Give me feedback on...", "Critique..."
+- "Explain...", "Compare...", "Summarize..."
+- Requests for opinions, perspectives, or expertise-based answers
+- Questions that can be answered from knowledge alone
+
+**Signals for Single Agent (speak):**
+- Explicit request: "Ask [Agent Name] to...", "Let [Agent Name] answer..."
+- Follow-up to a specific agent's previous response
+- Task clearly matches only one agent's expertise
**Default Behavior:**
-- When in doubt in a group context, LEAN TOWARDS invoking relevant agents
-- Users created a group specifically for collaborative discussions - respect that intent
-- A brief group response is better than no response when the topic is relevant to group members
+- When in doubt about tool usage → Ask yourself: "Can this be answered with knowledge alone, or does it require the agent to DO something?"
+- When in doubt about single vs multiple agents → Lean towards broadcast for diverse perspectives
</user_intent_analysis>
-<core_capabilities>
-You have access to a set of tools to manage and orchestrate the agent group:
+<intent_clarification>
+## Clarify Before Dispatching
-**Member Management:**
-1. **searchAgent**: Search for agents that can be invited to the group. Returns agents from user's collection and community marketplace.
-2. **inviteAgent**: Invite an agent to join the current group. The agent must be found via searchAgent first.
-3. **createAgent**: Dynamically create a new agent based on requirements and add it to the group.
-4. **removeAgent**: Remove an agent from the current group. The agent is not deleted, just removed from this group.
-5. **getAgentInfo**: Get detailed information about an agent, including capabilities, tools, and configuration.
+**IMPORTANT: Before assigning tasks to agents, briefly clarify the user's core needs when the request is ambiguous.**
-**Communication Coordination:**
-6. **speak**: Let a specific agent respond. Synchronous and waits for the agent's response.
-7. **broadcast**: Let multiple agents respond simultaneously in parallel.
+When a user's request is broad or unclear, ask 1-2 focused questions to understand their intent before dispatching agents. This prevents wasted agent effort on misaligned work.
-**Task Execution:**
-8. **executeTask**: Assign an asynchronous task to an agent. Results return to context upon completion.
-9. **interrupt**: Stop a running agent task by its task ID.
+**Clarification Rules:**
+- **Maximum 2 rounds** of questions - don't interrogate the user
+- **Ask only when necessary** - if the request is clear enough, proceed directly
+- **Batch related questions** - ask multiple questions in one message
+- **Focus on task-critical info** - what significantly impacts agent assignments
+
+**When to clarify:**
+- User's goal is vague ("help me with this project")
+- Scope is unclear (could be quick opinion vs deep research)
+- Multiple valid interpretations exist
+- Agent selection depends on unknown preferences
+
+**When to skip clarification:**
+- Request is specific enough to act on
+- User has provided clear deliverables
+- Follow-up to an ongoing discussion
+- Simple questions or consultations
+
+**What to clarify:**
+- Core objective (what does success look like?)
+- Scope preference (quick feedback vs thorough research?)
+- Priority constraints (time, quality, coverage?)
+- Specific agents or expertise needed
+
+**Examples:**
+
+✅ Good clarification:
+> User: "Help me improve my app's performance"
+> Supervisor: "To get you the best help, I'd like to know:
+> 1. Is this about frontend (UI/load time) or backend (API/database) performance?
+> 2. Do you want a quick review with suggestions, or thorough profiling and analysis?"
+
+❌ Skip clarification (already specific):
+> User: "Have the frontend expert review my React component for performance issues"
+> Supervisor: [Proceed directly - clear agent and task]
-**Context Management:**
-10. **summarize**: Summarize and compress the current conversation context.
+❌ Too many questions:
+> User: "Help me with my website"
+> Supervisor: "Sure! What framework? What's the budget? Timeline? Target audience? Current traffic? Hosting provider? Team size?..."
+
+**After clarification:**
+1. Acknowledge their input briefly
+2. Explain your orchestration approach
+3. Dispatch appropriate agents with clear instructions
+</intent_clarification>
+
+<core_capabilities>
+## Tool Categories
+
+**Agent Info:**
+- **getAgentInfo**: Get agent details including their tools and capabilities - **Use this to check if an agent has tools before deciding speak vs executeAgentTask**
+
+**Speaking (Shared Context, No Tools):**
+- **speak**: Single agent responds synchronously in group context
+- **broadcast**: Multiple agents respond in parallel in group context
+
+**Task Execution (Independent Context, With Tools):**
+- **executeAgentTask**: Assign a single task to one agent in isolated context
+- **executeAgentTasks**: Assign multiple tasks to different agents in parallel (each with isolated context)
+- **interrupt**: Stop a running task
**Flow Control:**
-11. **vote**: Initiate a vote among agents on a specific question or decision.
+- **summarize**: Compress conversation context
+- **vote**: Initiate voting among agents
</core_capabilities>
-<workflow_analysis>
-Before orchestrating agent responses, analyze the task to determine the optimal execution pattern:
-
-## Task Pattern Recognition
-
-**Parallel Pattern (use \`broadcast\`)** - When order doesn't matter and diverse perspectives are valuable:
-- **Brainstorming**: Generate ideas from multiple angles simultaneously
- - Example: "Let's brainstorm marketing strategies" → broadcast to Marketing, Product, Design agents
-- **Independent Review**: Multiple experts review the same artifact
- - Example: "Review this code" → broadcast to Security, Performance, Architecture agents
-- **Gathering Opinions**: Collect viewpoints without sequential influence
- - Example: "What do you think about this proposal?" → broadcast to all relevant agents
-- **Parallel Analysis**: Analyze different aspects of a problem simultaneously
- - Example: "Analyze this business plan" → broadcast to Finance, Legal, Operations agents
-
-**Sequential Pattern (use \`speak\`)** - When there's logical dependency or build-upon relationship:
-- **Expert Chain**: Each expert builds on previous expert's output
- - Example: AI Expert proposes algorithm → Product Manager analyzes feasibility → Designer creates UX → Engineer estimates effort
-- **Refinement Flow**: Iteratively improve a solution
- - Example: Writer drafts → Editor refines → Proofreader finalizes
-- **Validation Pipeline**: Each step validates/extends previous
- - Example: Architect designs → Security reviews → DevOps validates deployment
-- **Decision Funnel**: Progressively narrow down options
- - Example: Researcher provides options → Analyst evaluates → Decision-maker selects
-
-**Hybrid Pattern** - Complex tasks may need both:
-1. First \`broadcast\` to gather diverse inputs
-2. Then sequential \`speak\` to synthesize and refine
-3. Finally \`vote\` if consensus is needed
-
-## Decision Framework
-
-Ask yourself:
-1. **Does output from Agent A inform Agent B's response?** → Sequential (speak)
-2. **Are agents analyzing the same thing independently?** → Parallel (broadcast)
-3. **Is there a natural workflow order (design→implement→test)?** → Sequential
-4. **Do we need diverse perspectives without cross-influence?** → Parallel
-5. **Is the task creative/generative with no single right answer?** → Parallel
-6. **Does quality depend on building upon previous work?** → Sequential
-</workflow_analysis>
-
-<workflow_examples>
-## Example 1: Product Feature Discussion (Hybrid)
-User: "We need to design a new notification system"
-
-Analysis: Creative task requiring multiple perspectives, then synthesis.
-Workflow:
-1. \`broadcast\` to [Product, Design, Engineering]: "Share your initial thoughts on requirements and constraints"
-2. \`speak\` to Design: "Based on the inputs, propose a UX approach"
-3. \`speak\` to Engineering: "Evaluate the technical feasibility of the design proposal"
-4. \`speak\` to Product: "Synthesize the discussion into a final recommendation"
-
-## Example 2: Code Review (Parallel)
-User: "Review this authentication implementation"
-
-Analysis: Independent expert reviews, order doesn't matter.
-Workflow:
-\`broadcast\` to [Security, Architecture, Performance]: "Review this code from your expertise perspective"
-
-## Example 3: Technical Solution Design (Sequential)
-User: "Design a recommendation algorithm for our e-commerce platform"
-
-Analysis: Clear dependency chain - algorithm design → product fit → implementation plan.
-Workflow:
-1. \`speak\` to AI Expert: "Propose recommendation algorithm approaches"
-2. \`speak\` to Product Manager: "Analyze which approach best fits our user needs and business goals"
-3. \`speak\` to Data Engineer: "Design the data pipeline for the selected approach"
-4. \`speak\` to Backend Engineer: "Outline the implementation architecture"
-
-## Example 4: Research Task (Parallel then Sequential)
-User: "Research best practices for microservices migration"
-
-Analysis: Gather independent research, then synthesize.
-Workflow:
-1. \`broadcast\` to [Architect, DevOps, Security]: "Research best practices from your domain"
-2. \`speak\` to Architect: "Synthesize findings into a unified migration strategy"
-
-## Example 5: Decision Making (Sequential then Vote)
-User: "Should we use PostgreSQL or MongoDB for this project?"
-
-Analysis: Need informed opinions, then democratic decision.
-Workflow:
-1. \`speak\` to Database Expert: "Compare PostgreSQL vs MongoDB for our use case"
-2. \`speak\` to Backend Engineer: "Add implementation perspective"
-3. \`vote\` with question: "Which database should we use?" options: [PostgreSQL, MongoDB]
-</workflow_examples>
+<workflow_patterns>
+## Pattern Selection Guide
+
+### Pattern 1: Discussion/Consultation (Speaking)
+When you need opinions, feedback, or knowledge-based responses.
+
+\`\`\`
+User: "What do you think about using microservices for this project?"
+Analysis: Opinion-based, no tools needed
+Action: broadcast to [Architect, DevOps, Backend] - share perspectives
+\`\`\`
+
+### Pattern 2: Independent Research (Parallel Tasks)
+When multiple agents need to research/work independently using their tools.
+
+\`\`\`
+User: "Research the pros and cons of React vs Vue vs Svelte"
+Analysis: Requires web search, agents work independently
+Action: executeAgentTasks with parallel assignments
+executeAgentTasks({
+ tasks: [
+ { agentId: "frontend-expert", title: "Research React", instruction: "Research React ecosystem, performance benchmarks, community size, and typical use cases. Provide pros and cons." },
+ { agentId: "ui-specialist", title: "Research Vue", instruction: "Research Vue ecosystem, performance benchmarks, community size, and typical use cases. Provide pros and cons." },
+ { agentId: "tech-analyst", title: "Research Svelte", instruction: "Research Svelte ecosystem, performance benchmarks, community size, and typical use cases. Provide pros and cons." }
+ ]
+})
+\`\`\`
+
+### Pattern 3: Sequential Discussion (Speaking Chain)
+When each response should build on previous ones.
+
+\`\`\`
+User: "Design a notification system architecture"
+Analysis: Build-upon discussion, no tools needed per step
+Action:
+1. speak to Architect: "Propose high-level architecture"
+2. speak to Backend: "Evaluate and add implementation details"
+3. speak to DevOps: "Add deployment and scaling considerations"
+\`\`\`
+
+### Pattern 4: Research then Discuss (Hybrid)
+When you need facts first, then discussion.
+
+\`\`\`
+User: "Should we migrate to Kubernetes? Research and discuss."
+Analysis: First gather facts (tools), then discuss (no tools)
+Action:
+1. executeAgentTasks({
+ tasks: [
+ { agentId: "devops", title: "K8s Adoption Research", instruction: "Research Kubernetes adoption best practices for our scale. Include migration complexity, resource requirements, and operational overhead." },
+ { agentId: "security", title: "K8s Security Analysis", instruction: "Research Kubernetes security considerations including network policies, RBAC, secrets management, and common vulnerabilities." }
+ ]
+ })
+2. [Wait for results]
+3. broadcast: "Based on the research, share your recommendations"
+\`\`\`
+
+### Pattern 5: Collaborative Implementation (Parallel Tasks)
+When multiple agents create deliverables using their tools.
+
+\`\`\`
+User: "Create a landing page - need copy, design specs, and code"
+Analysis: Each agent produces artifacts using their tools
+Action: executeAgentTasks({
+ tasks: [
+ { agentId: "copywriter", title: "Write Copy", instruction: "Write compelling landing page copy for [product]. Include headline, subheadline, feature descriptions, and CTA text." },
+ { agentId: "designer", title: "Design Specs", instruction: "Create design specifications including color palette, typography, layout grid, and component list with visual hierarchy." },
+ { agentId: "frontend-dev", title: "Implement Page", instruction: "Implement the landing page using React. Include responsive design, animations, and SEO-friendly markup." }
+ ]
+})
+\`\`\`
+</workflow_patterns>
<tool_usage_guidelines>
-- For finding agents to invite: Use 'searchAgent'. Provide:
- - 'query' (Optional): Search keywords to find agents by name, description, or capabilities.
- - 'source' (Optional): Filter by "user" (user's agents) or "community" (marketplace).
- - 'limit' (Optional): Maximum results to return (default: 10, max: 20).
-- For inviting agents: Use 'inviteAgent'. Provide:
- - 'agentId': The ID of the agent from searchAgent results.
-- For creating new agents: Use 'createAgent'. Provide:
- - 'title': Display name for the new agent.
- - 'systemRole': The system prompt defining the agent's behavior and capabilities.
- - 'description' (Optional): Brief description of what the agent does.
- - 'avatar' (Optional): Emoji or image URL for the agent's avatar.
-- For removing agents: Use 'removeAgent'. Provide:
- - 'agentId': The ID of the agent to remove.
-- For agent details: Use 'getAgentInfo'. Provide:
- - 'agentId': The ID of the agent to get information about.
-- For single agent response: Use 'speak'. Provide:
- - 'agentId': The ID of the agent who should respond.
- - 'instruction' (Optional): Guidance for the agent's response.
-- For parallel responses: Use 'broadcast'. Provide:
- - 'agentIds': Array of agent IDs who should respond.
- - 'instruction' (Optional): Shared instruction for all agents.
-- For async tasks: Use 'executeTask'. Provide:
- - 'agentId': The ID of the agent to execute the task.
- - 'task': Clear description of the task with expected deliverables.
- - 'timeout' (Optional): Maximum time in milliseconds (default: 60000).
-- For stopping tasks: Use 'interrupt'. Provide:
- - 'taskId': The ID of the task to interrupt (from executeTask).
-- For context compression: Use 'summarize'. Provide:
- - 'focus' (Optional): Focus area like "decisions made", "action items", "key points".
- - 'preserveRecent' (Optional): Number of recent messages to keep in full (default: 5).
-- For voting: Use 'vote'. Provide:
- - 'question': The question or decision to vote on.
- - 'options': Array of option objects with 'id', 'label', and optional 'description'.
- - 'voterAgentIds' (Optional): Specific agents to vote. If omitted, all members vote.
- - 'requireReasoning' (Optional): Whether agents must explain their vote (default: true).
+**Agent Info:**
+- getAgentInfo: \`agentId\` - **Use this to check if an agent has tools before deciding speak vs executeAgentTask**
+
+**Speaking:**
+- speak: \`agentId\`, \`instruction\` (optional guidance)
+- broadcast: \`agentIds\` (array), \`instruction\` (optional shared guidance)
+
+**Task Execution:**
+- executeAgentTask: \`agentId\`, \`task\` (clear deliverable description), \`timeout\` (optional, default 30min)
+- executeAgentTasks: \`tasks\` (array of {agentId, title, instruction, timeout?}) - **Use this for parallel task execution across multiple agents**
+- interrupt: \`taskId\`
+
+**Flow Control:**
+- summarize: \`focus\` (optional), \`preserveRecent\` (messages to keep, default 5)
+- vote: \`question\`, \`options\` (array of {id, label, description}), \`voterAgentIds\` (optional), \`requireReasoning\` (default true)
</tool_usage_guidelines>
-<orchestration_best_practices>
-- **Analyze before acting**: Always determine the task pattern (parallel/sequential/hybrid) before calling tools.
-- **Match expertise to queries**: Use getAgentInfo to understand agent capabilities before selecting.
-- **Respect dependencies**: If Agent B needs Agent A's output, always use sequential speak, never broadcast.
-- **Preserve independence**: For brainstorming and opinion gathering, use broadcast to avoid anchoring bias.
-- **Consolidate requests**: Combine related queries rather than multiple separate calls.
-- **Proactive summarization**: Use summarize before context grows too large.
-- **Balanced participation**: Ensure no single agent dominates unless the task requires it.
-- **Explain your orchestration**: Briefly tell the user why you chose a particular pattern.
-</orchestration_best_practices>
+<best_practices>
+1. **Check agent capabilities first**: Use getAgentInfo to see if agent has tools before choosing mode
+2. **Don't over-engineer**: Simple questions → speak; Complex tasks requiring tools → executeAgentTask
+3. **Parallel when possible**: Use broadcast for opinions, parallel executeAgentTask for independent work
+4. **Sequential when dependent**: Use speak chain when each response builds on previous
+5. **Be explicit with task instructions**: For executeAgentTask, clearly describe expected deliverables
+6. **Monitor long tasks**: Use interrupt if tasks run too long or go off-track
+7. **Summarize proactively**: Compress context before it grows too large
+8. **Explain your choices**: Tell users why you chose speaking vs task execution
+</best_practices>
<response_format>
-- When starting orchestration, briefly explain your analysis: "This is a [parallel/sequential/hybrid] task because..."
-- When referencing agents in responses, use clear identification: "Agent [Name] (ID: [agentId])".
-- When reporting task status, include the taskId for reference.
-- When presenting vote results, show each agent's choice and reasoning.
-- After all agents respond, synthesize the key points and actionable conclusions.
+When orchestrating:
+1. Briefly explain your mode choice: "This requires [speaking/task execution] because..."
+2. For tasks, clearly state what each agent will do
+3. After completion, synthesize results and provide actionable conclusions
+4. Reference agents clearly: "Agent [Name] suggests..." or "Task [taskId] completed with..."
</response_format>`;
diff --git a/packages/builtin-tool-group-management/src/types.ts b/packages/builtin-tool-group-management/src/types.ts
index bd41573e890..565526d6d6d 100644
--- a/packages/builtin-tool-group-management/src/types.ts
+++ b/packages/builtin-tool-group-management/src/types.ts
@@ -2,17 +2,12 @@
/**
* API names for Group Management tool
+ *
+ * Note: Member management APIs (searchAgent, inviteAgent, createAgent, removeAgent)
+ * are handled by group-agent-builder tool. This tool focuses on orchestration.
*/
export const GroupManagementApiName = {
- // ==================== Member Management ====================
- /** Search for agents that can be invited to the group */
- searchAgent: 'searchAgent',
- /** Invite an agent to join the group */
- inviteAgent: 'inviteAgent',
- /** Create a new agent and add it to the group */
- createAgent: 'createAgent',
- /** Remove an agent from the group */
- removeAgent: 'removeAgent',
+ // ==================== Agent Info ====================
/** Get detailed information about an agent */
getAgentInfo: 'getAgentInfo',
@@ -26,7 +21,9 @@ export const GroupManagementApiName = {
// ==================== Task Execution ====================
/** Let an agent execute a task asynchronously */
- executeTask: 'executeTask',
+ executeAgentTask: 'executeAgentTask',
+ /** Let multiple agents execute different tasks in parallel */
+ executeAgentTasks: 'executeAgentTasks',
/** Interrupt a running agent task */
interrupt: 'interrupt',
@@ -44,28 +41,7 @@ export const GroupManagementApiName = {
export type GroupManagementApiNameType =
(typeof GroupManagementApiName)[keyof typeof GroupManagementApiName];
-// ==================== Member Management Params ====================
-
-export interface SearchAgentParams {
- limit?: number;
- query?: string;
- source?: 'user' | 'community';
-}
-
-export interface InviteAgentParams {
- agentId: string;
-}
-
-export interface CreateAgentParams {
- avatar?: string;
- description?: string;
- systemRole: string;
- title: string;
-}
-
-export interface RemoveAgentParams {
- agentId: string;
-}
+// ==================== Agent Info Params ====================
export interface GetAgentInfoParams {
agentId: string;
@@ -116,6 +92,27 @@ export interface ExecuteTaskParams {
timeout?: number;
}
+export interface TaskItem {
+ /** The ID of the agent to execute this task */
+ agentId: string;
+ /** Detailed instruction/prompt for the task execution */
+ instruction: string;
+ /** Optional timeout in milliseconds for this specific task */
+ timeout?: number;
+ /** Brief title describing what this task does (shown in UI) */
+ title: string;
+}
+
+export interface ExecuteTasksParams {
+ /**
+ * If true, the orchestration will end after all tasks complete,
+ * without calling the supervisor again.
+ */
+ skipCallSupervisor?: boolean;
+ /** Array of tasks to execute, each assigned to a specific agent */
+ tasks: TaskItem[];
+}
+
export interface InterruptParams {
taskId: string;
}
@@ -156,14 +153,6 @@ export interface VoteParams {
// ==================== Result Types ====================
-export interface AgentSearchResult {
- avatar?: string;
- description?: string;
- id: string;
- source: 'user' | 'community';
- title: string;
-}
-
export interface VoteResult {
agentId: string;
reasoning?: string;
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index 28dddd60d77..05139c9a67f 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -7,7 +7,7 @@ import { ContextEngine } from '../../pipeline';
import {
AgentCouncilFlattenProcessor,
GroupMessageFlattenProcessor,
- GroupMessageSenderProcessor,
+ GroupRoleTransformProcessor,
HistoryTruncateProcessor,
InputTemplateProcessor,
MessageCleanupProcessor,
@@ -274,11 +274,13 @@ export class MessagesEngine {
// 15. Supervisor role restore (convert role=supervisor back to role=assistant for model)
new SupervisorRoleRestoreProcessor(),
- // 16. Group message sender identity injection (for multi-agent chat)
- ...(isAgentGroupEnabled
+ // 16. Group role transform (convert other agents' messages to user role with speaker tags)
+ // This must be BEFORE ToolCallProcessor so other agents' tool messages are converted first
+ ...(isAgentGroupEnabled && agentGroup.currentAgentId
? [
- new GroupMessageSenderProcessor({
+ new GroupRoleTransformProcessor({
agentMap: agentGroup.agentMap!,
+ currentAgentId: agentGroup.currentAgentId,
}),
]
: []),
diff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.ts
index e34dd9c45d3..9fdf2011aac 100644
--- a/packages/context-engine/src/engine/messages/types.ts
+++ b/packages/context-engine/src/engine/messages/types.ts
@@ -4,12 +4,12 @@ import type { RuntimeInitialContext, RuntimeStepContext } from '@lobechat/types'
import type { OpenAIChatMessage, UIChatMessage } from '@/types/index';
-import type { AgentInfo } from '../../processors/GroupMessageSender';
+import type { AgentInfo } from '../../processors/GroupRoleTransform';
import type { AgentBuilderContext } from '../../providers/AgentBuilderContextInjector';
-import type { GroupAgentBuilderContext } from '../../providers/GroupAgentBuilderContextInjector';
-import type { GroupMemberInfo } from '../../providers/GroupContextInjector';
import type { GTDPlan } from '../../providers/GTDPlanInjector';
import type { GTDTodoList } from '../../providers/GTDTodoInjector';
+import type { GroupAgentBuilderContext } from '../../providers/GroupAgentBuilderContextInjector';
+import type { GroupMemberInfo } from '../../providers/GroupContextInjector';
import type { LobeToolManifest } from '../tools/types';
/**
@@ -249,7 +249,7 @@ export interface MessagesEngineResult {
// Re-export types for convenience
-export { type AgentInfo } from '../../processors/GroupMessageSender';
+export { type AgentInfo } from '../../processors/GroupRoleTransform';
export { type AgentBuilderContext } from '../../providers/AgentBuilderContextInjector';
export { type GroupAgentBuilderContext } from '../../providers/GroupAgentBuilderContextInjector';
export { type GTDPlan } from '../../providers/GTDPlanInjector';
diff --git a/packages/context-engine/src/processors/GroupMessageSender.ts b/packages/context-engine/src/processors/GroupMessageSender.ts
deleted file mode 100644
index 7d513856c28..00000000000
--- a/packages/context-engine/src/processors/GroupMessageSender.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-import debug from 'debug';
-
-import { BaseProcessor } from '../base/BaseProcessor';
-import type { Message, PipelineContext, ProcessorOptions } from '../types';
-
-const log = debug('context-engine:processor:GroupMessageSenderProcessor');
-
-/**
- * Agent info for message sender identification
- */
-export interface AgentInfo {
- name: string;
- role: 'supervisor' | 'participant';
-}
-
-/**
- * Configuration for GroupMessageSenderProcessor
- */
-export interface GroupMessageSenderConfig {
- /**
- * Mapping from agentId to agent info
- * Used to look up agent name and role for each message
- */
- agentMap: Record<string, AgentInfo>;
-}
-
-/**
- * Group Message Sender Processor
- *
- * Responsible for injecting sender identity information into assistant messages
- * in group chat scenarios. This helps the model understand which agent sent
- * each message in a multi-agent conversation.
- *
- * The processor appends a system context block at the end of each assistant
- * message that has an agentId, containing:
- * - Agent name
- * - Agent role (supervisor or agent)
- * - Agent ID (with instruction not to expose it in responses)
- *
- * @example
- * ```typescript
- * const processor = new GroupMessageSenderProcessor({
- * agentMap: {
- * 'agt_xxx': { name: 'Weather Expert', role: 'agent' },
- * 'agt_yyy': { name: 'Supervisor', role: 'supervisor' },
- * }
- * });
- * ```
- */
-export class GroupMessageSenderProcessor extends BaseProcessor {
- readonly name = 'GroupMessageSenderProcessor';
-
- constructor(
- private config: GroupMessageSenderConfig,
- options: ProcessorOptions = {},
- ) {
- super(options);
- }
-
- protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
- const clonedContext = this.cloneContext(context);
-
- // Skip if no agentMap provided
- if (!this.config.agentMap || Object.keys(this.config.agentMap).length === 0) {
- log('No agentMap provided, skipping processing');
- return this.markAsExecuted(clonedContext);
- }
-
- let processedCount = 0;
-
- clonedContext.messages = clonedContext.messages.map((msg: Message) => {
- // Only process assistant messages with agentId
- if (msg.role === 'assistant' && msg.agentId) {
- const agentInfo = this.config.agentMap[msg.agentId];
-
- if (agentInfo) {
- // Build the sender tag
- const senderTag = this.buildSenderContext(msg.agentId, agentInfo);
-
- // Prepend to message content (at the beginning)
- if (typeof msg.content === 'string') {
- processedCount++;
- log(
- `Injecting sender info for message from agent: ${agentInfo.name} (${agentInfo.role})`,
- );
-
- return {
- ...msg,
- content: senderTag + msg.content,
- };
- }
- // Handle array content (multimodal messages)
- else if (Array.isArray(msg.content)) {
- const firstTextIndex = msg.content.findIndex((part: any) => part.type === 'text');
-
- if (firstTextIndex !== -1) {
- processedCount++;
- log(
- `Injecting sender info for multimodal message from agent: ${agentInfo.name} (${agentInfo.role})`,
- );
-
- const newContent = [...msg.content];
- newContent[firstTextIndex] = {
- ...newContent[firstTextIndex],
- text: senderTag + newContent[firstTextIndex].text,
- };
-
- return {
- ...msg,
- content: newContent,
- };
- }
- }
- }
- }
-
- return msg;
- });
-
- // Update metadata
- clonedContext.metadata.groupMessageSenderProcessed = processedCount;
-
- log(`Group message sender processing completed: ${processedCount} messages processed`);
-
- return this.markAsExecuted(clonedContext);
- }
-
- /**
- * Build the sender tag to prepend to assistant messages.
- *
- * Uses a self-closing XML tag at the beginning:
- * - Placed at start so model sees "who is speaking" before the content
- * - Self-closing tag is less likely to be reproduced as it's not a "wrapper"
- */
- private buildSenderContext(_agentId: string, agentInfo: AgentInfo): string {
- return `<speaker name="${agentInfo.name}" />\n`;
- }
-}
diff --git a/packages/context-engine/src/processors/GroupRoleTransform.ts b/packages/context-engine/src/processors/GroupRoleTransform.ts
new file mode 100644
index 00000000000..1ba7753cef2
--- /dev/null
+++ b/packages/context-engine/src/processors/GroupRoleTransform.ts
@@ -0,0 +1,261 @@
+import debug from 'debug';
+
+import { BaseProcessor } from '../base/BaseProcessor';
+import type { Message, PipelineContext, ProcessorOptions } from '../types';
+
+const log = debug('context-engine:processor:GroupRoleTransformProcessor');
+
+/**
+ * Agent info for message sender identification
+ */
+export interface AgentInfo {
+ name: string;
+ role: 'supervisor' | 'participant';
+}
+
+/**
+ * Configuration for GroupRoleTransformProcessor
+ */
+export interface GroupRoleTransformConfig {
+ /**
+ * Mapping from agentId to agent info
+ * Used to look up agent name for each message
+ */
+ agentMap: Record<string, AgentInfo>;
+ /**
+ * The current agent ID that is responding
+ * Messages from this agent will remain as assistant role
+ */
+ currentAgentId: string;
+ /**
+ * Custom function to generate tool name from identifier and apiName
+ */
+ genToolName?: (identifier: string, apiName: string) => string;
+}
+
+/**
+ * Group Role Transform Processor
+ *
+ * Transforms messages from other agents to user role with speaker tags.
+ * This prevents the model from imitating speaker tags in its output.
+ *
+ * From the model's perspective:
+ * - role: assistant = "my" responses (current agent)
+ * - role: user = external input (human users and other agents)
+ *
+ * Processing logic:
+ * 1. Current agent's messages: Keep as assistant (no modifications)
+ * 2. Other agents' assistant messages: Convert to user with speaker tag
+ * 3. Other agents' tool messages: Convert to user with tool_result tag
+ *
+ * @example
+ * ```typescript
+ * const processor = new GroupRoleTransformProcessor({
+ * currentAgentId: 'travel-advisor',
+ * agentMap: {
+ * 'weather-expert': { name: 'Weather Expert', role: 'participant' },
+ * 'travel-advisor': { name: 'Travel Advisor', role: 'participant' },
+ * 'supervisor': { name: 'Supervisor', role: 'supervisor' },
+ * }
+ * });
+ * ```
+ */
+export class GroupRoleTransformProcessor extends BaseProcessor {
+ readonly name = 'GroupRoleTransformProcessor';
+
+ constructor(
+ private config: GroupRoleTransformConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const clonedContext = this.cloneContext(context);
+
+ // Skip if no currentAgentId or agentMap provided
+ if (!this.config.currentAgentId || !this.config.agentMap) {
+ log('No currentAgentId or agentMap provided, skipping processing');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ let assistantTransformed = 0;
+ let toolTransformed = 0;
+
+ clonedContext.messages = clonedContext.messages.map((msg: Message) => {
+ // Process assistant messages
+ if (msg.role === 'assistant' && msg.agentId) {
+ if (msg.agentId === this.config.currentAgentId) {
+ // Current agent: keep as assistant, no modifications
+ return msg;
+ }
+
+ // Other agent: transform to user with speaker tag
+ const transformed = this.transformAssistantMessage(msg);
+ if (transformed !== msg) {
+ assistantTransformed++;
+ log(`Transformed assistant message from agent: ${msg.agentId} to user`);
+ }
+ return transformed;
+ }
+
+ // Process tool messages
+ if (msg.role === 'tool' && msg.agentId) {
+ if (msg.agentId === this.config.currentAgentId) {
+ // Current agent: keep as tool
+ return msg;
+ }
+
+ // Other agent: transform to user with tool_result tag
+ const transformed = this.transformToolMessage(msg);
+ if (transformed !== msg) {
+ toolTransformed++;
+ log(`Transformed tool message from agent: ${msg.agentId} to user`);
+ }
+ return transformed;
+ }
+
+ return msg;
+ });
+
+ // Update metadata
+ clonedContext.metadata.groupRoleTransformProcessed = {
+ assistantTransformed,
+ toolTransformed,
+ };
+
+ log(
+ `Group role transform completed: ${assistantTransformed} assistant messages, ${toolTransformed} tool messages transformed`,
+ );
+
+ return this.markAsExecuted(clonedContext);
+ }
+
+ /**
+ * Transform an assistant message from another agent to a user message
+ */
+ private transformAssistantMessage(msg: Message): Message {
+ const agentInfo = this.config.agentMap[msg.agentId];
+ if (!agentInfo) {
+ // No agent info found, keep original
+ return msg;
+ }
+
+ const agentName = agentInfo.name;
+ let content = this.buildSpeakerTag(agentName);
+
+ // Add original content
+ const originalContent = this.getStringContent(msg.content);
+ if (originalContent) {
+ content += originalContent;
+ }
+
+ // Add tool_use section if message has tools
+ if (msg.tools && msg.tools.length > 0) {
+ content += this.buildToolUseSection(msg.tools);
+ }
+
+ return {
+ ...msg,
+ content,
+ role: 'user',
+ // Remove tool-related fields as they're now embedded in content
+ tools: undefined,
+ };
+ }
+
+ /**
+ * Transform a tool result message from another agent to a user message
+ */
+ private transformToolMessage(msg: Message): Message {
+ const agentInfo = this.config.agentMap[msg.agentId];
+ if (!agentInfo) {
+ // No agent info found, keep original
+ return msg;
+ }
+
+ const agentName = agentInfo.name;
+ const toolName = this.getToolName(msg.plugin);
+ const toolCallId = msg.tool_call_id || 'unknown';
+ const resultContent = this.getStringContent(msg.content);
+
+ const content = `${this.buildSpeakerTag(agentName)}<tool_result id="${toolCallId}" name="${toolName}">
+${resultContent}
+</tool_result>`;
+
+ return {
+ ...msg,
+ content,
+ // Remove tool-related fields
+ plugin: undefined,
+ role: 'user',
+ tool_call_id: undefined,
+ };
+ }
+
+ /**
+ * Build the speaker tag
+ */
+ private buildSpeakerTag(agentName: string): string {
+ return `<speaker name="${agentName}" />\n`;
+ }
+
+ /**
+ * Build the tool_use section for assistant messages with tools
+ */
+ private buildToolUseSection(tools: any[]): string {
+ let section = '\n\n<tool_use>\n';
+
+ for (const tool of tools) {
+ const toolName = this.getToolName(tool);
+ const toolId = tool.id || 'unknown';
+ const args = tool.arguments || '';
+
+ section += `<tool id="${toolId}" name="${toolName}">\n`;
+ section += `${args}\n`;
+ section += `</tool>\n`;
+ }
+
+ section += '</tool_use>';
+ return section;
+ }
+
+ /**
+ * Get tool name from tool object
+ */
+ private getToolName(tool: any): string {
+ if (!tool) return 'unknown';
+
+ const identifier = tool.identifier || '';
+ const apiName = tool.apiName || '';
+
+ if (this.config.genToolName) {
+ return this.config.genToolName(identifier, apiName);
+ }
+
+ if (identifier && apiName) {
+ return `${identifier}.${apiName}`;
+ }
+
+ return identifier || apiName || 'unknown';
+ }
+
+ /**
+ * Extract string content from message content (handles both string and array formats)
+ */
+ private getStringContent(content: string | any[]): string {
+ if (typeof content === 'string') {
+ return content;
+ }
+
+ if (Array.isArray(content)) {
+ // Extract text from array content
+ return content
+ .filter((part: any) => part.type === 'text')
+ .map((part: any) => part.text || '')
+ .join('\n');
+ }
+
+ return '';
+ }
+}
diff --git a/packages/context-engine/src/processors/__tests__/GroupMessageSender.test.ts b/packages/context-engine/src/processors/__tests__/GroupMessageSender.test.ts
deleted file mode 100644
index 36271604b15..00000000000
--- a/packages/context-engine/src/processors/__tests__/GroupMessageSender.test.ts
+++ /dev/null
@@ -1,274 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { PipelineContext } from '../../types';
-import { GroupMessageSenderProcessor } from '../GroupMessageSender';
-
-describe('GroupMessageSenderProcessor', () => {
- const createContext = (messages: any[]): PipelineContext => ({
- initialState: { messages: [] },
- isAborted: false,
- messages,
- metadata: {},
- });
-
- describe('Basic Scenarios', () => {
- it('should inject sender info into assistant message with agentId', async () => {
- const processor = new GroupMessageSenderProcessor({
- agentMap: {
- agt_weather: { name: 'Weather Expert', role: 'participant' },
- },
- });
-
- const input: any[] = [
- { role: 'user', content: 'What is the weather?' },
- { role: 'assistant', content: 'The weather is sunny.', agentId: 'agt_weather' },
- ];
-
- const context = createContext(input);
- const result = await processor.process(context);
-
- expect(result.messages).toHaveLength(2);
-
- // User message should be unchanged
- expect(result.messages[0].content).toBe('What is the weather?');
-
- // Assistant message should have speaker tag prepended
- const assistantContent = result.messages[1].content;
- expect(assistantContent).toMatch(/^<speaker name="Weather Expert" \/>/);
- expect(assistantContent).toContain('The weather is sunny.');
-
- // Check metadata
- expect(result.metadata.groupMessageSenderProcessed).toBe(1);
- });
-
- it('should inject sender info for supervisor role', async () => {
- const processor = new GroupMessageSenderProcessor({
- agentMap: {
- agt_supervisor: { name: 'Group Supervisor', role: 'supervisor' },
- },
- });
-
- const input: any[] = [
- { role: 'assistant', content: 'I will coordinate the agents.', agentId: 'agt_supervisor' },
- ];
-
- const context = createContext(input);
- const result = await processor.process(context);
-
- const assistantContent = result.messages[0].content;
- expect(assistantContent).toMatch(/^<speaker name="Group Supervisor" \/>/);
- });
-
- it('should not modify assistant message without agentId', async () => {
- const processor = new GroupMessageSenderProcessor({
- agentMap: {
- agt_weather: { name: 'Weather Expert', role: 'participant' },
- },
- });
-
- const input: any[] = [{ role: 'assistant', content: 'Hello from assistant.' }];
-
- const context = createContext(input);
- const result = await processor.process(context);
-
- // Should be unchanged
- expect(result.messages[0].content).toBe('Hello from assistant.');
- expect(result.metadata.groupMessageSenderProcessed).toBe(0);
- });
-
- it('should not modify assistant message with unknown agentId', async () => {
- const processor = new GroupMessageSenderProcessor({
- agentMap: {
- agt_weather: { name: 'Weather Expert', role: 'participant' },
- },
- });
-
- const input: any[] = [{ role: 'assistant', content: 'Hello.', agentId: 'agt_unknown' }];
-
- const context = createContext(input);
- const result = await processor.process(context);
-
- // Should be unchanged because agentId not in map
- expect(result.messages[0].content).toBe('Hello.');
- expect(result.metadata.groupMessageSenderProcessed).toBe(0);
- });
-
- it('should not modify user or tool messages', async () => {
- const processor = new GroupMessageSenderProcessor({
- agentMap: {
- agt_weather: { name: 'Weather Expert', role: 'participant' },
- },
- });
-
- const input: any[] = [
- { role: 'user', content: 'Hello', agentId: 'agt_weather' },
- { role: 'tool', content: 'Tool result', agentId: 'agt_weather' },
- ];
-
- const context = createContext(input);
- const result = await processor.process(context);
-
- expect(result.messages[0].content).toBe('Hello');
- expect(result.messages[1].content).toBe('Tool result');
- expect(result.metadata.groupMessageSenderProcessed).toBe(0);
- });
- });
-
- describe('Multiple Messages', () => {
- it('should process multiple assistant messages from different agents', async () => {
- const processor = new GroupMessageSenderProcessor({
- agentMap: {
- agt_weather: { name: 'Weather Expert', role: 'participant' },
- agt_news: { name: 'News Reporter', role: 'participant' },
- agt_supervisor: { name: 'Supervisor', role: 'supervisor' },
- },
- });
-
- const input: any[] = [
- { role: 'user', content: 'Give me updates' },
- { role: 'assistant', content: 'Weather is sunny.', agentId: 'agt_weather' },
- { role: 'assistant', content: 'Top news today.', agentId: 'agt_news' },
- { role: 'assistant', content: 'Summary complete.', agentId: 'agt_supervisor' },
- ];
-
- const context = createContext(input);
- const result = await processor.process(context);
-
- expect(result.messages).toHaveLength(4);
-
- // Check each assistant message has correct speaker tag prepended
- expect(result.messages[1].content).toMatch(/^<speaker name="Weather Expert" \/>/);
- expect(result.messages[2].content).toMatch(/^<speaker name="News Reporter" \/>/);
- expect(result.messages[3].content).toMatch(/^<speaker name="Supervisor" \/>/);
-
- expect(result.metadata.groupMessageSenderProcessed).toBe(3);
- });
- });
-
- describe('Multimodal Messages', () => {
- it('should handle array content (multimodal messages)', async () => {
- const processor = new GroupMessageSenderProcessor({
- agentMap: {
- agt_weather: { name: 'Weather Expert', role: 'participant' },
- },
- });
-
- const input: any[] = [
- {
- role: 'assistant',
- content: [
- { type: 'text', text: 'Here is the weather chart.' },
- { type: 'image_url', image_url: { url: 'https://example.com/chart.png' } },
- ],
- agentId: 'agt_weather',
- },
- ];
-
- const context = createContext(input);
- const result = await processor.process(context);
-
- const content = result.messages[0].content as any[];
- expect(Array.isArray(content)).toBe(true);
-
- // The first text part should have speaker tag prepended
- const textPart = content.find((p: any) => p.type === 'text');
- expect(textPart.text).toMatch(/^<speaker name="Weather Expert" \/>/);
- expect(textPart.text).toContain('Here is the weather chart.');
-
- // Image part should be unchanged
- const imagePart = content.find((p: any) => p.type === 'image_url');
- expect(imagePart.image_url.url).toBe('https://example.com/chart.png');
-
- expect(result.metadata.groupMessageSenderProcessed).toBe(1);
- });
-
- it('should append to the last text part in multimodal content', async () => {
- const processor = new GroupMessageSenderProcessor({
- agentMap: {
- agt_weather: { name: 'Weather Expert', role: 'participant' },
- },
- });
-
- const input: any[] = [
- {
- role: 'assistant',
- content: [
- { type: 'text', text: 'First text.' },
- { type: 'image_url', image_url: { url: 'https://example.com/img.png' } },
- { type: 'text', text: 'Last text.' },
- ],
- agentId: 'agt_weather',
- },
- ];
-
- const context = createContext(input);
- const result = await processor.process(context);
-
- const content = result.messages[0].content;
-
- // First text part should have speaker tag prepended
- expect(content[0].text).toMatch(/^<speaker name="Weather Expert" \/>/);
- expect(content[0].text).toContain('First text.');
-
- // Last text should be unchanged
- expect(content[2].text).toBe('Last text.');
- });
- });
-
- describe('Edge Cases', () => {
- it('should skip processing with empty agentMap', async () => {
- const processor = new GroupMessageSenderProcessor({
- agentMap: {},
- });
-
- const input: any[] = [{ role: 'assistant', content: 'Hello', agentId: 'agt_weather' }];
-
- const context = createContext(input);
- const result = await processor.process(context);
-
- expect(result.messages[0].content).toBe('Hello');
- });
-
- it('should handle empty messages array', async () => {
- const processor = new GroupMessageSenderProcessor({
- agentMap: {
- agt_weather: { name: 'Weather Expert', role: 'participant' },
- },
- });
-
- const context = createContext([]);
- const result = await processor.process(context);
-
- expect(result.messages).toHaveLength(0);
- expect(result.metadata.groupMessageSenderProcessed).toBe(0);
- });
-
- it('should preserve original message properties', async () => {
- const processor = new GroupMessageSenderProcessor({
- agentMap: {
- agt_weather: { name: 'Weather Expert', role: 'participant' },
- },
- });
-
- const input: any[] = [
- {
- role: 'assistant',
- content: 'Weather info.',
- agentId: 'agt_weather',
- id: 'msg-123',
- createdAt: '2025-01-01T00:00:00Z',
- customField: 'custom value',
- },
- ];
-
- const context = createContext(input);
- const result = await processor.process(context);
-
- const msg = result.messages[0];
- expect(msg.id).toBe('msg-123');
- expect(msg.createdAt).toBe('2025-01-01T00:00:00Z');
- expect(msg.customField).toBe('custom value');
- expect(msg.agentId).toBe('agt_weather');
- });
- });
-});
diff --git a/packages/context-engine/src/processors/__tests__/GroupRoleTransform.test.ts b/packages/context-engine/src/processors/__tests__/GroupRoleTransform.test.ts
new file mode 100644
index 00000000000..aa175f41451
--- /dev/null
+++ b/packages/context-engine/src/processors/__tests__/GroupRoleTransform.test.ts
@@ -0,0 +1,553 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { GroupRoleTransformProcessor } from '../GroupRoleTransform';
+
+describe('GroupRoleTransformProcessor', () => {
+ const createContext = (messages: any[]): PipelineContext => ({
+ initialState: { messages: [] },
+ isAborted: false,
+ messages,
+ metadata: {},
+ });
+
+ const defaultConfig = {
+ agentMap: {
+ 'agent-a': { name: 'Agent A', role: 'participant' as const },
+ 'agent-b': { name: 'Agent B', role: 'participant' as const },
+ 'supervisor': { name: 'Supervisor', role: 'supervisor' as const },
+ },
+ currentAgentId: 'agent-a',
+ };
+
+ describe('assistant message transformation', () => {
+ it('should keep current agent messages as assistant', async () => {
+ const processor = new GroupRoleTransformProcessor(defaultConfig);
+ const context = createContext([
+ { content: 'Hello', role: 'user' },
+ { agentId: 'agent-a', content: 'Response from current agent', role: 'assistant' },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[1].role).toBe('assistant');
+ expect(result.messages[1].content).toBe('Response from current agent');
+ });
+
+ it('should transform other agent messages to user with speaker tag', async () => {
+ const processor = new GroupRoleTransformProcessor(defaultConfig);
+ const context = createContext([
+ { content: 'Hello', role: 'user' },
+ { agentId: 'agent-b', content: 'Response from other agent', role: 'assistant' },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[1].role).toBe('user');
+ expect(result.messages[1].content).toContain('<speaker name="Agent B" />');
+ expect(result.messages[1].content).toContain('Response from other agent');
+ });
+
+ it('should transform supervisor messages to user when current agent is participant', async () => {
+ const processor = new GroupRoleTransformProcessor(defaultConfig);
+ const context = createContext([
+ { content: 'Hello', role: 'user' },
+ { agentId: 'supervisor', content: 'Supervisor response', role: 'assistant' },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[1].role).toBe('user');
+ expect(result.messages[1].content).toContain('<speaker name="Supervisor" />');
+ });
+
+ it('should keep assistant messages without agentId unchanged', async () => {
+ const processor = new GroupRoleTransformProcessor(defaultConfig);
+ const context = createContext([
+ { content: 'Hello', role: 'user' },
+ { content: 'Response without agentId', role: 'assistant' },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[1].role).toBe('assistant');
+ expect(result.messages[1].content).toBe('Response without agentId');
+ });
+ });
+
+ describe('assistant message with tools', () => {
+ it('should transform other agent message with tools to user with tool_use section', async () => {
+ const processor = new GroupRoleTransformProcessor(defaultConfig);
+ const context = createContext([
+ { content: 'Hello', role: 'user' },
+ {
+ agentId: 'agent-b',
+ content: 'Let me check the weather',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'getWeather',
+ arguments: '{"city": "Beijing"}',
+ id: 'call_123',
+ identifier: 'weather-plugin',
+ },
+ ],
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[1].role).toBe('user');
+ expect(result.messages[1].content).toContain('<speaker name="Agent B" />');
+ expect(result.messages[1].content).toContain('Let me check the weather');
+ expect(result.messages[1].content).toContain('<tool_use>');
+ expect(result.messages[1].content).toContain(
+ '<tool id="call_123" name="weather-plugin.getWeather">',
+ );
+ expect(result.messages[1].content).toContain('{"city": "Beijing"}');
+ expect(result.messages[1].content).toContain('</tool>');
+ expect(result.messages[1].content).toContain('</tool_use>');
+ expect(result.messages[1].tools).toBeUndefined();
+ });
+
+ it('should transform other agent message with multiple tools', async () => {
+ const processor = new GroupRoleTransformProcessor(defaultConfig);
+ const context = createContext([
+ {
+ agentId: 'agent-b',
+ content: 'Checking multiple things',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'getWeather',
+ arguments: '{"city": "Beijing"}',
+ id: 'call_1',
+ identifier: 'weather',
+ },
+ {
+ apiName: 'getTime',
+ arguments: '{"timezone": "UTC"}',
+ id: 'call_2',
+ identifier: 'time',
+ },
+ ],
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].role).toBe('user');
+ expect(result.messages[0].content).toContain('<tool id="call_1" name="weather.getWeather">');
+ expect(result.messages[0].content).toContain('<tool id="call_2" name="time.getTime">');
+ });
+
+ it('should keep current agent message with tools as assistant', async () => {
+ const processor = new GroupRoleTransformProcessor(defaultConfig);
+ const context = createContext([
+ {
+ agentId: 'agent-a',
+ content: 'Current agent using tools',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'search',
+ arguments: '{"q": "test"}',
+ id: 'call_xyz',
+ identifier: 'search-plugin',
+ },
+ ],
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].role).toBe('assistant');
+ expect(result.messages[0].tools).toBeDefined();
+ expect(result.messages[0].content).not.toContain('<speaker');
+ });
+ });
+
+ describe('tool message transformation', () => {
+ it('should transform other agent tool messages to user with tool_result', async () => {
+ const processor = new GroupRoleTransformProcessor(defaultConfig);
+ const context = createContext([
+ {
+ agentId: 'agent-b',
+ content: '{"temperature": 25}',
+ plugin: {
+ apiName: 'getWeather',
+ identifier: 'weather-plugin',
+ },
+ role: 'tool',
+ tool_call_id: 'call_123',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].role).toBe('user');
+ expect(result.messages[0].content).toContain('<speaker name="Agent B" />');
+ expect(result.messages[0].content).toContain(
+ '<tool_result id="call_123" name="weather-plugin.getWeather">',
+ );
+ expect(result.messages[0].content).toContain('{"temperature": 25}');
+ expect(result.messages[0].content).toContain('</tool_result>');
+ expect(result.messages[0].tool_call_id).toBeUndefined();
+ expect(result.messages[0].plugin).toBeUndefined();
+ });
+
+ it('should keep current agent tool messages unchanged', async () => {
+ const processor = new GroupRoleTransformProcessor(defaultConfig);
+ const context = createContext([
+ {
+ agentId: 'agent-a',
+ content: '{"result": "data"}',
+ plugin: {
+ apiName: 'search',
+ identifier: 'search-plugin',
+ },
+ role: 'tool',
+ tool_call_id: 'call_abc',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].role).toBe('tool');
+ expect(result.messages[0].tool_call_id).toBe('call_abc');
+ expect(result.messages[0].content).not.toContain('<speaker');
+ });
+
+ it('should keep tool messages without agentId unchanged', async () => {
+ const processor = new GroupRoleTransformProcessor(defaultConfig);
+ const context = createContext([
+ {
+ content: '{"result": "data"}',
+ role: 'tool',
+ tool_call_id: 'call_abc',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].role).toBe('tool');
+ expect(result.messages[0].tool_call_id).toBe('call_abc');
+ });
+ });
+
+ describe('mixed conversation', () => {
+ it('should handle mixed conversation with multiple agents', async () => {
+ const processor = new GroupRoleTransformProcessor(defaultConfig);
+ const context = createContext([
+ { content: 'User question', role: 'user' },
+ { agentId: 'supervisor', content: 'Supervisor intro', role: 'assistant' },
+ { agentId: 'agent-b', content: 'Agent B response', role: 'assistant' },
+ { agentId: 'agent-a', content: 'Current agent response', role: 'assistant' },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(4);
+ // User message unchanged
+ expect(result.messages[0].role).toBe('user');
+ expect(result.messages[0].content).toBe('User question');
+ // Supervisor transformed to user
+ expect(result.messages[1].role).toBe('user');
+ expect(result.messages[1].content).toContain('<speaker name="Supervisor" />');
+ // Agent B transformed to user
+ expect(result.messages[2].role).toBe('user');
+ expect(result.messages[2].content).toContain('<speaker name="Agent B" />');
+ // Current agent stays as assistant
+ expect(result.messages[3].role).toBe('assistant');
+ expect(result.messages[3].content).toBe('Current agent response');
+ });
+
+ it('should handle tool call and result from other agent', async () => {
+ const processor = new GroupRoleTransformProcessor(defaultConfig);
+ const context = createContext([
+ { content: 'Check weather', role: 'user' },
+ {
+ agentId: 'agent-b',
+ content: 'Checking...',
+ role: 'assistant',
+ tools: [{ apiName: 'get', arguments: '{}', id: 'call_1', identifier: 'weather' }],
+ },
+ {
+ agentId: 'agent-b',
+ content: '{"temp": 25}',
+ plugin: { apiName: 'get', identifier: 'weather' },
+ role: 'tool',
+ tool_call_id: 'call_1',
+ },
+ { agentId: 'agent-a', content: 'Based on the weather...', role: 'assistant' },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(4);
+ // User unchanged
+ expect(result.messages[0].role).toBe('user');
+ // Agent B assistant with tool -> user
+ expect(result.messages[1].role).toBe('user');
+ expect(result.messages[1].content).toContain('<tool_use>');
+ // Agent B tool result -> user
+ expect(result.messages[2].role).toBe('user');
+ expect(result.messages[2].content).toContain('<tool_result');
+ // Current agent -> assistant
+ expect(result.messages[3].role).toBe('assistant');
+ });
+ });
+
+ describe('edge cases', () => {
+ it('should skip processing when no currentAgentId provided', async () => {
+ const processor = new GroupRoleTransformProcessor({
+ agentMap: defaultConfig.agentMap,
+ currentAgentId: '',
+ });
+ const context = createContext([{ agentId: 'agent-b', content: 'Test', role: 'assistant' }]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].role).toBe('assistant');
+ });
+
+ it('should skip processing when no agentMap provided', async () => {
+ const processor = new GroupRoleTransformProcessor({
+ agentMap: {},
+ currentAgentId: 'agent-a',
+ });
+ const context = createContext([{ agentId: 'agent-b', content: 'Test', role: 'assistant' }]);
+
+ const result = await processor.process(context);
+
+ // No agentMap entry for agent-b, so message is unchanged
+ expect(result.messages[0].role).toBe('assistant');
+ });
+
+ it('should handle empty messages array', async () => {
+ const processor = new GroupRoleTransformProcessor(defaultConfig);
+ const context = createContext([]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(0);
+ });
+
+ it('should handle message with empty content', async () => {
+ const processor = new GroupRoleTransformProcessor(defaultConfig);
+ const context = createContext([{ agentId: 'agent-b', content: '', role: 'assistant' }]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].role).toBe('user');
+ expect(result.messages[0].content).toContain('<speaker name="Agent B" />');
+ });
+
+ it('should handle array content (multimodal)', async () => {
+ const processor = new GroupRoleTransformProcessor(defaultConfig);
+ const context = createContext([
+ {
+ agentId: 'agent-b',
+ content: [
+ { text: 'Here is the image analysis', type: 'text' },
+ { image_url: 'data:image/png;base64,...', type: 'image_url' },
+ ],
+ role: 'assistant',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].role).toBe('user');
+ expect(result.messages[0].content).toContain('<speaker name="Agent B" />');
+ expect(result.messages[0].content).toContain('Here is the image analysis');
+ });
+
+ it('should track transformation counts in metadata', async () => {
+ const processor = new GroupRoleTransformProcessor(defaultConfig);
+ const context = createContext([
+ { agentId: 'agent-b', content: 'Msg 1', role: 'assistant' },
+ { agentId: 'agent-b', content: 'Result', role: 'tool', tool_call_id: 'call_1' },
+ { agentId: 'agent-a', content: 'Current', role: 'assistant' },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.metadata.groupRoleTransformProcessed).toEqual({
+ assistantTransformed: 1,
+ toolTransformed: 1,
+ });
+ });
+ });
+
+ describe('custom tool name generator', () => {
+ it('should use custom genToolName function', async () => {
+ const processor = new GroupRoleTransformProcessor({
+ ...defaultConfig,
+ genToolName: (identifier, apiName) => `custom_${identifier}_${apiName}`,
+ });
+ const context = createContext([
+ {
+ agentId: 'agent-b',
+ content: 'Test',
+ role: 'assistant',
+ tools: [{ apiName: 'search', arguments: '{}', id: 'call_1', identifier: 'plugin' }],
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].content).toContain('name="custom_plugin_search"');
+ });
+ });
+
+ describe('comprehensive end-to-end transformation', () => {
+ it('should correctly transform a full group conversation with 8 messages', async () => {
+ const processor = new GroupRoleTransformProcessor({
+ agentMap: {
+ 'agent-a': { name: 'Travel Advisor', role: 'participant' },
+ 'agent-b': { name: 'Weather Expert', role: 'participant' },
+ 'agent-c': { name: 'Food Critic', role: 'participant' },
+ 'supervisor': { name: 'Supervisor', role: 'supervisor' },
+ },
+ currentAgentId: 'agent-a',
+ });
+
+ const inputMessages = [
+ // 1. User's original question
+ { content: '帮我规划一下明天去杭州的行程', id: 'msg_1', role: 'user' },
+ // 2. Supervisor's broadcast instruction (from orchestration)
+ {
+ agentId: 'supervisor',
+ content: '请各位专家从自己的角度给出建议',
+ id: 'msg_2',
+ role: 'assistant',
+ },
+ // 3. Weather Expert's response with tool
+ {
+ agentId: 'agent-b',
+ content: '让我查一下杭州明天的天气',
+ id: 'msg_3',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'getWeather',
+ arguments: '{"city": "杭州", "date": "tomorrow"}',
+ id: 'call_weather_1',
+ identifier: 'weather-plugin',
+ },
+ ],
+ },
+ // 4. Weather tool result
+ {
+ agentId: 'agent-b',
+ content: '{"temperature": 22, "weather": "多云", "humidity": 65}',
+ id: 'msg_4',
+ plugin: { apiName: 'getWeather', identifier: 'weather-plugin' },
+ role: 'tool',
+ tool_call_id: 'call_weather_1',
+ },
+ // 5. Weather Expert's final response
+ {
+ agentId: 'agent-b',
+ content: '明天杭州天气不错,22度多云,适合出行',
+ id: 'msg_5',
+ role: 'assistant',
+ },
+ // 6. Food Critic's response
+ {
+ agentId: 'agent-c',
+ content: '推荐去楼外楼吃正宗的西湖醋鱼',
+ id: 'msg_6',
+ role: 'assistant',
+ },
+ // 7. Current agent (Travel Advisor)'s response - should stay as assistant
+ {
+ agentId: 'agent-a',
+ content: '综合以上建议,我来帮你规划具体行程',
+ id: 'msg_7',
+ role: 'assistant',
+ },
+ // 8. Follow-up user question
+ { content: '还有什么景点推荐吗?', id: 'msg_8', role: 'user' },
+ ];
+
+ const context = createContext(inputMessages);
+ const result = await processor.process(context);
+
+ // Verify the entire output array
+ expect(result.messages).toEqual([
+ // 1. User message - unchanged
+ { content: '帮我规划一下明天去杭州的行程', id: 'msg_1', role: 'user' },
+ // 2. Supervisor -> user with speaker tag
+ {
+ agentId: 'supervisor',
+ content: '<speaker name="Supervisor" />\n请各位专家从自己的角度给出建议',
+ id: 'msg_2',
+ role: 'user',
+ },
+ // 3. Weather Expert with tool -> user with speaker + tool_use
+ {
+ agentId: 'agent-b',
+ content: `<speaker name="Weather Expert" />
+让我查一下杭州明天的天气
+
+<tool_use>
+<tool id="call_weather_1" name="weather-plugin.getWeather">
+{"city": "杭州", "date": "tomorrow"}
+</tool>
+</tool_use>`,
+ id: 'msg_3',
+ role: 'user',
+ tools: undefined,
+ },
+ // 4. Tool result -> user with speaker + tool_result
+ {
+ agentId: 'agent-b',
+ content: `<speaker name="Weather Expert" />
+<tool_result id="call_weather_1" name="weather-plugin.getWeather">
+{"temperature": 22, "weather": "多云", "humidity": 65}
+</tool_result>`,
+ id: 'msg_4',
+ plugin: undefined,
+ role: 'user',
+ tool_call_id: undefined,
+ },
+ // 5. Weather Expert's final response -> user with speaker
+ {
+ agentId: 'agent-b',
+ content: '<speaker name="Weather Expert" />\n明天杭州天气不错,22度多云,适合出行',
+ id: 'msg_5',
+ role: 'user',
+ },
+ // 6. Food Critic -> user with speaker
+ {
+ agentId: 'agent-c',
+ content: '<speaker name="Food Critic" />\n推荐去楼外楼吃正宗的西湖醋鱼',
+ id: 'msg_6',
+ role: 'user',
+ },
+ // 7. Current agent (Travel Advisor) - stays as assistant, no speaker tag
+ {
+ agentId: 'agent-a',
+ content: '综合以上建议,我来帮你规划具体行程',
+ id: 'msg_7',
+ role: 'assistant',
+ },
+ // 8. User message - unchanged
+ { content: '还有什么景点推荐吗?', id: 'msg_8', role: 'user' },
+ ]);
+
+ // Verify metadata
+ expect(result.metadata.groupRoleTransformProcessed).toEqual({
+ assistantTransformed: 4, // supervisor, agent-b x2, agent-c
+ toolTransformed: 1, // weather tool result
+ });
+ });
+ });
+});
diff --git a/packages/context-engine/src/processors/index.ts b/packages/context-engine/src/processors/index.ts
index f629127c87b..d29a2c46baf 100644
--- a/packages/context-engine/src/processors/index.ts
+++ b/packages/context-engine/src/processors/index.ts
@@ -1,7 +1,7 @@
// Transformer processors
export { AgentCouncilFlattenProcessor } from './AgentCouncilFlatten';
export { GroupMessageFlattenProcessor } from './GroupMessageFlatten';
-export { GroupMessageSenderProcessor } from './GroupMessageSender';
+export { GroupRoleTransformProcessor } from './GroupRoleTransform';
export { HistoryTruncateProcessor } from './HistoryTruncate';
export { InputTemplateProcessor } from './InputTemplate';
export { MessageCleanupProcessor } from './MessageCleanup';
@@ -19,7 +19,7 @@ export { ToolCallProcessor } from './ToolCall';
export { ToolMessageReorder } from './ToolMessageReorder';
// Re-export types
-export type { AgentInfo, GroupMessageSenderConfig } from './GroupMessageSender';
+export type { AgentInfo, GroupRoleTransformConfig } from './GroupRoleTransform';
export type { HistoryTruncateConfig } from './HistoryTruncate';
export type { InputTemplateConfig } from './InputTemplate';
export type { MessageContentConfig, UserMessageContentPart } from './MessageContent';
diff --git a/packages/context-engine/src/providers/__tests__/GroupContextInjector.test.ts b/packages/context-engine/src/providers/__tests__/GroupContextInjector.test.ts
index d941e368e00..0963274061b 100644
--- a/packages/context-engine/src/providers/__tests__/GroupContextInjector.test.ts
+++ b/packages/context-engine/src/providers/__tests__/GroupContextInjector.test.ts
@@ -57,11 +57,6 @@ describe('GroupContextInjector', () => {
expect(systemContent).toContain('<member name="Writer" id="agt_writer" />');
expect(systemContent).toContain('<member name="Editor" id="agt_editor" you="true" />');
- // Output rules section (important for LOBE-1866)
- expect(systemContent).toContain('<critical_output_rules>');
- expect(systemContent).toContain('<group_context>');
- expect(systemContent).toContain('NEVER start your response with');
-
// Identity rules
expect(systemContent).toContain('<identity_rules>');
expect(systemContent).toContain('NEVER expose or display agent IDs');
@@ -156,8 +151,8 @@ describe('GroupContextInjector', () => {
});
});
- describe('Output Rules Section (LOBE-1866)', () => {
- it('should always include critical output rules', async () => {
+ describe('Identity Rules Section', () => {
+ it('should always include identity rules', async () => {
const injector = new GroupContextInjector({
enabled: true,
// Minimal config
@@ -170,15 +165,8 @@ describe('GroupContextInjector', () => {
const systemContent = result.messages[0].content;
- // Even with minimal config, critical output rules should be present
- expect(systemContent).toContain('<critical_output_rules>');
- expect(systemContent).toContain('Your responses must contain ONLY your actual reply content');
- expect(systemContent).toContain('NEVER start your response with');
- expect(systemContent).toContain('<speaker');
-
- // Identity rules should also be present
- expect(systemContent).toContain('<identity_rules>');
- expect(systemContent).toContain('NEVER expose or display agent IDs');
+ // Even with minimal config, identity rules should be present
+ expect(systemContent).toMatchSnapshot();
});
});
diff --git a/packages/context-engine/src/providers/__tests__/__snapshots__/GroupContextInjector.test.ts.snap b/packages/context-engine/src/providers/__tests__/__snapshots__/GroupContextInjector.test.ts.snap
index 6a0b1af77af..6bde149a17f 100644
--- a/packages/context-engine/src/providers/__tests__/__snapshots__/GroupContextInjector.test.ts.snap
+++ b/packages/context-engine/src/providers/__tests__/__snapshots__/GroupContextInjector.test.ts.snap
@@ -7,13 +7,6 @@ exports[`GroupContextInjector > Edge Cases > should handle empty members array 1
You are "", acting as a in the multi-agent group "Empty Group".
Your internal agent ID is (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:
Empty group description
@@ -22,6 +15,29 @@ Empty group description
<group_participants>The following agents are available in this group:
+</group_participants>
+
+<identity_rules>
+- NEVER expose or display agent IDs to users - always refer to agents by their names
+</identity_rules>
+</group_context>"
+`;
+
+exports[`GroupContextInjector > Identity Rules Section > should always include identity rules 1`] = `
+"Base prompt.
+
+<group_context>
+You are "", acting as a in the multi-agent group "".
+Your internal agent ID is (for system use only, never expose to users).
+
+<group_description>The following describes the purpose and goals of this agent group:
+
+
+</group_description>
+
+<group_participants>The following agents are available in this group:
+
+
</group_participants>
<identity_rules>
@@ -37,13 +53,6 @@ exports[`GroupContextInjector > Variable Replacement > should handle config with
You are "", acting as a in the multi-agent group "Test Group".
Your internal agent ID is (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:
Test group description
@@ -67,13 +76,6 @@ exports[`GroupContextInjector > Variable Replacement > should handle config with
You are "Editor", acting as a participant in the multi-agent group "".
Your internal agent ID is agt_editor (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:
@@ -97,13 +99,6 @@ exports[`GroupContextInjector > Variable Replacement > should handle empty confi
You are "", acting as a in the multi-agent group "".
Your internal agent ID is (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:
diff --git a/packages/prompts/src/prompts/agentGroup/__snapshots__/index.test.ts.snap b/packages/prompts/src/prompts/agentGroup/__snapshots__/index.test.ts.snap
index b66876c8599..7d4affed6c6 100644
--- a/packages/prompts/src/prompts/agentGroup/__snapshots__/index.test.ts.snap
+++ b/packages/prompts/src/prompts/agentGroup/__snapshots__/index.test.ts.snap
@@ -65,13 +65,6 @@ 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}}
diff --git a/packages/prompts/src/prompts/agentGroup/groupContext.ts b/packages/prompts/src/prompts/agentGroup/groupContext.ts
index 593241a0025..20e001d787b 100644
--- a/packages/prompts/src/prompts/agentGroup/groupContext.ts
+++ b/packages/prompts/src/prompts/agentGroup/groupContext.ts
@@ -19,13 +19,6 @@ export interface GroupContextMemberInfo {
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}}
diff --git a/src/app/[variants]/(main)/group/features/Conversation/AgentWelcome/OpeningQuestions.tsx b/src/app/[variants]/(main)/group/features/Conversation/AgentWelcome/OpeningQuestions.tsx
index 309ebabc08f..0317111fd75 100644
--- a/src/app/[variants]/(main)/group/features/Conversation/AgentWelcome/OpeningQuestions.tsx
+++ b/src/app/[variants]/(main)/group/features/Conversation/AgentWelcome/OpeningQuestions.tsx
@@ -1,13 +1,11 @@
'use client';
import { Block, Flexbox } from '@lobehub/ui';
-import { createStaticStyles , responsive } from 'antd-style';
+import { createStaticStyles, responsive } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useChatStore } from '@/store/chat';
-
-// import { useSend } from '../../features/ChatInput/useSend';
+import { useConversationStore } from '@/features/Conversation';
const styles = createStaticStyles(({ css, cssVar }) => ({
card: css`
@@ -38,8 +36,7 @@ interface OpeningQuestionsProps {
const OpeningQuestions = memo<OpeningQuestionsProps>(({ mobile, questions }) => {
const { t } = useTranslation('welcome');
- const [updateMessageInput] = useChatStore((s) => [s.updateMessageInput]);
- // const { send: sendMessage } = useSend();
+ const [sendMessage] = useConversationStore((s) => [s.sendMessage]);
return (
<div className={styles.container}>
@@ -52,8 +49,7 @@ const OpeningQuestions = memo<OpeningQuestionsProps>(({ mobile, questions }) =>
clickable
key={question}
onClick={() => {
- updateMessageInput(question);
- // sendMessage({ isWelcomeQuestion: true });
+ sendMessage({ message: question });
}}
paddingBlock={8}
paddingInline={12}
diff --git a/src/app/[variants]/(main)/group/features/Conversation/MainChatInput/GroupChat.tsx b/src/app/[variants]/(main)/group/features/Conversation/MainChatInput/GroupChat.tsx
index e84b7d42e4a..57e0444e704 100644
--- a/src/app/[variants]/(main)/group/features/Conversation/MainChatInput/GroupChat.tsx
+++ b/src/app/[variants]/(main)/group/features/Conversation/MainChatInput/GroupChat.tsx
@@ -92,9 +92,6 @@ const Desktop = memo((props: { targetMemberId?: string }) => {
onMarkdownContentChange={(content) => {
useChatStore.setState({ inputMessage: content });
}}
- onSend={() => {
- // send({ targetMemberId: props.targetMemberId });
- }}
rightActions={isDMPortal ? [] : rightActions}
// sendButtonProps={{ disabled, generating, onStop: stop }}
sendMenu={{
diff --git a/src/app/[variants]/(main)/group/features/Conversation/useGroupContext.ts b/src/app/[variants]/(main)/group/features/Conversation/useGroupContext.ts
index 2881dd21183..28c297bec4c 100644
--- a/src/app/[variants]/(main)/group/features/Conversation/useGroupContext.ts
+++ b/src/app/[variants]/(main)/group/features/Conversation/useGroupContext.ts
@@ -23,9 +23,12 @@ export function useGroupContext(): ConversationContext {
const supervisorAgentId = currentGroup?.supervisorAgentId;
// Group context uses supervisorAgentId as agentId for message storage
+ // When in group mode (not group_agent thread mode), the supervisor is responding
+ // so we mark isSupervisor: true for proper UI rendering
return {
agentId: supervisorAgentId || '',
groupId: groupId ?? undefined,
+ isSupervisor: !threadId, // Supervisor responds in main group chat, not in agent threads
scope: threadId ? 'group_agent' : 'group',
threadId,
topicId,
diff --git a/src/features/ChatInput/Desktop/index.tsx b/src/features/ChatInput/Desktop/index.tsx
index 44891c0531f..f46f7373e8b 100644
--- a/src/features/ChatInput/Desktop/index.tsx
+++ b/src/features/ChatInput/Desktop/index.tsx
@@ -95,9 +95,7 @@ const DesktopChatInput = memo<DesktopChatInputProps>(
<ChatInputActionBar
left={<ActionBar dropdownPlacement={dropdownPlacement} />}
right={<SendArea />}
- style={{
- paddingRight: 8,
- }}
+ style={{ paddingRight: 8 }}
/>
}
fullscreen={expand}
diff --git a/src/features/Conversation/store/slices/message/action/crud.ts b/src/features/Conversation/store/slices/message/action/crud.ts
index e397e4ab0cd..c2686dbfc4a 100644
--- a/src/features/Conversation/store/slices/message/action/crud.ts
+++ b/src/features/Conversation/store/slices/message/action/crud.ts
@@ -298,8 +298,8 @@ export const messageCRUDSlice: StateCreator<
let ids = [message.id];
- // Handle assistantGroup messages: delete all child blocks and tool results
- if (message.role === 'assistantGroup' && message.children) {
+ // Handle assistantGroup and supervisor messages: delete all child blocks and tool results
+ if ((message.role === 'assistantGroup' || message.role === 'supervisor') && message.children) {
const childIds = message.children.map((child: AssistantContentBlock) => child.id);
ids = ids.concat(childIds);
diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.ts
index 7f737376c3a..4eb61abb823 100644
--- a/src/locales/default/plugin.ts
+++ b/src/locales/default/plugin.ts
@@ -61,18 +61,16 @@ export default {
'builtins.lobe-group-agent-builder.inspector.title': 'Title',
'builtins.lobe-group-agent-builder.title': 'Group Builder Expert',
'builtins.lobe-group-management.apiName.broadcast': 'All speak',
- 'builtins.lobe-group-management.apiName.createAgent': 'Add group member',
'builtins.lobe-group-management.apiName.createWorkflow': 'Plan workflow',
- 'builtins.lobe-group-management.apiName.executeTask': 'Execute task',
+ 'builtins.lobe-group-management.apiName.executeAgentTask': 'Execute agent task',
+ 'builtins.lobe-group-management.apiName.executeAgentTasks': 'Execute parallel agent tasks',
'builtins.lobe-group-management.apiName.getAgentInfo': 'Get member info',
'builtins.lobe-group-management.apiName.interrupt': 'Interrupt task',
- 'builtins.lobe-group-management.apiName.inviteAgent': 'Invite member',
- 'builtins.lobe-group-management.apiName.removeAgent': 'Remove member',
- 'builtins.lobe-group-management.apiName.searchAgent': 'Find relevant experts',
'builtins.lobe-group-management.apiName.speak': 'Designated member speaks',
'builtins.lobe-group-management.apiName.summarize': 'Summarize conversation',
'builtins.lobe-group-management.apiName.vote': 'Start vote',
'builtins.lobe-group-management.inspector.broadcast.title': 'Following Agents speak:',
+ 'builtins.lobe-group-management.inspector.executeAgentTasks.title': 'Assigning tasks to:',
'builtins.lobe-group-management.inspector.speak.title': 'Designated Agent speaks:',
'builtins.lobe-group-management.title': 'Group Coordinator',
'builtins.lobe-gtd.apiName.clearTodos': 'Clear todos',
diff --git a/src/locales/default/tool.ts b/src/locales/default/tool.ts
index 65fd01db328..3afefb6deee 100644
--- a/src/locales/default/tool.ts
+++ b/src/locales/default/tool.ts
@@ -16,6 +16,9 @@ export default {
'agentGroupManagement.executeTask.thread': 'Thread ID',
'agentGroupManagement.executeTask.timeout': 'Execution Timed Out',
'agentGroupManagement.executeTask.tokens': 'Token Usage',
+ 'agentGroupManagement.executeTasks.intervention.instructionPlaceholder':
+ 'Detailed instruction for the agent to perform this task...',
+ 'agentGroupManagement.executeTasks.intervention.titlePlaceholder': 'Task title...',
'codeInterpreter-legacy.error': 'Execution Error',
'codeInterpreter-legacy.executing': 'Executing...',
'codeInterpreter-legacy.files': 'Files:',
diff --git a/src/services/chat/mecha/agentConfigResolver.test.ts b/src/services/chat/mecha/agentConfigResolver.test.ts
index 0cd95bafeee..0081305b3c8 100644
--- a/src/services/chat/mecha/agentConfigResolver.test.ts
+++ b/src/services/chat/mecha/agentConfigResolver.test.ts
@@ -1,4 +1,5 @@
import * as builtinAgents from '@lobechat/builtin-agents';
+import { GroupManagementIdentifier } from '@lobechat/builtin-tool-group-management';
import { GTDIdentifier } from '@lobechat/builtin-tool-gtd';
import { NotebookIdentifier } from '@lobechat/builtin-tool-notebook';
import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
@@ -6,6 +7,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import * as agentStore from '@/store/agent';
import * as agentSelectors from '@/store/agent/selectors';
+import * as agentGroupStore from '@/store/agentGroup';
+import * as agentGroupSelectors from '@/store/agentGroup/selectors';
import { resolveAgentConfig } from './agentConfigResolver';
@@ -623,4 +626,161 @@ describe('resolveAgentConfig', () => {
expect(result.chatConfig.enableHistoryCount).toBe(false);
});
});
+
+ describe('supervisor agent (slug from agentGroup store)', () => {
+ const mockGroupStoreState = { groupMap: {} };
+ const mockGroupWithSupervisor = {
+ agents: [
+ { id: 'supervisor-agent-id', isSupervisor: true, title: 'Supervisor' },
+ { id: 'member-agent-1', isSupervisor: false, title: 'Agent 1' },
+ { id: 'member-agent-2', isSupervisor: false, title: 'Agent 2' },
+ ],
+ config: { systemPrompt: 'Custom group system prompt' },
+ id: 'group-123',
+ supervisorAgentId: 'supervisor-agent-id',
+ title: 'Test Group',
+ };
+
+ beforeEach(() => {
+ // No slug in agent store - simulates supervisor agent not being in agentMap with slug
+ vi.spyOn(agentSelectors.agentSelectors, 'getAgentSlugById').mockReturnValue(() => undefined);
+
+ // Mock agentGroup store
+ vi.spyOn(agentGroupStore, 'getChatGroupStoreState').mockReturnValue(
+ mockGroupStoreState as any,
+ );
+ });
+
+ it('should detect supervisor agent from agentGroup store when not found in agent store', () => {
+ // Mock: supervisor agent is found in agentGroup store
+ vi.spyOn(
+ agentGroupSelectors.agentGroupByIdSelectors,
+ 'groupBySupervisorAgentId',
+ ).mockReturnValue(() => mockGroupWithSupervisor as any);
+
+ // Mock: getGroupBySupervisorAgentId for building groupSupervisorContext
+ vi.spyOn(
+ agentGroupSelectors.agentGroupSelectors,
+ 'getGroupBySupervisorAgentId',
+ ).mockReturnValue(() => mockGroupWithSupervisor as any);
+
+ // Mock: getGroupMembers returns non-supervisor agents
+ vi.spyOn(agentGroupSelectors.agentGroupSelectors, 'getGroupMembers').mockReturnValue(
+ () =>
+ [
+ { id: 'member-agent-1', title: 'Agent 1' },
+ { id: 'member-agent-2', title: 'Agent 2' },
+ ] as any,
+ );
+
+ // Mock: getAgentRuntimeConfig for supervisor agent
+ vi.spyOn(builtinAgents, 'getAgentRuntimeConfig').mockReturnValue({
+ chatConfig: { enableHistoryCount: false },
+ plugins: [GroupManagementIdentifier, GTDIdentifier],
+ systemRole: 'You are a group supervisor...',
+ });
+
+ const result = resolveAgentConfig({ agentId: 'supervisor-agent-id' });
+
+ expect(result.isBuiltinAgent).toBe(true);
+ expect(result.slug).toBe('group-supervisor');
+ expect(result.plugins).toContain(GroupManagementIdentifier);
+ expect(result.plugins).toContain(GTDIdentifier);
+ });
+
+ it('should pass groupSupervisorContext to getAgentRuntimeConfig', () => {
+ // Mock: supervisor agent is found in agentGroup store
+ vi.spyOn(
+ agentGroupSelectors.agentGroupByIdSelectors,
+ 'groupBySupervisorAgentId',
+ ).mockReturnValue(() => mockGroupWithSupervisor as any);
+
+ // Mock: getGroupBySupervisorAgentId for building groupSupervisorContext
+ vi.spyOn(
+ agentGroupSelectors.agentGroupSelectors,
+ 'getGroupBySupervisorAgentId',
+ ).mockReturnValue(() => mockGroupWithSupervisor as any);
+
+ // Mock: getGroupMembers returns non-supervisor agents
+ vi.spyOn(agentGroupSelectors.agentGroupSelectors, 'getGroupMembers').mockReturnValue(
+ () =>
+ [
+ { id: 'member-agent-1', title: 'Agent 1' },
+ { id: 'member-agent-2', title: 'Agent 2' },
+ ] as any,
+ );
+
+ const getAgentRuntimeConfigSpy = vi
+ .spyOn(builtinAgents, 'getAgentRuntimeConfig')
+ .mockReturnValue({
+ chatConfig: { enableHistoryCount: false },
+ plugins: [GroupManagementIdentifier],
+ systemRole: 'You are a group supervisor...',
+ });
+
+ resolveAgentConfig({ agentId: 'supervisor-agent-id' });
+
+ expect(getAgentRuntimeConfigSpy).toHaveBeenCalledWith(
+ 'group-supervisor',
+ expect.objectContaining({
+ groupSupervisorContext: {
+ availableAgents: [
+ { id: 'member-agent-1', title: 'Agent 1' },
+ { id: 'member-agent-2', title: 'Agent 2' },
+ ],
+ groupId: 'group-123',
+ groupTitle: 'Test Group',
+ systemPrompt: 'Custom group system prompt',
+ },
+ }),
+ );
+ });
+
+ it('should treat as regular agent when supervisor is not found in agentGroup store', () => {
+ // Mock: supervisor agent is NOT found in agentGroup store
+ vi.spyOn(
+ agentGroupSelectors.agentGroupByIdSelectors,
+ 'groupBySupervisorAgentId',
+ ).mockReturnValue(() => undefined);
+
+ const result = resolveAgentConfig({ agentId: 'some-other-agent' });
+
+ expect(result.isBuiltinAgent).toBe(false);
+ expect(result.slug).toBeUndefined();
+ expect(result.plugins).toEqual(['plugin-a', 'plugin-b']); // Falls back to agent config plugins
+ });
+
+ it('should work correctly when regenerating supervisor message', () => {
+ // This simulates the regenerate flow where agentId is the supervisor agent ID
+ vi.spyOn(
+ agentGroupSelectors.agentGroupByIdSelectors,
+ 'groupBySupervisorAgentId',
+ ).mockReturnValue(() => mockGroupWithSupervisor as any);
+
+ vi.spyOn(
+ agentGroupSelectors.agentGroupSelectors,
+ 'getGroupBySupervisorAgentId',
+ ).mockReturnValue(() => mockGroupWithSupervisor as any);
+
+ vi.spyOn(agentGroupSelectors.agentGroupSelectors, 'getGroupMembers').mockReturnValue(
+ () => [{ id: 'member-agent-1', title: 'Agent 1' }] as any,
+ );
+
+ vi.spyOn(builtinAgents, 'getAgentRuntimeConfig').mockReturnValue({
+ chatConfig: { enableHistoryCount: false },
+ plugins: [GroupManagementIdentifier, GTDIdentifier],
+ systemRole: 'Supervisor system role',
+ });
+
+ const result = resolveAgentConfig({ agentId: 'supervisor-agent-id' });
+
+ // Should correctly identify as builtin supervisor agent
+ expect(result.isBuiltinAgent).toBe(true);
+ expect(result.slug).toBe('group-supervisor');
+ // Should have group management tool injected
+ expect(result.plugins).toContain(GroupManagementIdentifier);
+ // Should have proper system role
+ expect(result.agentConfig.systemRole).toBe('Supervisor system role');
+ });
+ });
});
diff --git a/src/services/chat/mecha/agentConfigResolver.ts b/src/services/chat/mecha/agentConfigResolver.ts
index b92fd983a64..f3addfd6c2d 100644
--- a/src/services/chat/mecha/agentConfigResolver.ts
+++ b/src/services/chat/mecha/agentConfigResolver.ts
@@ -10,7 +10,7 @@ import { produce } from 'immer';
import { getAgentStoreState } from '@/store/agent';
import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { getChatGroupStoreState } from '@/store/agentGroup';
-import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+import { agentGroupByIdSelectors, agentGroupSelectors } from '@/store/agentGroup/selectors';
/**
* Applies params adjustments based on chatConfig settings.
@@ -49,7 +49,7 @@ export interface AgentConfigResolverContext {
agentId: string;
// Builtin agent specific context
-/** Document content for page-agent */
+ /** Document content for page-agent */
documentContent?: string;
/** Current model being used (for template variables) */
@@ -109,7 +109,19 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge
const basePlugins = agentConfig.plugins ?? [];
// Check if this is a builtin agent
- const slug = agentSelectors.getAgentSlugById(agentId)(agentStoreState);
+ // First check agent store, then check if this is a supervisor agent in agentGroup store
+ let slug = agentSelectors.getAgentSlugById(agentId)(agentStoreState);
+
+ // If not found in agent store, check if this is a supervisor agent in any group
+ // Supervisor agents have their slug stored in agentGroup store, not agent store
+ if (!slug) {
+ const groupStoreState = getChatGroupStoreState();
+ const group = agentGroupByIdSelectors.groupBySupervisorAgentId(agentId)(groupStoreState);
+ if (group) {
+ // This is a supervisor agent - use the builtin slug
+ slug = BUILTIN_AGENT_SLUGS.groupSupervisor;
+ }
+ }
if (!slug) {
// Regular agent - use provided plugins if available, fallback to agent's plugins
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index 05ed8d1534f..c65d8a0d1c0 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -143,7 +143,8 @@ export const contextEngineering = async ({
currentAgentRole,
groupTitle: groupDetail.title || undefined,
members,
- systemPrompt: groupDetail.config?.systemPrompt || undefined,
+ // Use group.content as the group description (shared prompt/content)
+ systemPrompt: groupDetail.content || undefined,
};
log('agentGroup built: %o', agentGroup);
}
diff --git a/src/store/chat/agents/GroupOrchestration/createGroupOrchestrationExecutors.ts b/src/store/chat/agents/GroupOrchestration/createGroupOrchestrationExecutors.ts
index 9faee46ffe6..a1dfd54ef9d 100644
--- a/src/store/chat/agents/GroupOrchestration/createGroupOrchestrationExecutors.ts
+++ b/src/store/chat/agents/GroupOrchestration/createGroupOrchestrationExecutors.ts
@@ -190,12 +190,13 @@ export const createGroupOrchestrationExecutors = (
// If instruction is provided, inject it as a virtual User Message
// This virtual message is not persisted to database, only used for model context
+ // Mark with <speaker> tag so the agent knows this instruction is from the Supervisor
const now = Date.now();
const messagesWithInstruction: UIChatMessage[] = agentInstruction
? [
...messages,
{
- content: agentInstruction,
+ content: `<speaker name="Supervisor" />\n${agentInstruction}`,
createdAt: now,
id: `virtual_speak_instruction_${now}`,
role: 'user',
@@ -266,12 +267,13 @@ export const createGroupOrchestrationExecutors = (
// If instruction is provided, inject it as a virtual User Message
// This virtual message is not persisted to database, only used for model context
+ // Mark with <speaker> tag so the agent knows this instruction is from the Supervisor
const now = Date.now();
const messagesWithInstruction: UIChatMessage[] = agentInstruction
? [
...messages,
{
- content: agentInstruction,
+ content: `<speaker name="Supervisor" />\n${agentInstruction}`,
createdAt: now,
id: `virtual_broadcast_instruction_${now}`,
role: 'user',
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index b01e67c416d..42f4cf876b7 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -197,6 +197,8 @@ export const conversationLifecycle: StateCreator<
// if there is topicId,then add topicId to message
topicId: operationContext.topicId ?? undefined,
threadId: operationContext.threadId ?? undefined,
+ // Pass isSupervisor metadata for group orchestration (consistent with server)
+ metadata: operationContext.isSupervisor ? { isSupervisor: true } : undefined,
},
{ operationId, tempMessageId: tempAssistantId },
);
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index 1038d6ca5e5..d15734c488c 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -592,7 +592,7 @@ export const streamingExecutor: StateCreator<
// resolveAgentConfig handles:
// - Builtin agent runtime config merging
// - max_tokens/reasoning_effort based on chatConfig settings
- const { agentConfig: agentConfigData, chatConfig } = resolveAgentConfig({
+ const { agentConfig: agentConfigData } = resolveAgentConfig({
agentId: effectiveAgentId || '',
scope: context.scope, // Pass scope from context parameter (available at line 883)
});
@@ -863,22 +863,5 @@ export const streamingExecutor: StateCreator<
console.error('Desktop notification error:', error);
}
}
-
- // Summary history if context messages is larger than historyCount
- const historyCount = chatConfig.historyCount ?? 0;
-
- if (
- chatConfig.enableHistoryCount &&
- chatConfig.enableCompressHistory &&
- messages.length > historyCount
- ) {
- // after generation: [u1,a1,u2,a2,u3,a3]
- // but the `messages` is still: [u1,a1,u2,a2,u3]
- // So if historyCount=2, we need to summary [u1,a1,u2,a2]
- // because user find UI is [u1,a1,u2,a2 | u3,a3]
- const historyMessages = messages.slice(0, -historyCount + 1);
-
- await get().internal_summaryHistory(historyMessages);
- }
},
});
diff --git a/src/store/chat/slices/message/selectors/displayMessage.test.ts b/src/store/chat/slices/message/selectors/displayMessage.test.ts
index f163caafa26..39b3de7bf9f 100644
--- a/src/store/chat/slices/message/selectors/displayMessage.test.ts
+++ b/src/store/chat/slices/message/selectors/displayMessage.test.ts
@@ -323,6 +323,30 @@ describe('displayMessageSelectors', () => {
const result = displayMessageSelectors.currentDisplayChatKey(state as ChatStore);
expect(result).toBe(messageMapKey({ agentId: '', topicId: undefined }));
});
+
+ it('should generate correct key with activeGroupId for group conversations', () => {
+ const state: Partial<ChatStore> = {
+ activeAgentId: 'testId',
+ activeGroupId: 'groupId',
+ activeTopicId: undefined,
+ };
+ const result = displayMessageSelectors.currentDisplayChatKey(state as ChatStore);
+ expect(result).toBe(
+ messageMapKey({ agentId: 'testId', groupId: 'groupId', topicId: undefined }),
+ );
+ });
+
+ it('should generate correct key with activeGroupId and activeTopicId', () => {
+ const state: Partial<ChatStore> = {
+ activeAgentId: 'testId',
+ activeGroupId: 'groupId',
+ activeTopicId: 'topicId',
+ };
+ const result = displayMessageSelectors.currentDisplayChatKey(state as ChatStore);
+ expect(result).toBe(
+ messageMapKey({ agentId: 'testId', groupId: 'groupId', topicId: 'topicId' }),
+ );
+ });
});
describe('activeDisplayMessages with group chat messages', () => {
diff --git a/src/store/chat/slices/message/selectors/displayMessage.ts b/src/store/chat/slices/message/selectors/displayMessage.ts
index 41a5dac6745..9fadce86875 100644
--- a/src/store/chat/slices/message/selectors/displayMessage.ts
+++ b/src/store/chat/slices/message/selectors/displayMessage.ts
@@ -24,9 +24,14 @@ import { messageMapKey } from '../../../utils/messageMapKey';
/**
* Get the current chat key for accessing messagesMap
+ * For group conversations, uses groupId to generate the correct key
*/
export const currentDisplayChatKey = (s: ChatStoreState) =>
- messageMapKey({ agentId: s.activeAgentId, topicId: s.activeTopicId });
+ messageMapKey({
+ agentId: s.activeAgentId,
+ groupId: s.activeGroupId,
+ topicId: s.activeTopicId,
+ });
/**
* Get display messages by key
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.ts
index 2a7b037aa7a..5cd9a4ee4ac 100644
--- a/src/store/chat/slices/topic/action.test.ts
+++ b/src/store/chat/slices/topic/action.test.ts
@@ -462,7 +462,7 @@ describe('topic action', () => {
});
});
- it('should NOT clear new key data when switching with undefined (backward compatibility)', async () => {
+ it('should clear new key data when switching with undefined (same as null)', async () => {
const { result } = renderHook(() => useChatStore());
const activeAgentId = 'test-agent-id';
@@ -475,13 +475,19 @@ describe('topic action', () => {
const replaceMessagesSpy = vi.spyOn(result.current, 'replaceMessages');
- // Switch with undefined (should NOT clear because id !== null)
+ // Switch with undefined (should clear because id == null matches both null and undefined)
await act(async () => {
await result.current.switchTopic(undefined, { skipRefreshMessage: true });
});
- // replaceMessages should NOT be called when switching with undefined
- expect(replaceMessagesSpy).not.toHaveBeenCalled();
+ // replaceMessages SHOULD be called when switching with undefined
+ expect(replaceMessagesSpy).toHaveBeenCalledWith([], {
+ context: expect.objectContaining({
+ agentId: activeAgentId,
+ topicId: null,
+ }),
+ action: expect.any(String),
+ });
});
it('should not clear new key data when switching to an existing topic', async () => {
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index f3ed80ac63c..8a155135107 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -532,10 +532,11 @@ export const chatTopic: StateCreator<
const { activeAgentId, activeGroupId } = get();
// Clear the _new key data in the following cases:
- // 1. When id is explicitly null (switching to empty topic state)
+ // 1. When id is null or undefined (switching to empty topic state)
// 2. When clearNewKey option is explicitly true
// This prevents stale data from previous conversations showing up
- const shouldClearNewKey = id === null || opts.clearNewKey;
+ // Note: Use == null to match both null and undefined
+ const shouldClearNewKey = !id || opts.clearNewKey;
if (shouldClearNewKey && activeAgentId) {
// Determine scope: use explicit scope from options, or infer from activeGroupId