🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(context-engine): keep system date and tool discovery prefix stable across activation (#23592)
AmAzing-5c17a06e3970
diff --git a/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts b/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.tsindex 1d43c2f9245..db9b8ca1284 100644--- a/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts@@ -188,6 +188,59 @@ describe('resolveServerCallLlmTooling', () => {).toEqual([searchTool]);});+ it('keeps toolDiscoveryConfig stable across mid-operation tool activations', () => {+ const ctx = { operationId: 'op-1', stepIndex: 0 };+ const state = buildState({+ operationToolSet: {+ enabledToolIds: [LobeActivatorManifest.identifier],+ manifestMap: {+ [LobeActivatorManifest.identifier]: LobeActivatorManifest,+ [CredsIdentifier]: CredsManifest,+ 'lobe-web-browsing': webBrowsing,+ },+ sourceMap: {},+ tools: [],+ },+ });++ const before = resolveServerCallLlmTooling(ctx, state);+ const after = resolveServerCallLlmTooling(+ { ...ctx, stepIndex: 1 },+ {+ ...state,+ activatedStepTools: [+ {+ activatedAtStep: 0,+ id: 'lobe-web-browsing',+ manifest: webBrowsing,+ source: 'discovery',+ },+ ],+ },+ );++ expect(after.resolved.enabledToolIds).toContain('lobe-web-browsing');+ expect(after.toolDiscoveryConfig).toEqual(before.toolDiscoveryConfig);++ const forcedFinish = resolveServerCallLlmTooling(+ { ...ctx, stepIndex: 2 },+ {+ ...state,+ activatedStepTools: [+ {+ activatedAtStep: 0,+ id: 'lobe-web-browsing',+ manifest: webBrowsing,+ source: 'discovery',+ },+ ],+ forceFinish: true,+ },+ );++ expect(forcedFinish.toolDiscoveryConfig).toBeUndefined();+ });+it('leaves the active device id undefined with no binding at all', () => {const result = resolveServerCallLlmTooling({ operationId: 'op-1', stepIndex: 0 }, buildState());diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.tsindex 939c1ac7493..b85b0164ee3 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts@@ -1,4 +1,5 @@import { type AgentState, selectOperationToolSet } from '@lobechat/agent-runtime';+import { LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';import {buildStepSkillDelta,buildStepToolDelta,@@ -78,7 +79,14 @@ export const resolveServerCallLlmTooling = ();const tools = resolved.tools.length > 0 ? resolved.tools : undefined;- const toolDiscoveryConfig = buildToolDiscoveryConfig(operationToolSet, resolved.enabledToolIds);+ // Keep <available_tools> anchored to the operation's starting enabledToolIds+ // as long as the activator remains active this step (e.g. not stripped by+ // forceFinish). Dropping newly activated tools mid-operation mutates the+ // before-first-user context message and invalidates the prompt-cache prefix;+ // the next operation starts with them already in `operationToolSet.enabledToolIds`.+ const toolDiscoveryConfig = resolved.enabledToolIds.includes(LobeActivatorIdentifier)+ ? buildToolDiscoveryConfig(operationToolSet, operationToolSet.enabledToolIds)+ : undefined;if (stepDelta.activatedTools.length > 0) {log(diff --git a/packages/builtin-tool-web-browsing/src/manifest.ts b/packages/builtin-tool-web-browsing/src/manifest.tsindex 22ad1232127..bb9796e1973 100644--- a/packages/builtin-tool-web-browsing/src/manifest.ts+++ b/packages/builtin-tool-web-browsing/src/manifest.ts@@ -1,5 +1,4 @@import type { BuiltinToolManifest } from '@lobechat/types';-import dayjs from 'dayjs';import { systemPrompt } from './systemRole';import { WebBrowsingApiName } from './types';@@ -79,6 +78,6 @@ export const WebBrowsingManifest: BuiltinToolManifest = {'Search the web for current information and crawl web pages to extract content. Supports automatic engine selection, categories, and time ranges for comprehensive research.',title: 'Web Browsing',},- systemRole: systemPrompt(dayjs(new Date()).format('YYYY-MM-DD')),+ systemRole: systemPrompt(),type: 'builtin',};diff --git a/packages/builtin-tool-web-browsing/src/systemRole.ts b/packages/builtin-tool-web-browsing/src/systemRole.tsindex eba02f04fa6..b3e414af916 100644--- a/packages/builtin-tool-web-browsing/src/systemRole.ts+++ b/packages/builtin-tool-web-browsing/src/systemRole.ts@@ -1,5 +1,5 @@export const systemPrompt = (- date: string,+ _date?: string,) => `You have a Web Information tool with powerful internet access capabilities. You can search the web with automatic engine selection and extract content from web pages to provide users with accurate, comprehensive, and up-to-date information.<core_capabilities>@@ -120,6 +120,4 @@ Our search service is a metasearch engine with automatic engine selection. Provi- For ambiguous queries, ask for clarification or suggest interpretations/alternative search terms before conducting extensive searches.- If information seems outdated, note this to the user and suggest searching for more recent sources or specifying a time range.</error_handling>--Current date: ${date}`;diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.tsindex 61b77d2832a..ae0fd6182fa 100644--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts@@ -242,12 +242,11 @@ export class MessagesEngine {: undefined;const isTodoEnabled = effectiveTodos !== undefined;- // System date is redundant when web-browsing or memory tools are enabled,- // as they already include current date in their system promptsconst toolIds = toolsConfig?.tools || [];- const hasDateAwareTools =- toolIds.includes('lobe-web-browsing') || toolIds.includes('lobe-user-memory');- const isSystemDateEnabled = enableSystemDate !== false && !hasDateAwareTools;+ // Keep SystemDateProvider independent of dynamically activated tools:+ // toggling it off when web-browsing or user-memory is activated mid-run+ // mutates the leading system message and invalidates the prompt-cache prefix.+ const isSystemDateEnabled = enableSystemDate !== false;// An eval attempt renders "today" from its case clock, never the wall clock.const evalClock = evalContext?.sessionDate ? new Date(evalContext.sessionDate) : undefined;const currentUserMessage = [...messages]diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.systemDate.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.systemDate.test.tsnew file mode 100644index 00000000000..a459083092c--- /dev/null+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.systemDate.test.ts@@ -0,0 +1,85 @@+import { describe, expect, it } from 'vitest';++import type { UIChatMessage } from '@/types/index';++import { MessagesEngine } from '../MessagesEngine';+import type { MessagesEngineParams } from '../types';++const createMessages = (): UIChatMessage[] => [+ {+ content: 'Check this article',+ createdAt: 1_700_000_000_000,+ id: 'msg-1',+ role: 'user',+ updatedAt: 1_700_000_000_000,+ } as UIChatMessage,+];++const createParams = (overrides?: Partial<MessagesEngineParams>): MessagesEngineParams => ({+ evalContext: { sessionDate: '2026-11-21T12:00:00Z' },+ messages: createMessages(),+ model: 'gemini-4-neon',+ provider: 'lobehub',+ skillsConfig: {+ enabledSkills: [+ {+ description: 'Run statistical tests',+ identifier: 'stat-skill',+ name: 'Statistical Analysis',+ },+ ],+ },+ systemRole: 'You are a helpful assistant.',+ timezone: 'Asia/Shanghai',+ ...overrides,+});++describe('MessagesEngine SystemDateProvider stability', () => {+ it.each(['lobe-web-browsing', 'lobe-user-memory'])(+ 'keeps SystemDateProvider and the leading system prefix stable when %s is activated mid-run',+ async (toolId) => {+ const before = await new MessagesEngine(+ createParams({+ toolsConfig: {+ manifests: [],+ tools: ['lobe-activator'],+ },+ }),+ ).process();++ const after = await new MessagesEngine(+ createParams({+ toolsConfig: {+ manifests: [+ {+ api: [{ description: 'Run tool', name: 'run', parameters: {} }],+ identifier: toolId,+ meta: { title: toolId },+ systemRole: 'Use this tool carefully.',+ type: 'builtin',+ },+ ],+ tools: ['lobe-activator', toolId],+ },+ }),+ ).process();++ const beforeSystem = before.messages[0].content as string;+ const afterSystem = after.messages[0].content as string;++ expect(beforeSystem).toContain('Current date: 2026-11-21 (Asia/Shanghai)');+ expect(afterSystem).toContain('Current date: 2026-11-21 (Asia/Shanghai)');+ expect(afterSystem.startsWith(beforeSystem)).toBe(true);+ },+ );++ it('still respects explicit enableSystemDate: false', async () => {+ const result = await new MessagesEngine(+ createParams({+ enableSystemDate: false,+ }),+ ).process();++ expect(result.messages[0].content as string).not.toContain('Current date:');+ });+});diff --git a/src/services/chat/index.ts b/src/services/chat/index.tsindex 93c101e82f5..1e788b375d6 100644--- a/src/services/chat/index.ts+++ b/src/services/chat/index.ts@@ -77,6 +77,7 @@ export interface GetChatCompletionPayload extends Partial<Omit<ChatStreamPayload* budget is spent (planned by `shouldCompress`).*/attachmentPreviewFileIds?: string[];+ discoveryExcludedToolIds?: string[];discoveryManifests?: Record<string, LobeToolManifest>;groupId?: string;messages: UIChatMessage[];@@ -159,6 +160,7 @@ class ChatService {groupId,additionalContexts,attachmentPreviewFileIds,+ discoveryExcludedToolIds,discoveryManifests,topicId,resolvedAgentConfig,@@ -268,6 +270,7 @@ class ChatService {// Page editor context from agent runtimeinitialContext: options?.initialContext,inputTemplate: chatConfig.inputTemplate,+ discoveryExcludedToolIds,discoveryManifests,manifests: enabledManifests,messages: messagesForContext,diff --git a/src/services/chat/mecha/contextEngineering.discovery.test.ts b/src/services/chat/mecha/contextEngineering.discovery.test.tsnew file mode 100644index 00000000000..5a128c2e639--- /dev/null+++ b/src/services/chat/mecha/contextEngineering.discovery.test.ts@@ -0,0 +1,82 @@+import { LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';+import type { LobeToolManifest } from '@lobechat/context-engine';+import type { UIChatMessage } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import { contextEngineering } from './contextEngineering';++vi.mock('@/helpers/parserPlaceholder', () => ({+ HOST_VARIABLE_GENERATORS: {+ random: () => '12345',+ username: () => 'TestUser',+ },+}));++describe('contextEngineering tool discovery stability', () => {+ const discoveryManifests: Record<string, LobeToolManifest> = {+ [LobeActivatorIdentifier]: {+ api: [{ description: 'Activate tools', name: 'activateTools', parameters: {} }],+ identifier: LobeActivatorIdentifier,+ meta: { description: 'Activate tools', title: 'Activator' },+ type: 'builtin',+ },+ 'lobe-web-browsing': {+ api: [{ description: 'Crawl a page', name: 'crawlSinglePage', parameters: {} }],+ identifier: 'lobe-web-browsing',+ meta: { description: 'Search and crawl web pages', title: 'Web Browsing' },+ type: 'builtin',+ },+ 'lobe-notebook': {+ api: [{ description: 'Create note', name: 'createDocument', parameters: {} }],+ identifier: 'lobe-notebook',+ meta: { description: 'Manage notes', title: 'Notebook' },+ type: 'builtin',+ },+ };++ const baseMessages: UIChatMessage[] = [+ {+ content: 'Check this link',+ createdAt: 1_700_000_000_000,+ id: 'msg-1',+ role: 'user',+ updatedAt: 1_700_000_000_000,+ } as UIChatMessage,+ ];++ it('keeps <available_tools> unchanged mid-operation when discoveryExcludedToolIds stays anchored', async () => {+ const before = await contextEngineering({+ discoveryExcludedToolIds: [LobeActivatorIdentifier],+ discoveryManifests,+ messages: baseMessages,+ model: 'gpt-4o',+ provider: 'openai',+ tools: [LobeActivatorIdentifier],+ });++ const after = await contextEngineering({+ discoveryExcludedToolIds: [LobeActivatorIdentifier],+ discoveryManifests,+ messages: baseMessages,+ model: 'gpt-4o',+ provider: 'openai',+ tools: [LobeActivatorIdentifier, 'lobe-web-browsing'],+ });++ const beforeInjected = before.find(+ (m) =>+ m.role === 'user' &&+ typeof m.content === 'string' &&+ m.content.includes('<available_tools'),+ );+ const afterInjected = after.find(+ (m) =>+ m.role === 'user' &&+ typeof m.content === 'string' &&+ m.content.includes('<available_tools'),+ );++ expect(beforeInjected?.content).toContain('lobe-web-browsing');+ expect(afterInjected?.content).toBe(beforeInjected?.content);+ });+});diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.tsindex 2f689ff5021..b5fdb8840bf 100644--- a/src/services/chat/mecha/contextEngineering.ts+++ b/src/services/chat/mecha/contextEngineering.ts@@ -85,6 +85,13 @@ interface ContextEngineeringContext {* `<available_skills>` nor resolvable by name via `activateSkill`.*/disabledPluginIds?: string[];+ /**+ * Tool IDs excluded from `<available_tools>` discovery (typically the tools+ * already enabled when the operation started). Keeping this anchored across+ * mid-operation tool activations prevents mutating the before-first-user+ * prefix message. Defaults to `tools`.+ */+ discoveryExcludedToolIds?: string[];discoveryManifests?: Record<string, LobeToolManifest>;/*** Runtime-resolved agent mode. Callers may force chat mode for models without@@ -148,6 +155,7 @@ export const contextEngineering = async ({agentId,autoSkillIds,disabledPluginIds,+ discoveryExcludedToolIds,discoveryManifests,enableAgentMode,groupId,@@ -254,12 +262,13 @@ export const contextEngineering = async ({// engine dropped their manifests, so listing them would only invite an// activation that cannot succeed.const disabledIdSet = new Set(disabledPluginIds ?? []);+ const discoveryExcludedSet = new Set(discoveryExcludedToolIds ?? tools ?? []);// The run's discovery pool is scoped to the conversation already; a// connector row's tool set is disabled with its connectorconst availableTools = Object.values(discoveryManifests ?? {}).filter((manifest) =>- !enabledToolSet.has(manifest.identifier) &&+ !discoveryExcludedSet.has(manifest.identifier) &&!disabledIdSet.has(manifest.identifier) &&!disabledIdSet.has(manifestBaseIdentifier(manifest)),)diff --git a/src/store/chat/agents/transports/ClientContextBuilder.test.ts b/src/store/chat/agents/transports/ClientContextBuilder.test.tsindex a67081701e9..d310edfee91 100644--- a/src/store/chat/agents/transports/ClientContextBuilder.test.ts+++ b/src/store/chat/agents/transports/ClientContextBuilder.test.ts@@ -127,6 +127,7 @@ describe('ClientContextBuilder', () => {);expect(prepareContext).toHaveBeenCalledWith(expect.objectContaining({+ discoveryExcludedToolIds: [],messages: [userMessage],resolvedAgentConfig: expect.objectContaining({enabledToolIds: ['dynamic-search'],diff --git a/src/store/chat/agents/transports/ClientContextBuilder.ts b/src/store/chat/agents/transports/ClientContextBuilder.tsindex 9d369b35f76..695df50cda3 100644--- a/src/store/chat/agents/transports/ClientContextBuilder.ts+++ b/src/store/chat/agents/transports/ClientContextBuilder.ts@@ -81,6 +81,7 @@ export class ClientContextBuilder implements ContextBuilder {agentId: effectiveAgentId || undefined,additionalContexts: input.payload.additionalContexts,attachmentPreviewFileIds: input.payload.attachmentPreviewFileIds,+ discoveryExcludedToolIds: this.context.agentConfig.enabledToolIds ?? [],discoveryManifests:input.state.operationToolSet?.manifestMap ?? input.state.toolManifestMap,groupId,