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(ai-agent): keep turn-selected and @agent-delegation tools enabled across follow-up turns (#23735)

AmAzing-8c44304c8a14
diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
index 4f39269524e..6972a87c76d 100644
--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts
+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
@@ -441,6 +441,14 @@ export const execAgentTurn = async (
// other forever; past the bound a person has to step in.
assertAgentRelayHop(agentSender);
+ // When the user @-mentions agents (multi-mention, non-group), enable the
+ // agent-management tool for this run so the supervisor can `callAgent` to
+ // delegate. Mirrors the client runtime, which injects a callAgent manifest.
+ // Single-mention takes a client-only deterministic-router path and never
+ // reaches here. The delegation *context* (which agents were mentioned) is
+ // injected separately via `initialContext.mentionedAgents` below.
+ const hasMentionedAgents = !appContext?.groupId && !!mentionedAgents?.length;
+
// Stage 3 + shared turn setup β€” topic creation/reuse (with the pinned
// model), device-access policy, hetero detection, attachment ingestion, and
// the persisted user/assistant rows (see `pipeline/turnSetup`).
@@ -472,6 +480,7 @@ export const execAgentTurn = async (
webhookThread,
openedByTopicId,
files,
+ hasMentionedAgents,
modelOverride,
operationTaskId,
parentMessageId,
@@ -490,6 +499,7 @@ export const execAgentTurn = async (
resume,
runFromHistory,
selectedSkillIds,
+ selectedToolIds,
shareGate,
steer,
throwIfExecutionAborted,
@@ -683,14 +693,6 @@ export const execAgentTurn = async (
},
);
- // When the user @-mentions agents (multi-mention, non-group), enable the
- // agent-management tool for this run so the supervisor can `callAgent` to
- // delegate. Mirrors the client runtime, which injects a callAgent manifest.
- // Single-mention takes a client-only deterministic-router path and never
- // reaches here. The delegation *context* (which agents were mentioned) is
- // injected separately via `initialContext.mentionedAgents` below.
- const hasMentionedAgents = !appContext?.groupId && !!mentionedAgents?.length;
-
// 15. Generate operation ID: op_{timestamp}_{agentId}_{topicId}_{random}
const operationId =
params.reservedOperationId ??
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts
index 70f805a3457..ee30bc84548 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts
@@ -427,6 +427,45 @@ describe('discoverTools β€” connector discovery', () => {
expect(result.agentPlugins).toContain('community-mcp');
});
+ it('keeps tools and @agent delegation from earlier turns in the topic enabled on follow-up turns', async () => {
+ const result = await run({
+ ...sources,
+ input: {
+ loadHistoryMessages: vi.fn().mockResolvedValue([
+ {
+ content: '<mention name="Writer" id="agt_writer" /> Hello',
+ metadata: { selectedToolIds: ['community-mcp', 'lobe-agent-management'] },
+ role: 'user',
+ },
+ { content: 'How can I help?', role: 'assistant' },
+ ]),
+ },
+ }).promise;
+
+ expect(engineInstalledIds()).toEqual(['community-mcp']);
+ expect(result.agentPlugins).toEqual(
+ expect.arrayContaining(['community-mcp', 'lobe-agent-management']),
+ );
+ });
+
+ it('does not leak supervisor @-mentioned connectors from shared group history into an in-group member turn', async () => {
+ const result = await run({
+ ...sources,
+ appContext: { groupId: 'group-1', orchestrationRole: 'member' },
+ input: {
+ loadHistoryMessages: vi.fn().mockResolvedValue([
+ {
+ metadata: { selectedToolIds: ['community-mcp'] },
+ role: 'user',
+ },
+ { content: 'Delegating to member', role: 'assistant' },
+ ]),
+ },
+ }).promise;
+
+ expect(result.agentPlugins).not.toContain('community-mcp');
+ });
+
it('leaves an exact toolset untouched by the agent switches', async () => {
const result = await run({
...sources,
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
index 0d5d9f72412..095b180158e 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
@@ -73,7 +73,11 @@ import {
import { resolveDevicePlan } from './devicePlan';
import { resolveModelContext, startModelMetadataRead } from './modelFacts';
import { readCredentialFacts, startToolReads } from './reads';
-import { resolveOperationGroup, resolveTurnScopedPluginIds } from './turnContext';
+import {
+ collectSelectedToolIds,
+ resolveOperationGroup,
+ resolveTurnScopedPluginIds,
+} from './turnContext';
import type { ToolDiscoveryDeps, ToolDiscoveryInput, ToolDiscoveryResult } from './types';
export type { ToolDiscoveryDeps, ToolDiscoveryInput, ToolDiscoveryResult } from './types';
@@ -187,11 +191,29 @@ export const discoverTools = async (
let composioManifests: LobeToolManifest[] = [];
let connectorManifests: ReturnType<typeof buildConnectorManifests> = [];
- // `selectedToolIds` are the user's @-mention picks for this turn; merged in
+ // `selectedToolIds` are the user's @-mention picks for this turn plus any
+ // selections persisted on earlier user turns in the topic; merged in
// (deduped) alongside the agent's configured plugins and any internal
// `additionalPluginIds` so a mentioned-but-not-enabled tool (e.g. a custom MCP
- // connector) is both queried for manifests and enabled by the tools engine.
+ // connector or `lobe-agent-management` from an earlier @agent mention) stays
+ // enabled across follow-up turns in the same conversation.
+ let historyMessagesCache: any[] | undefined;
+ const readHistoryMessages = async () => {
+ historyMessagesCache ??= await loadHistoryMessages();
+ return historyMessagesCache;
+ };
const isGoalTurn = isGoalPrompt(prompt);
+ const isInGroupMember = appContext?.orchestrationRole === 'member' && !appContext?.threadId;
+ const historyMessages =
+ disableTools || exclusivePluginIds || isGoalTurn || isInGroupMember
+ ? []
+ : await readHistoryMessages();
+ const effectiveSelectedToolIds = collectSelectedToolIds(historyMessages, selectedToolIds, {
+ hasMentionedAgents,
+ isGroupConversation: !!appContext?.groupId,
+ isInGroupMember,
+ resolvedAgentId,
+ });
const toolMode = resolveToolMode(agentConfig.chatConfig);
const configuredPluginIds =
toolMode === 'agent'
@@ -213,8 +235,7 @@ export const discoverTools = async (
: id,
),
...(additionalPluginIds || []),
- ...(selectedToolIds || []),
- ...(hasMentionedAgents ? ['lobe-agent-management'] : []),
+ ...effectiveSelectedToolIds,
...(shareGate ? getShareGrantActivatedPluginIds(shareGate) : []),
]),
];
@@ -251,7 +272,7 @@ export const discoverTools = async (
optedInIds,
turnIds: [
...(additionalPluginIds || []),
- ...(selectedToolIds || []),
+ ...effectiveSelectedToolIds.filter((id) => id !== 'lobe-agent-management'),
...(shareGate ? getShareGrantActivatedPluginIds(shareGate) : []),
// An eval binds its connectors to the run by snapshot.
...boundConnectorIds,
@@ -517,7 +538,7 @@ export const discoverTools = async (
isBotConversation,
isProjectConversation: !!appContext?.projectId,
isProjectCoordinator: projectScope.isCoordinator,
- loadHistoryMessages,
+ loadHistoryMessages: readHistoryMessages,
modelMediaCapabilities,
})),
]),
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.test.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.test.ts
index 50787589f3e..a1da77e1bb8 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.test.ts
@@ -2,7 +2,7 @@ import { ArtboardIdentifier } from '@lobechat/builtin-tool-artboard';
import { GoalIdentifier } from '@lobechat/builtin-tool-goal';
import { describe, expect, it, vi } from 'vitest';
-import { resolveTurnScopedPluginIds } from './turnContext';
+import { collectSelectedToolIds, resolveTurnScopedPluginIds } from './turnContext';
vi.mock('../../helpers/mediaAvailability', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
@@ -56,3 +56,123 @@ describe('resolveTurnScopedPluginIds artboard', () => {
expect(await resolveIn(false)).not.toContain(ArtboardIdentifier);
});
});
+
+describe('collectSelectedToolIds', () => {
+ it('keeps tools earlier user turns selected and merges the current turn selection', () => {
+ const history = [
+ { metadata: { selectedToolIds: ['xmind'] }, role: 'user' },
+ { metadata: null, role: 'assistant' },
+ { metadata: { selectedToolIds: ['lobe-web-browsing', 'xmind'] }, role: 'user' },
+ ];
+
+ expect(
+ collectSelectedToolIds(history, ['feishu', 'xmind'], { hasMentionedAgents: true }),
+ ).toEqual(['xmind', 'lobe-web-browsing', 'feishu', 'lobe-agent-management']);
+ });
+
+ it('recovers tool action tags and agent mentions from legacy user turns without metadata.selectedToolIds', () => {
+ const history = [
+ {
+ content: '<mention name="Writer" id="agt_writer" /> Draft an outline',
+ editorData: {
+ root: {
+ children: [
+ {
+ children: [
+ {
+ actionCategory: 'tool',
+ actionLabel: 'XMind',
+ actionType: 'xmind',
+ type: 'action-tag',
+ },
+ {
+ label: 'Writer',
+ metadata: { id: 'agt_writer', type: 'agent' },
+ type: 'mention',
+ },
+ ],
+ type: 'paragraph',
+ },
+ ],
+ type: 'root',
+ },
+ },
+ role: 'user',
+ },
+ {
+ compressedMessages: [
+ {
+ content: '<mention name="Reviewer" id="market:reviewer" /> Check it',
+ role: 'user',
+ },
+ ],
+ role: 'compressedGroup',
+ },
+ ];
+
+ expect(collectSelectedToolIds(history)).toEqual(['xmind', 'lobe-agent-management']);
+ });
+
+ it('does not enable lobe-agent-management from @mentions inside a group conversation', () => {
+ const history = [
+ {
+ content: '<mention name="Writer" id="agt_writer" /> Hello',
+ editorData: {
+ root: {
+ children: [
+ {
+ label: 'Writer',
+ metadata: { id: 'agt_writer', type: 'agent' },
+ type: 'mention',
+ },
+ ],
+ type: 'root',
+ },
+ },
+ role: 'user',
+ },
+ ];
+
+ expect(
+ collectSelectedToolIds(history, [], {
+ hasMentionedAgents: true,
+ isGroupConversation: true,
+ }),
+ ).toEqual([]);
+ });
+
+ it('ignores non-user rows, external/bot messages, other agents rows, and malformed metadata', () => {
+ const history = [
+ { metadata: { selectedToolIds: ['from-assistant'] }, role: 'assistant' },
+ { metadata: { selectedToolIds: 'not-an-array' }, role: 'user' },
+ { metadata: { selectedToolIds: [42, '', 'kept'] }, role: 'user' },
+ {
+ content: '<mention name="Writer" id="agt_writer" /> From bot sender',
+ metadata: {
+ botSender: { platform: 'discord', userId: 'u1' },
+ selectedToolIds: ['from-bot'],
+ },
+ role: 'user',
+ },
+ {
+ content: '<mention name="Writer" id="agt_writer" /> From external event',
+ metadata: {
+ externalOrigin: { provider: 'github' },
+ selectedToolIds: ['from-webhook'],
+ },
+ role: 'user',
+ },
+ {
+ agentId: 'agt_supervisor',
+ metadata: { selectedToolIds: ['supervisor-only-connector'] },
+ role: 'user',
+ },
+ { content: 'plain text without mention tags', role: 'user' },
+ ];
+
+ expect(collectSelectedToolIds(history, [], { resolvedAgentId: 'agt_member' })).toEqual([
+ 'kept',
+ ]);
+ expect(collectSelectedToolIds(history, [], { isInGroupMember: true })).toEqual([]);
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.ts
index 32de3747217..a003950126b 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.ts
@@ -23,6 +23,141 @@ import type { ToolDiscoveryDeps, ToolDiscoveryInput } from './types';
const log = debug('lobe-server:ai-agent-service');
+const AGENT_MANAGEMENT_IDENTIFIER = 'lobe-agent-management';
+const SERIALIZED_AGENT_MENTION_RE =
+ /<mention\b[^>]*\bid=["']?(?:agt_|market:)[^"'\s/>]+["']?[^>]*\/>/;
+
+const extractEditorTurnToolIds = (
+ node: unknown,
+ includeAgentMentions: boolean,
+ out: string[],
+): void => {
+ if (!node || typeof node !== 'object') return;
+ const record = node as Record<string, unknown>;
+ if (
+ record.type === 'action-tag' &&
+ record.actionCategory === 'tool' &&
+ typeof record.actionType === 'string' &&
+ record.actionType.length > 0
+ ) {
+ out.push(record.actionType);
+ }
+ if (
+ includeAgentMentions &&
+ record.type === 'mention' &&
+ record.metadata &&
+ typeof record.metadata === 'object' &&
+ (record.metadata as Record<string, unknown>).type === 'agent' &&
+ typeof (record.metadata as Record<string, unknown>).id === 'string' &&
+ ((record.metadata as Record<string, unknown>).id as string).length > 0
+ ) {
+ out.push(AGENT_MANAGEMENT_IDENTIFIER);
+ }
+ if (Array.isArray(record.children)) {
+ for (const child of record.children) {
+ extractEditorTurnToolIds(child, includeAgentMentions, out);
+ }
+ }
+};
+
+export interface HistoryTurnSelectionMessage {
+ agentId?: string | null;
+ compressedMessages?: ReadonlyArray<HistoryTurnSelectionMessage> | null;
+ content?: unknown;
+ editorData?: Record<string, any> | null;
+ metadata?: {
+ botSender?: unknown;
+ externalOrigin?: unknown;
+ selectedToolIds?: unknown;
+ } | null;
+ role: string;
+}
+
+/**
+ * The tools the user selected or triggered via @-mentions anywhere in this
+ * topic so far: earlier user turns' persisted `metadata.selectedToolIds`
+ * (falling back to composer `editorData` action tags / agent mentions and
+ * serialized `<mention id="agt_..." />` tags for legacy rows), plus this
+ * turn's selection. Deduplicated, in first-selected order.
+ *
+ * Keeping turn-selected tools in the operation's initial invocation set on
+ * follow-up turns preserves the system prompt and `<available_tools>` prefix
+ * across turns, avoiding prompt-cache invalidation and `tool_name_unresolved`
+ * when the model continues calling a tool it already used in an earlier turn.
+ */
+export const collectSelectedToolIds = (
+ historyMessages: ReadonlyArray<HistoryTurnSelectionMessage>,
+ current: readonly string[] = [],
+ options?: {
+ hasMentionedAgents?: boolean;
+ isGroupConversation?: boolean;
+ /**
+ * An in-group member turn (`orchestrationRole === 'member'` without an
+ * isolated `threadId`) shares the group topic's history but is prompted by
+ * an ephemeral supervisor instruction, so it must not inherit the group
+ * supervisor's @-mentioned tools from the shared topic.
+ */
+ isInGroupMember?: boolean;
+ resolvedAgentId?: string;
+ },
+): string[] => {
+ const includeAgentMentions = !options?.isGroupConversation;
+ const ids: string[] = [];
+
+ const visitMessage = (message: HistoryTurnSelectionMessage) => {
+ if (Array.isArray(message.compressedMessages)) {
+ for (const member of message.compressedMessages) {
+ if (member && typeof member === 'object') visitMessage(member);
+ }
+ }
+ if (message.role !== 'user') return;
+ if (message.metadata?.botSender || message.metadata?.externalOrigin) return;
+ if (
+ options?.resolvedAgentId &&
+ typeof message.agentId === 'string' &&
+ message.agentId.length > 0 &&
+ message.agentId !== options.resolvedAgentId
+ ) {
+ return;
+ }
+
+ const persisted = message.metadata?.selectedToolIds;
+ if (Array.isArray(persisted)) {
+ for (const id of persisted) {
+ if (typeof id === 'string' && id.length > 0) ids.push(id);
+ }
+ }
+ if (message.editorData && typeof message.editorData === 'object') {
+ extractEditorTurnToolIds(
+ (message.editorData as Record<string, unknown>).root,
+ includeAgentMentions,
+ ids,
+ );
+ }
+ if (
+ includeAgentMentions &&
+ typeof message.content === 'string' &&
+ SERIALIZED_AGENT_MENTION_RE.test(message.content)
+ ) {
+ ids.push(AGENT_MANAGEMENT_IDENTIFIER);
+ }
+ };
+
+ if (!options?.isInGroupMember) {
+ for (const message of historyMessages) {
+ visitMessage(message);
+ }
+ }
+
+ return [
+ ...new Set([
+ ...ids,
+ ...current.filter((id): id is string => typeof id === 'string' && id.length > 0),
+ ...(includeAgentMentions && options?.hasMentionedAgents ? [AGENT_MANAGEMENT_IDENTIFIER] : []),
+ ]),
+ ];
+};
+
/**
* Turn-scoped builtin tools to append to the candidate plugin ids: the IM
* message tool for bot conversations, the task tool for a project coordinator
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index 9e626df926f..43c3823a38b 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -356,6 +356,8 @@ export interface TurnSetupInput {
cronJobId?: string;
externalOrigin?: InternalExecAgentParams['externalOrigin'];
files?: InternalExecAgentParams['files'];
+ /** Whether the turn @-mentions agents in a non-group conversation. */
+ hasMentionedAgents?: boolean;
modelOverride?: string;
/** See `ExecAgentParams.openedByTopicId`. */
openedByTopicId?: string;
@@ -374,6 +376,8 @@ export interface TurnSetupInput {
runFromHistory: boolean;
/** Skills the user selected for this turn; see `ExecAgentParams.selectedSkillIds`. */
selectedSkillIds?: string[];
+ /** Tools the user selected for this turn; see `ExecAgentParams.selectedToolIds`. */
+ selectedToolIds?: string[];
/** Shared-agent visitor gate β€” set only by the shareChat router. */
shareGate?: AgentShareGate;
/** The prompt was queued behind a running turn; see `ExecAgentParams.steer`. */
@@ -473,6 +477,7 @@ export const setupTurn = async (
webhookThread,
openedByTopicId,
files,
+ hasMentionedAgents,
modelOverride,
operationTaskId,
parentMessageId,
@@ -486,6 +491,7 @@ export const setupTurn = async (
resume,
runFromHistory,
selectedSkillIds,
+ selectedToolIds,
shareGate,
steer,
throwIfExecutionAborted,
@@ -923,7 +929,9 @@ export const setupTurn = async (
botSender,
composerMetadata: userMessage?.metadata,
externalOrigin,
+ hasMentionedAgents,
selectedSkillIds,
+ selectedToolIds,
steer,
trigger,
});
diff --git a/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.test.ts b/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.test.ts
index d4a5b7dbdf7..5065fb8c7c9 100644
--- a/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.test.ts
@@ -29,4 +29,23 @@ describe('buildUserTurnMetadata', () => {
it('omits an empty skill selection', () => {
expect(buildUserTurnMetadata({ selectedSkillIds: [] })).not.toHaveProperty('selectedSkillIds');
});
+
+ it('persists the selected tools and agent-mention tool once each for later turns', () => {
+ expect(
+ buildUserTurnMetadata({
+ hasMentionedAgents: true,
+ selectedToolIds: ['lobe-web-browsing', 'xmind', 'lobe-web-browsing'],
+ trigger: RequestTrigger.Chat,
+ }),
+ ).toEqual({
+ selectedToolIds: ['lobe-web-browsing', 'xmind', 'lobe-agent-management'],
+ trigger: RequestTrigger.Chat,
+ });
+ });
+
+ it('omits an empty tool selection when no agents are mentioned', () => {
+ expect(
+ buildUserTurnMetadata({ hasMentionedAgents: false, selectedToolIds: [] }),
+ ).not.toHaveProperty('selectedToolIds');
+ });
});
diff --git a/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.ts b/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.ts
index 1a7221f2ec8..95e0892693d 100644
--- a/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.ts
+++ b/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.ts
@@ -10,7 +10,9 @@ export interface UserTurnMetadataInput {
/** What the composer authored for this message (attached content, …). */
composerMetadata?: ComposerUserMessageMetadata;
externalOrigin?: InternalExecAgentParams['externalOrigin'];
+ hasMentionedAgents?: boolean;
selectedSkillIds?: string[];
+ selectedToolIds?: string[];
steer?: boolean;
trigger?: string;
}
@@ -26,34 +28,49 @@ export const buildUserTurnMetadata = ({
botSender,
composerMetadata,
externalOrigin,
+ hasMentionedAgents,
selectedSkillIds,
+ selectedToolIds,
steer,
trigger,
-}: UserTurnMetadataInput) => ({
- // The composer's own part of the message, validated by
- // `ComposerUserMessageMetadataSchema`. Spread first so every server-derived
- // field below wins over anything a client sent.
- ...composerMetadata,
- ...(trigger && Object.values(RequestTrigger).includes(trigger as RequestTrigger)
- ? { trigger: trigger as RequestTrigger }
- : undefined),
- ...(appContext?.conversationAgentId && appContext.scope === 'sub_agent'
- ? { agentDispatch: { kind: 'callAgent' as const, visibility: 'internal' as const } }
- : undefined),
- // An agent β†’ agent turn (a sibling agent calling `lh agent run`). The row is
- // persisted in THIS topic under the human owner, so keep the sending agent
- // alongside β€” the UI shows it as the author and links back to its topic.
- ...(agentSender ? { agentSender } : undefined),
- // Bot-channel turns are inserted under the OWNER's userId; keep the real
- // platform author alongside so the UI can attribute the bubble correctly.
- ...(botSender ? { botSender } : undefined),
- // A provider event that injected this turn keeps its source on the row.
- ...(externalOrigin ? { externalOrigin } : undefined),
- // A message that steered the running turn directly renders as that turn's
- // continuation; the client's optimistic row is replaced by this one. A
- // follow-up that waited in queue starts its own turn and is not marked.
- ...(steer ? { steer: true as const } : undefined),
- // Later turns read the selection back from history, so the skills stay
- // injected for the rest of the topic (see `collectSelectedSkillIds`).
- ...(selectedSkillIds?.length ? { selectedSkillIds: [...new Set(selectedSkillIds)] } : undefined),
-});
+}: UserTurnMetadataInput) => {
+ const effectiveSelectedToolIds = [
+ ...(selectedToolIds ?? []),
+ ...(hasMentionedAgents ? ['lobe-agent-management'] : []),
+ ];
+
+ return {
+ // The composer's own part of the message, validated by
+ // `ComposerUserMessageMetadataSchema`. Spread first so every server-derived
+ // field below wins over anything a client sent.
+ ...composerMetadata,
+ ...(trigger && Object.values(RequestTrigger).includes(trigger as RequestTrigger)
+ ? { trigger: trigger as RequestTrigger }
+ : undefined),
+ ...(appContext?.conversationAgentId && appContext.scope === 'sub_agent'
+ ? { agentDispatch: { kind: 'callAgent' as const, visibility: 'internal' as const } }
+ : undefined),
+ // An agent β†’ agent turn (a sibling agent calling `lh agent run`). The row is
+ // persisted in THIS topic under the human owner, so keep the sending agent
+ // alongside β€” the UI shows it as the author and links back to its topic.
+ ...(agentSender ? { agentSender } : undefined),
+ // Bot-channel turns are inserted under the OWNER's userId; keep the real
+ // platform author alongside so the UI can attribute the bubble correctly.
+ ...(botSender ? { botSender } : undefined),
+ // A provider event that injected this turn keeps its source on the row.
+ ...(externalOrigin ? { externalOrigin } : undefined),
+ // A message that steered the running turn directly renders as that turn's
+ // continuation; the client's optimistic row is replaced by this one. A
+ // follow-up that waited in queue starts its own turn and is not marked.
+ ...(steer ? { steer: true as const } : undefined),
+ // Later turns read the selections back from history, so the skills and
+ // tools stay injected for the rest of the topic (see
+ // `collectSelectedSkillIds` and `collectSelectedToolIds`).
+ ...(selectedSkillIds?.length
+ ? { selectedSkillIds: [...new Set(selectedSkillIds)] }
+ : undefined),
+ ...(effectiveSelectedToolIds.length
+ ? { selectedToolIds: [...new Set(effectiveSelectedToolIds)] }
+ : undefined),
+ };
+};
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index f42c06acdea..05f58e0e27d 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -487,6 +487,7 @@ export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSche
reactions: z.array(EmojiReactionSchema).optional(),
scope: z.string().optional(),
selectedSkillIds: z.array(z.string()).optional(),
+ selectedToolIds: z.array(z.string()).optional(),
// External-signal lineage for Monitor-style callback turns ().
signal: MessageSignalSchema.optional(),
steer: z.boolean().optional(),
@@ -778,6 +779,12 @@ export interface MessageMetadata {
* on this and every later turn of the topic by the server runtime.
*/
selectedSkillIds?: string[];
+ /**
+ * Tools the user selected (or triggered via @agent mention) for this user
+ * turn, kept enabled on this and every later turn of the topic by the server
+ * runtime so the prompt-cache prefix and tool availability stay stable.
+ */
+ selectedToolIds?: string[];
/**
* External-signal lineage for messages produced as reactive replies
* to an out-of-band trigger (Monitor stdout push, webhook callback,