Skip to content

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

πŸ› fix(group): inject real member roster into durable group supervisor context (#16352)

Arvin Xu85e97a094c08
diff --git a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
index 163312c0592..cac291eefdc 100644
--- a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
+++ b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts
@@ -156,38 +156,6 @@ const LLM_RETRY_MAX_DELAY_MS = 30_000;
*/
const EMPTY_COMPLETION_MAX_RETRIES = 2;
-const buildBotAgentGroupContext = (params: {
- agentConfig?: any;
- agentId?: string;
- botContext?: unknown;
-}): AgentGroupConfig | undefined => {
- if (!params.botContext || !params.agentId) return undefined;
-
- const title = params.agentConfig?.title;
- const description = params.agentConfig?.description;
- const name = typeof title === 'string' && title.trim() ? title.trim() : 'Current Agent';
-
- return {
- agentMap: {
- [params.agentId]: {
- name,
- role: 'participant',
- },
- },
- currentAgentId: params.agentId,
- currentAgentName: name,
- currentAgentRole: 'participant',
- members: [
- {
- id: params.agentId,
- name,
- role: 'participant',
- },
- ],
- systemPrompt: typeof description === 'string' ? description : undefined,
- };
-};
-
/**
* Output-token count at or below this β€” combined with no content, reasoning,
* tool calls, or images β€” marks a turn as an empty completion.
@@ -1384,11 +1352,11 @@ export const createRuntimeExecutors = (
const contextEngineInput = {
agentDocuments,
...(agentBuilderContext && { agentBuilderContext }),
- agentGroup: buildBotAgentGroupContext({
- agentConfig,
- agentId: state.metadata?.agentId,
- botContext: state.metadata?.botContext ?? ctx.botContext,
- }),
+ // The group/bot member roster is resolved once at op creation
+ // (AiAgentService.execAgent β†’ buildGroupAgentContext) and snapshotted
+ // into op metadata, mirroring agentConfig/botContext β€” no per-step DB
+ // lookup here.
+ agentGroup: state.metadata?.agentGroup as AgentGroupConfig | undefined,
additionalVariables: {
...state.metadata?.deviceSystemInfo,
...lobehubSkillVariables,
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 4c0fc96a7b8..f542bce9f45 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -395,6 +395,7 @@ export class AgentRuntimeService {
operationId,
initialContext,
agentConfig,
+ agentGroup,
modelRuntimeConfig,
userId,
autoStart = true,
@@ -486,6 +487,7 @@ export class AgentRuntimeService {
metadata: {
activeDeviceId,
agentConfig,
+ agentGroup,
botContext,
botPlatformContext,
deviceAccessPolicy,
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index 7098646bad5..f740588efb3 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -1,5 +1,6 @@
import { type AgentRuntimeContext, type AgentState } from '@lobechat/agent-runtime';
import type {
+ AgentGroupConfig,
BotPlatformContext,
LobeToolManifest,
OperationSkillSet,
@@ -308,6 +309,13 @@ export interface ExecGroupMemberResult {
export interface OperationCreationParams {
activeDeviceId?: string;
agentConfig?: any;
+ /**
+ * Multi-agent group (or bot-conversation fallback) context, resolved once at
+ * op creation and forwarded into `state.metadata.agentGroup`. The per-step
+ * context engine reads it back to inject the participant roster (with real
+ * `agt_*` IDs) β€” no per-step DB lookup, mirroring `botContext`.
+ */
+ agentGroup?: AgentGroupConfig;
appContext: {
agentId?: string;
/**
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 014598b3f39..ec019fad77a 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -16,6 +16,7 @@ import { TaskIdentifier } from '@lobechat/builtin-tool-task';
import { builtinTools, manualModeExcludeToolIds } from '@lobechat/builtin-tools';
import { LOADING_FLAT } from '@lobechat/const';
import type {
+ AgentGroupConfig,
AgentManagementContext,
BotPlatformContext,
LobeToolManifest,
@@ -180,6 +181,72 @@ const isVisualUnderstandingConfigured = () => {
}
};
+/**
+ * Build the multi-agent group context from a group's member roster, mirroring
+ * the client `contextEngineering.ts` `agentGroup` build. Carries every member's
+ * real `agt_*` ID so the supervisor dispatches members by ID instead of role
+ * name (role names don't resolve β†’ "Agent member(s) failed to start."). Resolves
+ * the responding agent's own role/name so GroupContextInjector marks it with
+ * `you="true"` and the orchestration filter activates for participants.
+ */
+const buildGroupAgentContext = (
+ currentAgentId: string,
+ group: { content?: string | null; title?: string | null } | undefined,
+ roster: Array<{ agentId: string; role: string | null; title: string | null }>,
+): AgentGroupConfig | undefined => {
+ if (roster.length === 0) return undefined;
+
+ const agentMap: AgentGroupConfig['agentMap'] = {};
+ const members: NonNullable<AgentGroupConfig['members']> = [];
+ let currentAgentName: string | undefined;
+ let currentAgentRole: 'supervisor' | 'participant' | undefined;
+
+ for (const member of roster) {
+ const role = member.role === 'supervisor' ? 'supervisor' : 'participant';
+ const name = member.title?.trim() || 'Untitled Agent';
+ agentMap[member.agentId] = { name, role };
+ members.push({ id: member.agentId, name, role });
+
+ if (member.agentId === currentAgentId) {
+ currentAgentName = name;
+ currentAgentRole = role;
+ }
+ }
+
+ return {
+ agentMap,
+ currentAgentId,
+ currentAgentName,
+ currentAgentRole,
+ groupTitle: group?.title || undefined,
+ members,
+ systemPrompt: group?.content || undefined,
+ };
+};
+
+/**
+ * Bot-conversation fallback: a single bot agent has no real group, so build a
+ * degenerate one-member context purely to give it its `<group_context>`
+ * identity block. Only used when there is no `groupId`.
+ */
+const buildBotConversationGroupContext = (
+ currentAgentId: string,
+ agentConfig: { description?: unknown; title?: unknown } | undefined,
+): AgentGroupConfig => {
+ const title = agentConfig?.title;
+ const description = agentConfig?.description;
+ const name = typeof title === 'string' && title.trim() ? title.trim() : 'Current Agent';
+
+ return {
+ agentMap: { [currentAgentId]: { name, role: 'participant' } },
+ currentAgentId,
+ currentAgentName: name,
+ currentAgentRole: 'participant',
+ members: [{ id: currentAgentId, name, role: 'participant' }],
+ systemPrompt: typeof description === 'string' ? description : undefined,
+ };
+};
+
/**
* Internal params for execAgent with step lifecycle callbacks
* This extends the public ExecAgentParams with server-side only options
@@ -1847,6 +1914,9 @@ export class AiAgentService {
const agentMemoryEnabled = agentConfig.chatConfig?.memory?.enabled;
let globalMemoryEnabled = agentMemoryEnabled ?? false;
let userTimezone: string | undefined;
+ // Resolved once below (alongside the group-tool authorization fetch) and
+ // forwarded into op metadata for the per-step context engine.
+ let operationAgentGroup: AgentGroupConfig | undefined;
try {
const userModel = new UserModel(this.db, this.userId);
const settings = await userModel.getUserSettings();
@@ -2200,29 +2270,38 @@ export class AiAgentService {
activeDeviceId ?? 'none',
);
- // `appContext.orchestrationRole` is client-supplied (the execAgent /
- // execAgents schema accepts it, and execGroupAgent stamps it for whatever
- // agentId the caller passed), so it must NOT alone authorize the
- // group-orchestration toolset β€” otherwise any run marked
- // `{ orchestrationRole: 'supervisor', groupId }` could dispatch group
- // members. Verify against the persisted, ownership-scoped membership that
- // the executing agent really is this group's supervisor.
+ // Resolve the operation's group context ONCE here and snapshot it into op
+ // metadata below β€” the per-step context engine reads it back without a DB
+ // lookup, mirroring agentConfig/botContext. The same roster fetch also
+ // authorizes the group-orchestration toolset.
let isGroupSupervisor = false;
- if (appContext?.orchestrationRole === 'supervisor' && appContext?.groupId) {
- const groupAgents = await new ChatGroupModel(
- this.db,
- this.userId,
- this.workspaceId,
- ).getGroupAgents(appContext.groupId);
- isGroupSupervisor = groupAgents.some(
- (member) => member.agentId === resolvedAgentId && member.role === 'supervisor',
- );
- if (!isGroupSupervisor)
- log(
- 'execAgent: orchestrationRole=supervisor but agent %s is not the supervisor of group %s β€” denying group tools',
- resolvedAgentId,
- appContext.groupId,
+ if (appContext?.groupId) {
+ const chatGroupModel = new ChatGroupModel(this.db, this.userId, this.workspaceId);
+ const [group, roster] = await Promise.all([
+ chatGroupModel.findById(appContext.groupId),
+ chatGroupModel.getGroupAgentsWithMeta(appContext.groupId),
+ ]);
+
+ // `appContext.orchestrationRole` is client-supplied (execGroupAgent stamps
+ // it for whatever agentId the caller passed), so it must NOT alone
+ // authorize the group-orchestration toolset β€” otherwise any run marked
+ // `{ orchestrationRole: 'supervisor', groupId }` could dispatch members.
+ // Verify against the persisted, ownership-scoped membership instead.
+ if (appContext.orchestrationRole === 'supervisor') {
+ isGroupSupervisor = roster.some(
+ (member) => member.agentId === resolvedAgentId && member.role === 'supervisor',
);
+ if (!isGroupSupervisor)
+ log(
+ 'execAgent: orchestrationRole=supervisor but agent %s is not the supervisor of group %s β€” denying group tools',
+ resolvedAgentId,
+ appContext.groupId,
+ );
+ }
+
+ operationAgentGroup = buildGroupAgentContext(resolvedAgentId, group, roster);
+ } else if (botContext) {
+ operationAgentGroup = buildBotConversationGroupContext(resolvedAgentId, agentConfig);
}
const toolsEngine = createServerAgentToolsEngine(toolsContext, {
@@ -3035,6 +3114,7 @@ export class AiAgentService {
const result = await this.agentRuntimeService.createOperation({
activeDeviceId,
agentConfig,
+ agentGroup: operationAgentGroup,
deviceSystemInfo: Object.keys(deviceSystemInfo).length > 0 ? deviceSystemInfo : undefined,
executionPlan,
userTimezone,
diff --git a/packages/database/src/models/chatGroup.ts b/packages/database/src/models/chatGroup.ts
index e472576d87e..4730852cf6c 100644
--- a/packages/database/src/models/chatGroup.ts
+++ b/packages/database/src/models/chatGroup.ts
@@ -325,6 +325,46 @@ export class ChatGroupModel {
});
}
+ /**
+ * Read-only roster of a group's **enabled** agents joined with their agent meta
+ * (title/description) and membership role, ordered by member order.
+ *
+ * Used to inject the group member list β€” with the real `agt_*` IDs β€” into the
+ * supervisor/member runtime context so the orchestration model dispatches
+ * members by their actual IDs instead of hallucinating role names (which then
+ * fail to resolve to an agent, surfacing as "Agent member(s) failed to start").
+ *
+ * Disabled members are excluded (matching `getEnabledGroupAgents`): advertising
+ * them in `<group_participants>` would let the supervisor invoke a disabled
+ * agent, since the group-management runtime accepts whatever id it dispatches.
+ */
+ async getGroupAgentsWithMeta(groupId: string): Promise<
+ Array<{
+ agentId: string;
+ description: string | null;
+ role: string | null;
+ title: string | null;
+ }>
+ > {
+ return this.db
+ .select({
+ agentId: chatGroupsAgents.agentId,
+ description: agents.description,
+ role: chatGroupsAgents.role,
+ title: agents.title,
+ })
+ .from(chatGroupsAgents)
+ .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
+ .where(
+ and(
+ eq(chatGroupsAgents.chatGroupId, groupId),
+ eq(chatGroupsAgents.enabled, true),
+ this.agentsOwnership(),
+ ),
+ )
+ .orderBy(chatGroupsAgents.order);
+ }
+
async getEnabledGroupAgents(groupId: string): Promise<ChatGroupAgentItem[]> {
return this.db.query.chatGroupsAgents.findMany({
orderBy: [chatGroupsAgents.order],