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(agent-runtime): restore activated tools across operations (#17076)

Arvin Xu3c3dcd608c11
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index 275eb0eff12..94fdf54729e 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -326,6 +326,73 @@ describe('AgentRuntimeService', () => {
);
});
+ it('should restore tools activated in a previous operation into initial state', async () => {
+ const taskManifest = { identifier: 'lobe-task' } as any;
+ const initialMessages = [
+ {
+ content: 'Successfully activated tools: lobe-task',
+ id: 'tool-message-1',
+ plugin: { apiName: 'activateTools', identifier: 'lobe-activator' },
+ pluginState: { activatedTools: [{ identifier: 'lobe-task' }] },
+ role: 'tool',
+ },
+ ] as any;
+
+ await service.createOperation({
+ ...mockParams,
+ autoStart: false,
+ initialMessages,
+ initialStepCount: 3,
+ toolSet: {
+ ...mockParams.toolSet,
+ activatableToolIds: ['lobe-task'],
+ manifestMap: { 'lobe-task': taskManifest },
+ },
+ });
+
+ expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(
+ 'test-operation-1',
+ expect.objectContaining({
+ activatedStepTools: [
+ {
+ activatedAtStep: 3,
+ id: 'lobe-task',
+ manifest: taskManifest,
+ source: 'discovery',
+ },
+ ],
+ }),
+ );
+ });
+
+ it('should not restore historical tools that current run gates reject', async () => {
+ await service.createOperation({
+ ...mockParams,
+ autoStart: false,
+ initialMessages: [
+ {
+ content: 'Successfully activated tools: lobe-task',
+ id: 'tool-message-1',
+ plugin: { apiName: 'activateTools', identifier: 'lobe-activator' },
+ pluginState: { activatedTools: [{ identifier: 'lobe-task' }] },
+ role: 'tool',
+ },
+ ] as any,
+ toolSet: {
+ ...mockParams.toolSet,
+ // The broad discovery map may still contain the manifest in chat/custom
+ // mode or for a model without function calling support.
+ activatableToolIds: [],
+ manifestMap: { 'lobe-task': { identifier: 'lobe-task' } as any },
+ },
+ });
+
+ expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(
+ 'test-operation-1',
+ expect.objectContaining({ activatedStepTools: undefined }),
+ );
+ });
+
it('should abort before creating operation when signal is already aborted', async () => {
const controller = new AbortController();
controller.abort(new Error('startup aborted'));
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 177edce03c9..0f75a30732f 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -8,6 +8,7 @@ import type {
} from '@lobechat/agent-runtime';
import {
AgentRuntime,
+ extractActivatedToolIdsFromMessages,
findInMessages,
GeneralChatAgent,
isParkedStatus,
@@ -515,7 +516,21 @@ export class AgentRuntimeService {
);
// Initialize operation state - create state before saving
+ const activatableToolIds = new Set(operationToolSet.activatableToolIds ?? []);
+ const restoredActivatedToolIds = extractActivatedToolIdsFromMessages(initialMessages)?.filter(
+ (id) => activatableToolIds.has(id),
+ );
+ const activatedStepTools = restoredActivatedToolIds?.length
+ ? restoredActivatedToolIds.map((id) => ({
+ activatedAtStep: initialStepCount,
+ id,
+ manifest: operationToolSet.manifestMap[id],
+ source: 'discovery' as const,
+ }))
+ : undefined;
+
const initialState = {
+ activatedStepTools,
createdAt: new Date().toISOString(),
// Store initialContext for executeSync to use
initialContext,
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index 69df2a8832f..ba65c71fc66 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -19,6 +19,8 @@ import { type AgentHook } from './hooks/types';
// ==================== Operation Tool Set ====================
export interface OperationToolSet {
+ /** Tool IDs that may be restored from historical explicit activations for this run. */
+ activatableToolIds?: string[];
enabledToolIds?: string[];
executorMap?: Record<string, ToolExecutor>;
manifestMap: Record<string, LobeToolManifest>;
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 021863ba923..e524f2d18a7 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -4,7 +4,11 @@ import type {
AgentState,
GeneralAgentConfig,
} from '@lobechat/agent-runtime';
-import { GeneralChatAgent, GraphAgent } from '@lobechat/agent-runtime';
+import {
+ extractActivatedToolIdsFromMessages,
+ GeneralChatAgent,
+ GraphAgent,
+} from '@lobechat/agent-runtime';
import { BUILTIN_AGENT_SLUGS, getAgentRuntimeConfig } from '@lobechat/builtin-agents';
import { builtinSkills } from '@lobechat/builtin-skills';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
@@ -29,7 +33,7 @@ import type {
ToolExecutor,
ToolSource,
} from '@lobechat/context-engine';
-import { SkillEngine } from '@lobechat/context-engine';
+import { SkillEngine, type ToolsEngine } from '@lobechat/context-engine';
import type { LobeChatDatabase } from '@lobechat/database';
import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
import { buildTaskManagerDefaultsPrompt } from '@lobechat/prompts';
@@ -2238,6 +2242,7 @@ export class AiAgentService {
enabledToolIds: [],
tools: undefined,
};
+ let toolsEngine: ToolsEngine | undefined;
const toolManifestMap: Record<string, any> = {};
const toolSourceMap: Record<string, ToolSource> = {};
const toolExecutorMap: Record<string, ToolExecutor> = {};
@@ -2738,7 +2743,7 @@ export class AiAgentService {
const activeComposioManifests = dropDisabledManifests(composioManifests);
const activeConnectorManifests = dropDisabledManifests(connectorManifests);
- const toolsEngine = createServerAgentToolsEngine(toolsContext, {
+ toolsEngine = createServerAgentToolsEngine(toolsContext, {
additionalManifests: [
...activeLobehubSkillManifests,
...activeComposioManifests,
@@ -3296,6 +3301,20 @@ export class AiAgentService {
const allMessages =
runFromHistory && !ephemeralUserMessage ? historyMessages : [...historyMessages, userMessage];
+ // Re-check historical activations against this run's tool-mode and model
+ // gates. manifestMap is intentionally broader for discovery and must not
+ // by itself authorize a tool in chat/custom mode or without function calls.
+ const historicalActivatedToolIds = extractActivatedToolIdsFromMessages(allMessages) ?? [];
+ const activatableToolIds = toolsEngine && historicalActivatedToolIds.length > 0
+ ? toolsEngine.generateToolsDetailed({
+ context: { isExplicitActivation: true },
+ model,
+ provider,
+ skipDefaultTools: true,
+ toolIds: historicalActivatedToolIds,
+ }).enabledToolIds
+ : [];
+
log('execAgent: prepared evalContext for executor');
await throwIfExecutionAborted('operation preparation');
@@ -3692,6 +3711,7 @@ export class AiAgentService {
queueRetryDelay,
stream,
toolSet: {
+ activatableToolIds,
enabledToolIds: toolsResult.enabledToolIds,
executorMap: toolExecutorMap,
manifestMap: toolManifestMap,
diff --git a/packages/agent-runtime/src/utils/messageSelectors.test.ts b/packages/agent-runtime/src/utils/messageSelectors.test.ts
index 9d05cb0da1b..6db11df7a79 100644
--- a/packages/agent-runtime/src/utils/messageSelectors.test.ts
+++ b/packages/agent-runtime/src/utils/messageSelectors.test.ts
@@ -4,6 +4,7 @@ import { describe, expect, it } from 'vitest';
import {
collectFromMessages,
extractActivatedSkillsFromMessages,
+ extractActivatedToolIdsFromMessages,
findInMessages,
} from './messageSelectors';
@@ -384,3 +385,65 @@ describe('extractActivatedSkillsFromMessages', () => {
expect(extractActivatedSkillsFromMessages(messages)).toBeUndefined();
});
});
+
+describe('extractActivatedToolIdsFromMessages', () => {
+ it('should accumulate and deduplicate tools from activator results', () => {
+ const messages = [
+ createToolMessage({
+ plugin: { apiName: 'activateTools', identifier: 'lobe-activator' },
+ pluginState: {
+ activatedTools: [{ identifier: 'lobe-task' }, { identifier: 'lobe-calendar' }],
+ },
+ } as any),
+ createToolMessage({
+ plugin: { apiName: 'activateTools', identifier: 'lobe-activator' },
+ pluginState: { activatedTools: [{ identifier: 'lobe-task' }] },
+ } as any),
+ ];
+
+ expect(extractActivatedToolIdsFromMessages(messages)).toEqual(['lobe-task', 'lobe-calendar']);
+ });
+
+ it('should restore tools folded into an assistantGroup', () => {
+ const messages = [
+ createMessage({
+ children: [
+ {
+ content: '',
+ id: 'msg-asst-1',
+ tools: [
+ {
+ apiName: 'activateTools',
+ id: 'call-1',
+ identifier: 'lobe-activator',
+ result: {
+ content: 'activated',
+ id: 'msg-tool-1',
+ state: { activatedTools: [{ identifier: 'lobe-task' }] },
+ },
+ },
+ ],
+ },
+ ],
+ role: 'assistantGroup',
+ } as any),
+ ];
+
+ expect(extractActivatedToolIdsFromMessages(messages)).toEqual(['lobe-task']);
+ });
+
+ it('should ignore failed or unrelated tool results', () => {
+ const messages = [
+ createToolMessage({
+ plugin: { apiName: 'activateTools', identifier: 'another-tool' },
+ pluginState: { activatedTools: [{ identifier: 'lobe-task' }] },
+ } as any),
+ createToolMessage({
+ plugin: { apiName: 'activateTools', identifier: 'lobe-activator' },
+ pluginState: { notFound: ['lobe-task'] },
+ } as any),
+ ];
+
+ expect(extractActivatedToolIdsFromMessages(messages)).toBeUndefined();
+ });
+});
diff --git a/packages/agent-runtime/src/utils/messageSelectors.ts b/packages/agent-runtime/src/utils/messageSelectors.ts
index 09e30308370..25ef54a3483 100644
--- a/packages/agent-runtime/src/utils/messageSelectors.ts
+++ b/packages/agent-runtime/src/utils/messageSelectors.ts
@@ -227,3 +227,31 @@ export const extractActivatedSkillsFromMessages = (
return skillsMap.size > 0 ? [...skillsMap.values()] : undefined;
};
+
+/**
+ * Accumulate tool identifiers activated by lobe-activator across conversation
+ * turns. A new operation uses these identifiers to restore its step-level tool
+ * state, keeping discovered tools callable after the operation boundary.
+ */
+export const extractActivatedToolIdsFromMessages = (
+ messages: UIChatMessage[],
+): string[] | undefined => {
+ const toolIds = new Set<string>();
+
+ for (const msg of messages) {
+ for (const invocation of collectToolInvocations(msg)) {
+ if (
+ invocation.identifier !== ACTIVATOR_IDENTIFIER ||
+ invocation.apiName !== 'activateTools' ||
+ !Array.isArray(invocation.state?.activatedTools)
+ )
+ continue;
+
+ for (const tool of invocation.state.activatedTools as Array<{ identifier?: string }>) {
+ if (tool.identifier) toolIds.add(tool.identifier);
+ }
+ }
+ }
+
+ return toolIds.size > 0 ? [...toolIds] : undefined;
+};
diff --git a/packages/context-engine/src/engine/tools/types.ts b/packages/context-engine/src/engine/tools/types.ts
index 986e23215cb..e10ecf3aa7a 100644
--- a/packages/context-engine/src/engine/tools/types.ts
+++ b/packages/context-engine/src/engine/tools/types.ts
@@ -183,6 +183,8 @@ export type ActivationSource = 'active_tools' | 'mention' | 'device' | 'discover
* Operation-level tool set: determined at createOperation time, immutable during execution.
*/
export interface OperationToolSet {
+ /** Tool IDs that may be restored from historical explicit activations for this run. */
+ activatableToolIds?: string[];
enabledToolIds: string[];
executorMap?: Record<string, ToolExecutor>;
manifestMap: Record<string, LobeToolManifest>;