π€― 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): carry dynamic activation docs to the LLM payload once (#17972)
YuTengjing5b348e814c6e
diff --git a/packages/builtin-tool-activator/src/ExecutionRuntime/index.ts b/packages/builtin-tool-activator/src/ExecutionRuntime/index.tsindex a05a7f9dfaf..285a514697a 100644--- a/packages/builtin-tool-activator/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-activator/src/ExecutionRuntime/index.ts@@ -105,19 +105,18 @@ export class ActivatorExecutionRuntime {const parts: string[] = [];if (activatedTools.length > 0) {- parts.push('Successfully activated tools:');- for (const manifest of manifests) {- parts.push(`\n## ${manifest.name} (${manifest.identifier})`);- if (manifest.systemRole) {- parts.push(manifest.systemRole);- }- if (manifest.apiDescriptions.length > 0) {- parts.push('\nAvailable APIs:');- for (const api of manifest.apiDescriptions) {- parts.push(`- **${api.name}**: ${api.description}`);- }- }- }+ // Activation state flows through `state.activatedTools` and gets the+ // manifest (systemRole + API schemas) injected into the system prompt+ // from the next LLM call onwards, so the result only needs to list the+ // newly callable APIs β returning the full docs here would double-carry+ // them in every subsequent payload (LOBE-5684).+ const apiNames = manifests.flatMap((manifest) =>+ manifest.apiDescriptions.length > 0+ ? manifest.apiDescriptions.map((api) => `${manifest.identifier}.${api.name}`)+ : [manifest.identifier],+ );+ parts.push(`Successfully activated tools: ${apiNames.join(', ')}.`);+ parts.push('Usage instructions for the activated items are in the system prompt.');}if (activatedSkillResults.length > 0) {diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.tsindex f60ac4fa73f..edaed62e818 100644--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts@@ -4,6 +4,7 @@ import type { OpenAIChatMessage } from '@/types/index';import { ContextEngine } from '../../pipeline';import {+ ActivationResultTrimProcessor,AgentCouncilFlattenProcessor,CompressedGroupRoleTransformProcessor,DisabledToolCallFilter,@@ -51,7 +52,9 @@ import {PageEditorContextInjector,PageSelectionsInjector,PlanInjector,+ selectActivatedSkills,SelectedSkillInjector,+ selectToolPromptManifests,SkillContextProvider,SystemDateProvider,SystemRoleInjector,@@ -222,6 +225,21 @@ export class MessagesEngine {.find((m) => m.role === 'user' && typeof m.content === 'string')?.content asstring | undefined;+ // Mirror the injection gates of SkillContextProvider / ToolSystemRoleProvider+ // (enable flags + FC support + the shared select predicates) so+ // ActivationResultTrimProcessor only trims activation tool results whose full+ // documentation is confirmed to be injected into the system prompt for this+ // request β see LOBE-5684.+ const canUseFC = capabilities?.isCanUseFC || (() => true);+ const injectedActivatedSkills =+ isAgentMode && (skillsConfig?.enabledSkills?.length ?? 0) > 0+ ? selectActivatedSkills(skillsConfig?.enabledSkills)+ : [];+ const injectedToolManifests =+ (toolsConfig?.manifests?.length ?? 0) > 0 && !!canUseFC(model, provider)+ ? selectToolPromptManifests(toolsConfig?.manifests)+ : [];+// Shared config for all agent document injectorsconst agentDocConfig = {currentUserMessage,@@ -475,6 +493,17 @@ export class MessagesEngine {}),]: []),+ // Dynamic-activation result trimming β replaces activateTools /+ // activateSkill tool-result documents that are ALSO injected into the+ // system prompt (by ToolSystemRoleProvider / SkillContextProvider above)+ // with a short confirmation, so each activated document reaches the LLM+ // payload exactly once. MUST run AFTER the flatten steps (grouped /+ // compressed tool rows are only hoisted back to `role: 'tool'` with+ // plugin/pluginState there) and BEFORE ToolCallProcessor.+ new ActivationResultTrimProcessor({+ injectedManifests: injectedToolManifests,+ injectedSkills: injectedActivatedSkills,+ }),// Placeholder variables processing β MUST run AFTER all flatten / role// transform steps. AssistantGroup / Supervisor messages keep their real// content (including any `{{...}}` placeholders inside tool results)diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.activationResultTrim.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.activationResultTrim.test.tsnew file mode 100644index 00000000000..90ab53b10c0--- /dev/null+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.activationResultTrim.test.ts@@ -0,0 +1,282 @@+import { describe, expect, it } from 'vitest';++import type { UIChatMessage } from '@/types/index';++import type { SkillMeta } from '../../../providers/SkillContextProvider';+import type { LobeToolManifest } from '../../tools/types';+import { MessagesEngine } from '../MessagesEngine';+import type { MessagesEngineParams } from '../types';++/**+ * Regression tests for LOBE-5684: after dynamic activation, the full tool+ * systemRole / skill content must reach the final LLM payload exactly once β+ * either via the system prompt injection OR via the activation tool result,+ * never both.+ */++const CREDS_SYSTEM_ROLE =+ 'lobe-creds usage: always list before creating; never print secret values.\n'.repeat(30);+const SKILL_CONTENT = '# PowerShell\n\nUse pwsh for all Windows automation tasks.\n'.repeat(30);+const RESOURCE_TREE = '<resources skill="PowerShell">\n- scripts/run.ps1\n</resources>';++const credsManifest = {+ api: [{ description: 'List credentials', name: 'listCreds' }],+ identifier: 'lobe-creds',+ meta: { title: 'Creds' },+ systemRole: CREDS_SYSTEM_ROLE,+ type: 'builtin',+} as unknown as LobeToolManifest;++const powershellSkill: SkillMeta = {+ activated: true,+ content: SKILL_CONTENT,+ description: 'Run PowerShell',+ identifier: 'powershell',+ name: 'PowerShell',+};++const now = Date.now();++const activateToolsMessages = (): UIChatMessage[] =>+ [+ { content: 'help me manage creds', createdAt: now, id: 'u1', role: 'user', updatedAt: now },+ {+ content: '',+ createdAt: now,+ id: 'a1',+ role: 'assistant',+ tools: [+ {+ apiName: 'activateTools',+ arguments: '{"identifiers":["lobe-creds"]}',+ id: 'call_activate_1',+ identifier: 'lobe-activator',+ type: 'builtin',+ },+ ],+ updatedAt: now,+ },+ {+ content: `Successfully activated tools:\n\n## Creds (lobe-creds)\n${CREDS_SYSTEM_ROLE}\n\nAvailable APIs:\n- **listCreds**: List credentials`,+ createdAt: now,+ id: 't1',+ plugin: {+ apiName: 'activateTools',+ arguments: '{"identifiers":["lobe-creds"]}',+ identifier: 'lobe-activator',+ type: 'builtin',+ },+ pluginState: {+ activatedSkills: [],+ activatedTools: [{ apiCount: 1, identifier: 'lobe-creds', name: 'Creds' }],+ alreadyActive: [],+ notFound: [],+ },+ role: 'tool',+ tool_call_id: 'call_activate_1',+ updatedAt: now,+ },+ { content: 'now list my creds', createdAt: now, id: 'u2', role: 'user', updatedAt: now },+ ] as unknown as UIChatMessage[];++const activateSkillMessages = (): UIChatMessage[] =>+ [+ { content: 'run a pwsh script', createdAt: now, id: 'u1', role: 'user', updatedAt: now },+ {+ content: '',+ createdAt: now,+ id: 'a1',+ role: 'assistant',+ tools: [+ {+ apiName: 'activateSkill',+ arguments: '{"name":"PowerShell"}',+ id: 'call_skill_1',+ identifier: 'lobe-skills',+ type: 'builtin',+ },+ ],+ updatedAt: now,+ },+ {+ content: `${SKILL_CONTENT}\n\n${RESOURCE_TREE}`,+ createdAt: now,+ id: 't1',+ plugin: {+ apiName: 'activateSkill',+ arguments: '{"name":"PowerShell"}',+ identifier: 'lobe-skills',+ type: 'builtin',+ },+ pluginState: { hasResources: true, name: 'PowerShell', source: 'user' },+ role: 'tool',+ tool_call_id: 'call_skill_1',+ updatedAt: now,+ },+ { content: 'go ahead', createdAt: now, id: 'u2', role: 'user', updatedAt: now },+ ] as unknown as UIChatMessage[];++const createParams = (overrides?: Partial<MessagesEngineParams>): MessagesEngineParams => ({+ capabilities: { isCanUseFC: () => true },+ enableSystemDate: false,+ messages: [],+ model: 'gpt-4',+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ ...overrides,+});++/** Count how many times `needle` appears across every message content in the payload. */+const countInPayload = (messages: any[], needle: string) => {+ const haystack = messages+ .map((m) => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content)))+ .join('\n<<<message-boundary>>>\n');+ return haystack.split(needle).length - 1;+};++describe('MessagesEngine β activation result trimming (LOBE-5684)', () => {+ describe('activateTools', () => {+ it('should carry an activated manifest systemRole exactly once when injected', async () => {+ const engine = new MessagesEngine(+ createParams({+ messages: activateToolsMessages(),+ toolsConfig: { manifests: [credsManifest], tools: ['lobe-creds'] },+ }),+ );++ const result = await engine.process();++ expect(countInPayload(result.messages, CREDS_SYSTEM_ROLE)).toBe(1);+ // The single copy lives in the system prompt, not the tool result.+ const systemMessage = result.messages.find((m) => m.role === 'system');+ expect(systemMessage?.content).toContain(CREDS_SYSTEM_ROLE);+ const toolMessage = result.messages.find((m) => m.role === 'tool');+ expect(toolMessage?.content).toContain('Successfully activated tools: lobe-creds.listCreds.');+ expect(toolMessage?.content).toContain('in the system prompt');+ });++ it('should keep the tool result as the single channel when the manifest is not injected', async () => {+ const engine = new MessagesEngine(+ createParams({ messages: activateToolsMessages(), toolsConfig: { tools: [] } }),+ );++ const result = await engine.process();++ expect(countInPayload(result.messages, CREDS_SYSTEM_ROLE)).toBe(1);+ const toolMessage = result.messages.find((m) => m.role === 'tool');+ expect(toolMessage?.content).toContain(CREDS_SYSTEM_ROLE);+ });++ it('should not trim when the model does not support function calling', async () => {+ const engine = new MessagesEngine(+ createParams({+ capabilities: { isCanUseFC: () => false },+ messages: activateToolsMessages(),+ toolsConfig: { manifests: [credsManifest], tools: ['lobe-creds'] },+ }),+ );++ const result = await engine.process();++ // No FC β ToolSystemRoleProvider injects nothing β the tool result stays+ // the single carrier of the document.+ expect(countInPayload(result.messages, CREDS_SYSTEM_ROLE)).toBe(1);+ });+ });++ describe('activateSkill', () => {+ it('should carry an activated skill content exactly once when injected', async () => {+ const engine = new MessagesEngine(+ createParams({+ messages: activateSkillMessages(),+ skillsConfig: { enabledSkills: [powershellSkill] },+ }),+ );++ const result = await engine.process();++ expect(countInPayload(result.messages, SKILL_CONTENT)).toBe(1);+ const systemMessage = result.messages.find((m) => m.role === 'system');+ expect(systemMessage?.content).toContain(SKILL_CONTENT);+ const toolMessage = result.messages.find((m) => m.role === 'tool');+ expect(toolMessage?.content).toContain('Skill "PowerShell" activated');+ // The resource tree is NOT part of the injected content β it must survive.+ expect(toolMessage?.content).toContain(RESOURCE_TREE);+ });++ it('should keep the tool result as the single channel for non-injected skills', async () => {+ const engine = new MessagesEngine(+ createParams({+ messages: activateSkillMessages(),+ skillsConfig: {+ enabledSkills: [{ ...powershellSkill, activated: false, content: undefined }],+ },+ }),+ );++ const result = await engine.process();++ expect(countInPayload(result.messages, SKILL_CONTENT)).toBe(1);+ const toolMessage = result.messages.find((m) => m.role === 'tool');+ expect(toolMessage?.content).toContain(SKILL_CONTENT);+ });++ it('should not trim in chat mode where SkillContextProvider is disabled', async () => {+ const engine = new MessagesEngine(+ createParams({+ enableAgentMode: false,+ messages: activateSkillMessages(),+ skillsConfig: { enabledSkills: [powershellSkill] },+ }),+ );++ const result = await engine.process();++ expect(countInPayload(result.messages, SKILL_CONTENT)).toBe(1);+ const toolMessage = result.messages.find((m) => m.role === 'tool');+ expect(toolMessage?.content).toContain(SKILL_CONTENT);+ });+ });++ it('should not trim when a system-replace agent document discards the injections', async () => {+ // AgentDocumentSystemReplaceInjector replaces the whole assembled system+ // message AFTER the providers appended the activation docs β the tool+ // result must stay the single content channel.+ const engine = new MessagesEngine(+ createParams({+ agentDocuments: [+ {+ content: 'You are a totally custom agent.',+ filename: 'persona.md',+ loadPosition: 'system-replace',+ },+ ],+ messages: activateToolsMessages(),+ toolsConfig: { manifests: [credsManifest], tools: ['lobe-creds'] },+ }),+ );++ const result = await engine.process();++ expect(countInPayload(result.messages, CREDS_SYSTEM_ROLE)).toBe(1);+ const toolMessage = result.messages.find((m) => m.role === 'tool');+ expect(toolMessage?.content).toContain(CREDS_SYSTEM_ROLE);+ // The replaced system message carries only the agent document (here folded+ // into the progressive index) β the provider injections are gone.+ const systemMessage = result.messages.find((m) => m.role === 'system');+ expect(systemMessage?.content).not.toContain(CREDS_SYSTEM_ROLE);+ expect(systemMessage?.content).toContain('persona.md');+ });++ it('should stay byte-stable across subsequent requests (prompt-cache friendly)', async () => {+ const params = createParams({+ messages: activateToolsMessages(),+ toolsConfig: { manifests: [credsManifest], tools: ['lobe-creds'] },+ });++ const first = await new MessagesEngine(params).process();+ const second = await new MessagesEngine(params).process();++ expect(second.messages).toEqual(first.messages);+ });+});diff --git a/packages/context-engine/src/processors/ActivationResultTrim.ts b/packages/context-engine/src/processors/ActivationResultTrim.tsnew file mode 100644index 00000000000..00e95e4bc04--- /dev/null+++ b/packages/context-engine/src/processors/ActivationResultTrim.ts@@ -0,0 +1,320 @@+import debug from 'debug';++import { BaseProcessor } from '../base/BaseProcessor';+import type { LobeToolManifest } from '../engine/tools/types';+import type { SkillMeta } from '../providers/SkillContextProvider';+import type { Message, PipelineContext, ProcessorOptions } from '../types';++declare module '../types' {+ interface PipelineContextMetadataOverrides {+ activationResultTrim?: {+ savedChars: number;+ trimmedMessages: number;+ };+ }+}++const log = debug('context-engine:processor:ActivationResultTrimProcessor');++/**+ * Wire-format tool identifiers of the activation tools. Literal copies of+ * `LobeActivatorIdentifier` (@lobechat/builtin-tool-activator) and+ * `SkillsIdentifier` (@lobechat/builtin-tool-skills) β both are frozen,+ * persisted in DB message rows, and not importable here without adding+ * tool-package deps to context-engine (same rationale as agent-runtime's+ * messageSelectors).+ */+const ACTIVATOR_IDENTIFIER = 'lobe-activator';+const SKILLS_IDENTIFIER = 'lobe-skills';++interface ActivatedToolState {+ apiCount?: number;+ identifier?: string;+ name?: string;+}++interface ActivatedSkillState {+ identifier?: string;+ name?: string;+}++export interface ActivationResultTrimConfig {+ /**+ * Manifests whose systemRole / API descriptions the ToolSystemRoleProvider+ * injects into the system prompt for this request. Must be computed with+ * `selectToolPromptManifests` under the provider's own enablement gates+ * (manifests present + function calling supported); pass an empty array when+ * the provider is disabled so nothing gets trimmed.+ */+ injectedManifests?: LobeToolManifest[];+ /**+ * Activated skills whose full content the SkillContextProvider injects into+ * the system prompt for this request. Must be computed with+ * `selectActivatedSkills` under the provider's own enablement gates (agent+ * mode + enabled skills present); pass an empty array when the provider is+ * disabled so nothing gets trimmed.+ */+ injectedSkills?: SkillMeta[];+}++/**+ * Trims dynamic-activation tool results whose full documentation is ALSO+ * injected into the system prompt, so each activated tool/skill document+ * reaches the LLM payload exactly once.+ *+ * Background (LOBE-5684): `activateTools` used to write the manifest+ * systemRole + API descriptions into its `role=tool` result, and once+ * activated the same manifest enters ToolSystemRoleProvider's system-prompt+ * injection on every subsequent request β permanently double-carrying the+ * document. The activator now returns a short confirmation at the source, but+ * persisted history from before that change still carries the full docs, and+ * `activateSkill` (plus the activator's skill fallback) still returns the full+ * SKILL.md body because the tool result is the only content channel for+ * non-injected skills β so this payload-boundary trim remains load-bearing for+ * both.+ *+ * The trim happens ONLY at the payload assembly boundary β DB/UI rows keep the+ * full activation result β and ONLY when the injection is confirmed for this+ * request (condition-gated via the shared select helpers): a dynamically+ * activated skill that is NOT injected keeps its tool result as the single+ * content channel. The replacement text is deterministic, so once a document+ * moves to the system prompt the trimmed history stays byte-stable across+ * requests and keeps the prompt-cache prefix reusable.+ *+ * Must run AFTER the flatten processors (assistantGroup / compressedGroup+ * hoist nested tool results back into `role: 'tool'` rows with+ * plugin/pluginState re-attached) and BEFORE ToolCallProcessor consumes the+ * plugin payloads.+ */+export class ActivationResultTrimProcessor extends BaseProcessor {+ readonly name = 'ActivationResultTrimProcessor';++ private injectedManifestsById: Map<string, LobeToolManifest>;+ private injectedSkillsByIdentifier: Map<string, SkillMeta>;+ private injectedSkillsByName: Map<string, SkillMeta>;++ constructor(config: ActivationResultTrimConfig, options: ProcessorOptions = {}) {+ super(options);+ this.injectedManifestsById = new Map(+ (config.injectedManifests ?? []).map((m) => [m.identifier, m]),+ );+ this.injectedSkillsByIdentifier = new Map(+ (config.injectedSkills ?? []).map((s) => [s.identifier, s]),+ );+ // activateSkill resolves names case-insensitively, so match the same way.+ this.injectedSkillsByName = new Map(+ (config.injectedSkills ?? []).map((s) => [s.name.toLowerCase(), s]),+ );+ }++ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {+ if (this.injectedManifestsById.size === 0 && this.injectedSkillsByIdentifier.size === 0) {+ return this.markAsExecuted(context);+ }++ // A `system-replace` agent document discarded the assembled system message+ // AFTER the providers appended their docs β the injections this trim+ // relies on never reached the final prompt, so the activation results stay+ // the single content channel and must be kept intact.+ if (context.metadata.agentDocumentSystemReplace?.replaced) {+ log('System message was replaced by an agent document, skipping trim');+ return this.markAsExecuted(context);+ }++ const clonedContext = this.cloneContext(context);+ let trimmedMessages = 0;+ let savedChars = 0;++ clonedContext.messages = clonedContext.messages.map((message) => {+ const trimmed = this.trimMessage(message);+ if (trimmed === undefined) return message;++ trimmedMessages += 1;+ savedChars += (message.content as string).length - trimmed.length;+ return { ...message, content: trimmed };+ });++ if (trimmedMessages > 0) {+ log('Trimmed %d activation result(s), saved %d chars', trimmedMessages, savedChars);+ }++ clonedContext.metadata.activationResultTrim = { savedChars, trimmedMessages };+ return this.markAsExecuted(clonedContext);+ }++ /** Returns the replacement content, or undefined when the message must stay untouched. */+ private trimMessage(message: Message): string | undefined {+ if (message.role !== 'tool') return undefined;+ if (typeof message.content !== 'string' || !message.content) return undefined;++ const plugin = message.plugin as { apiName?: string; identifier?: string } | undefined;+ if (!plugin) return undefined;++ if (plugin.identifier === ACTIVATOR_IDENTIFIER && plugin.apiName === 'activateTools') {+ return this.trimActivateToolsResult(message);+ }++ // Direct activateSkill calls arrive on the skills tool; the activator also+ // exposes the same API for identifier-based fallbacks.+ if (+ plugin.apiName === 'activateSkill' &&+ (plugin.identifier === SKILLS_IDENTIFIER || plugin.identifier === ACTIVATOR_IDENTIFIER)+ ) {+ return this.trimActivateSkillResult(message);+ }++ return undefined;+ }++ private findInjectedSkill(state: ActivatedSkillState): SkillMeta | undefined {+ const byIdentifier = state.identifier+ ? this.injectedSkillsByIdentifier.get(state.identifier)+ : undefined;+ if (byIdentifier) return byIdentifier;++ return state.name ? this.injectedSkillsByName.get(state.name.toLowerCase()) : undefined;+ }++ private trimActivateToolsResult(message: Message): string | undefined {+ const state = message.pluginState as+ | {+ activatedSkills?: ActivatedSkillState[];+ activatedTools?: ActivatedToolState[];+ alreadyActive?: string[];+ notFound?: string[];+ }+ | undefined;++ const activatedTools = Array.isArray(state?.activatedTools) ? state.activatedTools : [];+ const activatedSkills = Array.isArray(state?.activatedSkills)+ ? state.activatedSkills.filter(Boolean)+ : [];++ // Nothing was activated (pure already-active / not-found result) β the+ // content carries no document, leave it alone.+ if (activatedTools.length === 0 && activatedSkills.length === 0) return undefined;++ // Trim only when EVERY activated item is covered by a system-prompt+ // injection; the result content is a single blob, so a partially covered+ // activation must keep its full text as the only channel for the+ // uncovered items.+ const allToolsInjected = activatedTools.every(+ (tool) => tool.identifier && this.injectedManifestsById.has(tool.identifier),+ );+ const allSkillsInjected = activatedSkills.every((skill) => !!this.findInjectedSkill(skill));+ if (!allToolsInjected || !allSkillsInjected) return undefined;++ // Fallback-activated skills append their full activation content to the+ // blob, which may extend beyond the injected `skill.content` (resource+ // tree, project directory hint β same shape the direct activateSkill path+ // preserves). Locate each injected copy inside the blob and keep those+ // suffixes; when a copy cannot be located we cannot prove what extra+ // information the blob carries, so keep the full result untouched.+ let skillRemainders: string[] = [];+ if (activatedSkills.length > 0) {+ const extracted = this.extractFallbackSkillRemainders(+ message.content as string,+ activatedSkills,+ );+ if (!extracted) return undefined;+ skillRemainders = extracted;+ }++ const parts: string[] = [];++ // List the newly callable APIs (`identifier.apiName`) so the model knows+ // exactly which functions the activation added to the tools array.+ const activatedApiNames = activatedTools.flatMap((tool) => {+ const manifest = this.injectedManifestsById.get(tool.identifier!)!;+ return manifest.api.length > 0+ ? manifest.api.map((api) => `${tool.identifier}.${api.name}`)+ : [tool.identifier!];+ });+ if (activatedApiNames.length > 0) {+ parts.push(`Successfully activated tools: ${activatedApiNames.join(', ')}.`);+ }++ if (activatedSkills.length > 0) {+ const skillNames = activatedSkills.map((skill) => skill.name ?? skill.identifier);+ parts.push(`Activated skills: ${skillNames.join(', ')}.`);+ parts.push(...skillRemainders);+ }++ if (state?.alreadyActive?.length) {+ parts.push(`Already active: ${state.alreadyActive.join(', ')}.`);+ }+ if (state?.notFound?.length) {+ parts.push(`Not found: ${state.notFound.join(', ')}.`);+ }++ parts.push('Usage instructions for the activated items are in the system prompt.');++ return parts.join('\n');+ }++ /**+ * Locate each fallback-activated skill's injected content inside the+ * activateTools result blob (skill contents are appended in activation+ * order) and return the non-injected suffix that follows each copy, cut at+ * the next skill's content or the trailing `Already active:` / `Not found:`+ * sections. Returns undefined when any copy cannot be located.+ */+ private extractFallbackSkillRemainders(+ original: string,+ activatedSkills: ActivatedSkillState[],+ ): string[] | undefined {+ const positions: Array<{ end: number; start: number }> = [];+ let searchFrom = 0;++ for (const skill of activatedSkills) {+ const injected = this.findInjectedSkill(skill);+ // Coverage was already checked by the caller; bail defensively anyway.+ if (!injected?.content) return undefined;++ const start = original.indexOf(injected.content, searchFrom);+ if (start === -1) return undefined;++ const end = start + injected.content.length;+ positions.push({ end, start });+ searchFrom = end;+ }++ const remainders: string[] = [];+ for (const [index, position] of positions.entries()) {+ let to = index + 1 < positions.length ? positions[index + 1].start : original.length;+ // Matches the literal section labels ActivatorExecutionRuntime appends+ // after the skill contents.+ for (const label of ['\nAlready active:', '\nNot found:']) {+ const labelIndex = original.indexOf(label, position.end);+ if (labelIndex !== -1 && labelIndex < to) to = labelIndex;+ }++ const remainder = original.slice(position.end, to).trim();+ if (remainder) remainders.push(remainder);+ }++ return remainders;+ }++ private trimActivateSkillResult(message: Message): string | undefined {+ const state = message.pluginState as ActivatedSkillState | undefined;+ if (!state?.name && !state?.identifier) return undefined;++ const injected = this.findInjectedSkill(state);+ if (!injected?.content) return undefined;++ const original = message.content as string;+ const confirmation = `Skill "${state.name ?? injected.name}" activated. Its full instructions are available in the system prompt.`;++ // The activation result may carry extra sections beyond the injected body+ // (resource tree, project directory hint). When the result is the injected+ // content plus a suffix, keep that suffix β it is not in the system prompt.+ // On any other mismatch (e.g. the skill was edited after activation), drop+ // the stale copy entirely: the system prompt carries the current version.+ const remainder = original.startsWith(injected.content)+ ? original.slice(injected.content.length).trim()+ : '';++ return remainder ? `${confirmation}\n\n${remainder}` : confirmation;+ }+}diff --git a/packages/context-engine/src/processors/__tests__/ActivationResultTrim.test.ts b/packages/context-engine/src/processors/__tests__/ActivationResultTrim.test.tsnew file mode 100644index 00000000000..f82aecddb68--- /dev/null+++ b/packages/context-engine/src/processors/__tests__/ActivationResultTrim.test.ts@@ -0,0 +1,329 @@+import { describe, expect, it } from 'vitest';++import type { LobeToolManifest } from '../../engine/tools/types';+import type { SkillMeta } from '../../providers/SkillContextProvider';+import type { PipelineContext } from '../../types';+import { ActivationResultTrimProcessor } from '../ActivationResultTrim';++const CREDS_SYSTEM_ROLE = 'lobe-creds instructions: manage credentials carefully.\n'.repeat(20);+const SKILL_CONTENT = '# PowerShell Skill\n\nRun PowerShell commands safely.\n'.repeat(20);+const RESOURCE_TREE = '<resources skill="PowerShell">\n- scripts/run.ps1\n</resources>';++const credsManifest = {+ api: [+ { description: 'List credentials', name: 'listCreds' },+ { description: 'Create a credential', name: 'createCred' },+ ],+ identifier: 'lobe-creds',+ meta: { title: 'Creds' },+ systemRole: CREDS_SYSTEM_ROLE,+} as unknown as LobeToolManifest;++const powershellSkill: SkillMeta = {+ activated: true,+ content: SKILL_CONTENT,+ description: 'Run PowerShell',+ identifier: 'powershell',+ name: 'PowerShell',+};++const createContext = (messages: any[]): PipelineContext => ({+ initialState: { messages: [] },+ isAborted: false,+ messages,+ metadata: {},+});++const activateToolsMessage = (overrides?: Record<string, unknown>) => ({+ content: `Successfully activated tools:\n\n## Creds (lobe-creds)\n${CREDS_SYSTEM_ROLE}\n\nAvailable APIs:\n- **listCreds**: List credentials\n- **createCred**: Create a credential`,+ id: 'tool-1',+ plugin: { apiName: 'activateTools', identifier: 'lobe-activator' },+ pluginState: {+ activatedSkills: [],+ activatedTools: [{ apiCount: 2, identifier: 'lobe-creds', name: 'Creds' }],+ alreadyActive: [],+ notFound: [],+ },+ role: 'tool',+ tool_call_id: 'call-1',+ ...overrides,+});++const activateSkillMessage = (overrides?: Record<string, unknown>) => ({+ content: `${SKILL_CONTENT}\n\n${RESOURCE_TREE}`,+ id: 'tool-2',+ plugin: { apiName: 'activateSkill', identifier: 'lobe-skills' },+ pluginState: { hasResources: true, name: 'PowerShell', source: 'user' },+ role: 'tool',+ tool_call_id: 'call-2',+ ...overrides,+});++describe('ActivationResultTrimProcessor', () => {+ describe('activateTools results', () => {+ it('should trim the result to a short confirmation when the manifest is injected', async () => {+ const processor = new ActivationResultTrimProcessor({ injectedManifests: [credsManifest] });+ const result = await processor.process(createContext([activateToolsMessage()]));++ const content = result.messages[0].content as string;+ expect(content).not.toContain(CREDS_SYSTEM_ROLE);+ expect(content).toContain(+ 'Successfully activated tools: lobe-creds.listCreds, lobe-creds.createCred.',+ );+ expect(content).toContain('in the system prompt');+ expect(result.metadata.activationResultTrim?.trimmedMessages).toBe(1);+ expect(result.metadata.activationResultTrim?.savedChars).toBeGreaterThan(0);+ });++ it('should keep already-active and not-found details in the confirmation', async () => {+ const processor = new ActivationResultTrimProcessor({ injectedManifests: [credsManifest] });+ const result = await processor.process(+ createContext([+ activateToolsMessage({+ pluginState: {+ activatedTools: [{ apiCount: 2, identifier: 'lobe-creds', name: 'Creds' }],+ alreadyActive: ['github'],+ notFound: ['nonexistent'],+ },+ }),+ ]),+ );++ const content = result.messages[0].content as string;+ expect(content).toContain('Already active: github.');+ expect(content).toContain('Not found: nonexistent.');+ });++ it('should NOT trim when an activated tool is not injected into the system prompt', async () => {+ const processor = new ActivationResultTrimProcessor({ injectedManifests: [] });+ const original = activateToolsMessage();+ const result = await processor.process(createContext([original]));++ expect(result.messages[0].content).toBe(original.content);+ });++ it('should NOT trim when a fallback-activated skill is not injected', async () => {+ // activateTools content is a single blob; a partially covered activation+ // must keep the full text as the only channel for the uncovered skill.+ const processor = new ActivationResultTrimProcessor({ injectedManifests: [credsManifest] });+ const original = activateToolsMessage({+ pluginState: {+ activatedSkills: [{ name: 'agent-browser' }],+ activatedTools: [{ apiCount: 2, identifier: 'lobe-creds', name: 'Creds' }],+ },+ });+ const result = await processor.process(createContext([original]));++ expect(result.messages[0].content).toBe(original.content);+ });++ it('should trim fallback-activated skills when they are injected too', async () => {+ const processor = new ActivationResultTrimProcessor({+ injectedManifests: [credsManifest],+ injectedSkills: [powershellSkill],+ });+ const result = await processor.process(+ createContext([+ activateToolsMessage({+ content: `Successfully activated tools:\n\n## Creds (lobe-creds)\n${CREDS_SYSTEM_ROLE}\n${SKILL_CONTENT}`,+ pluginState: {+ activatedSkills: [{ name: 'PowerShell' }],+ activatedTools: [{ apiCount: 2, identifier: 'lobe-creds', name: 'Creds' }],+ },+ }),+ ]),+ );++ const content = result.messages[0].content as string;+ expect(content).not.toContain(CREDS_SYSTEM_ROLE);+ expect(content).not.toContain(SKILL_CONTENT);+ expect(content).toContain('Activated skills: PowerShell.');+ });++ it('should preserve a fallback-activated skill suffix beyond the injected content', async () => {+ // Resource tree / project directory hints are appended to the fallback+ // activation content but are NOT part of the injected skill.content.+ const processor = new ActivationResultTrimProcessor({+ injectedManifests: [credsManifest],+ injectedSkills: [powershellSkill],+ });+ const result = await processor.process(+ createContext([+ activateToolsMessage({+ content: `Successfully activated tools:\n\n## Creds (lobe-creds)\n${CREDS_SYSTEM_ROLE}\n${SKILL_CONTENT}\n\n${RESOURCE_TREE}\nAlready active: github`,+ pluginState: {+ activatedSkills: [{ name: 'PowerShell' }],+ activatedTools: [{ apiCount: 2, identifier: 'lobe-creds', name: 'Creds' }],+ alreadyActive: ['github'],+ },+ }),+ ]),+ );++ const content = result.messages[0].content as string;+ expect(content).not.toContain(SKILL_CONTENT);+ expect(content).toContain(RESOURCE_TREE);+ expect(content).toContain('Already active: github.');+ });++ it('should NOT trim when a fallback skill copy cannot be located in the blob', async () => {+ // If the blob's copy diverges from the injected content we cannot prove+ // what extra information it carries β keep the full result.+ const processor = new ActivationResultTrimProcessor({+ injectedManifests: [credsManifest],+ injectedSkills: [powershellSkill],+ });+ const original = activateToolsMessage({+ content: `Successfully activated tools:\n\n## Creds (lobe-creds)\n${CREDS_SYSTEM_ROLE}\nstale powershell content v1`,+ pluginState: {+ activatedSkills: [{ name: 'PowerShell' }],+ activatedTools: [{ apiCount: 2, identifier: 'lobe-creds', name: 'Creds' }],+ },+ });+ const result = await processor.process(createContext([original]));++ expect(result.messages[0].content).toBe(original.content);+ });++ it('should be byte-identical on results the activator already returns short', async () => {+ // ActivatorExecutionRuntime now emits this exact confirmation at the+ // source; the trim rebuilding the same bytes keeps history stable and+ // guards the two formats against drifting apart.+ const short = [+ 'Successfully activated tools: lobe-creds.listCreds, lobe-creds.createCred.',+ 'Usage instructions for the activated items are in the system prompt.',+ ].join('\n');+ const processor = new ActivationResultTrimProcessor({ injectedManifests: [credsManifest] });+ const result = await processor.process(+ createContext([activateToolsMessage({ content: short })]),+ );++ expect(result.messages[0].content).toBe(short);+ });++ it('should leave pure already-active results untouched', async () => {+ const processor = new ActivationResultTrimProcessor({ injectedManifests: [credsManifest] });+ const original = activateToolsMessage({+ content: 'Already active: lobe-creds',+ pluginState: { activatedTools: [], alreadyActive: ['lobe-creds'] },+ });+ const result = await processor.process(createContext([original]));++ expect(result.messages[0].content).toBe(original.content);+ });+ });++ describe('activateSkill results', () => {+ it('should trim the result and keep the non-injected suffix (resource tree)', async () => {+ const processor = new ActivationResultTrimProcessor({ injectedSkills: [powershellSkill] });+ const result = await processor.process(createContext([activateSkillMessage()]));++ const content = result.messages[0].content as string;+ expect(content).not.toContain(SKILL_CONTENT);+ expect(content).toContain('Skill "PowerShell" activated');+ expect(content).toContain(RESOURCE_TREE);+ });++ it('should match skills case-insensitively by name', async () => {+ const processor = new ActivationResultTrimProcessor({ injectedSkills: [powershellSkill] });+ const result = await processor.process(+ createContext([+ activateSkillMessage({ pluginState: { name: 'powershell', source: 'builtin' } }),+ ]),+ );++ expect(result.messages[0].content).not.toContain(SKILL_CONTENT);+ });++ it('should fully replace a stale result whose content no longer matches', async () => {+ // The skill was edited after activation β the system prompt carries the+ // current version, so the stale copy is dropped entirely.+ const processor = new ActivationResultTrimProcessor({ injectedSkills: [powershellSkill] });+ const result = await processor.process(+ createContext([activateSkillMessage({ content: 'old skill body v1' })]),+ );++ expect(result.messages[0].content).toBe(+ 'Skill "PowerShell" activated. Its full instructions are available in the system prompt.',+ );+ });++ it('should NOT trim a dynamically activated skill that is not injected', async () => {+ const processor = new ActivationResultTrimProcessor({+ injectedSkills: [{ ...powershellSkill, activated: false }].filter((s) => s.activated),+ });+ const original = activateSkillMessage();+ const result = await processor.process(createContext([original]));++ expect(result.messages[0].content).toBe(original.content);+ });++ it('should handle activator-issued activateSkill results', async () => {+ const processor = new ActivationResultTrimProcessor({ injectedSkills: [powershellSkill] });+ const result = await processor.process(+ createContext([+ activateSkillMessage({+ plugin: { apiName: 'activateSkill', identifier: 'lobe-activator' },+ }),+ ]),+ );++ expect(result.messages[0].content).not.toContain(SKILL_CONTENT);+ });+ });++ describe('safety', () => {+ it('should ignore non-tool messages and other tool results', async () => {+ const processor = new ActivationResultTrimProcessor({+ injectedManifests: [credsManifest],+ injectedSkills: [powershellSkill],+ });+ const messages = [+ { content: SKILL_CONTENT, id: 'u1', role: 'user' },+ {+ content: 'some other tool output',+ id: 't1',+ plugin: { apiName: 'listCreds', identifier: 'lobe-creds' },+ role: 'tool',+ },+ ];+ const result = await processor.process(createContext(messages));++ expect(result.messages[0].content).toBe(SKILL_CONTENT);+ expect(result.messages[1].content).toBe('some other tool output');+ });++ it('should skip non-string tool content', async () => {+ const processor = new ActivationResultTrimProcessor({ injectedSkills: [powershellSkill] });+ const original = activateSkillMessage({ content: [{ text: 'part', type: 'text' }] });+ const result = await processor.process(createContext([original]));++ expect(result.messages[0].content).toBe(original.content);+ });++ it('should skip trimming entirely when a system-replace document discarded the system prompt', async () => {+ const processor = new ActivationResultTrimProcessor({+ injectedManifests: [credsManifest],+ injectedSkills: [powershellSkill],+ });+ const original = activateToolsMessage();+ const context = createContext([original, activateSkillMessage()]);+ context.metadata.agentDocumentSystemReplace = { replaced: true };++ const result = await processor.process(context);++ expect(result.messages[0].content).toBe(original.content);+ expect(result.messages[1].content).toContain(SKILL_CONTENT);+ expect(result.metadata.activationResultTrim).toBeUndefined();+ });++ it('should be a no-op when nothing is injected', async () => {+ const processor = new ActivationResultTrimProcessor({});+ const original = activateToolsMessage();+ const result = await processor.process(createContext([original]));++ expect(result.messages[0]).toBe(original);+ expect(result.metadata.activationResultTrim).toBeUndefined();+ });+ });+});diff --git a/packages/context-engine/src/processors/index.ts b/packages/context-engine/src/processors/index.tsindex 9c598235b5e..bf491635e4e 100644--- a/packages/context-engine/src/processors/index.ts+++ b/packages/context-engine/src/processors/index.ts@@ -1,4 +1,8 @@// Transformer processors+export {+ type ActivationResultTrimConfig,+ ActivationResultTrimProcessor,+} from './ActivationResultTrim';export { AgentCouncilFlattenProcessor } from './AgentCouncilFlatten';export { CompressedGroupRoleTransformProcessor } from './CompressedGroupRoleTransform';export { DisabledToolCallFilter } from './DisabledToolCallFilter';diff --git a/packages/context-engine/src/providers/AgentDocumentInjector/SystemReplaceInjector.ts b/packages/context-engine/src/providers/AgentDocumentInjector/SystemReplaceInjector.tsindex c0056fb3c81..350fd008f55 100644--- a/packages/context-engine/src/providers/AgentDocumentInjector/SystemReplaceInjector.ts+++ b/packages/context-engine/src/providers/AgentDocumentInjector/SystemReplaceInjector.ts@@ -5,6 +5,20 @@ import type { PipelineContext, ProcessorOptions } from '../../types';import type { AgentContextDocument, AgentDocumentFilterContext } from './shared';import { combineDocuments, getDocumentsForPositions } from './shared';+declare module '../../types' {+ interface PipelineContextMetadataOverrides {+ /**+ * Set when a `system-replace` agent document discarded the assembled+ * system message. Downstream processors that rely on Phase 2 system-prompt+ * injections (e.g. ActivationResultTrimProcessor) must treat those+ * injections as absent.+ */+ agentDocumentSystemReplace?: {+ replaced: boolean;+ };+ }+}+const log = debug('context-engine:provider:AgentDocumentSystemReplaceInjector');export interface AgentDocumentSystemReplaceInjectorConfig extends AgentDocumentFilterContext {@@ -58,6 +72,8 @@ export class AgentDocumentSystemReplaceInjector extends BaseProcessor {clonedContext.messages.unshift(message as any);}+ clonedContext.metadata.agentDocumentSystemReplace = { replaced: true };+log('Replaced system message with %d agent documents', docs.length);return this.markAsExecuted(clonedContext);}diff --git a/packages/context-engine/src/providers/SkillContextProvider.ts b/packages/context-engine/src/providers/SkillContextProvider.tsindex f91bf326486..4f58ddc8e7a 100644--- a/packages/context-engine/src/providers/SkillContextProvider.ts+++ b/packages/context-engine/src/providers/SkillContextProvider.ts@@ -49,6 +49,17 @@ export interface SkillContextProviderConfig {enabledSkills?: SkillMeta[];}+/**+ * Select the activated skills whose full content gets injected into the system+ * prompt by SkillContextProvider.+ *+ * Exported so ActivationResultTrimProcessor can decide, with the exact same+ * predicate, whether an activateSkill tool result's full content is already+ * carried by the system prompt and can therefore be trimmed from history.+ */+export const selectActivatedSkills = (enabledSkills?: SkillMeta[]): SkillMeta[] =>+ (enabledSkills ?? []).filter((s) => s.activated && s.content);+/*** Skill Context Provider* Injects lightweight skill metadata into the system prompt so the LLM knows@@ -75,7 +86,7 @@ export class SkillContextProvider extends BaseSystemRoleProvider {}// Separate activated skills (inject content directly) from available skills (list only)- const activatedSkills = enabledSkills.filter((s) => s.activated && s.content);+ const activatedSkills = selectActivatedSkills(enabledSkills);const availableSkills = enabledSkills.filter((s) => !s.activated);const contentParts: string[] = [];diff --git a/packages/context-engine/src/providers/ToolSystemRole.ts b/packages/context-engine/src/providers/ToolSystemRole.tsindex 33bea181403..d9688c85ae9 100644--- a/packages/context-engine/src/providers/ToolSystemRole.ts+++ b/packages/context-engine/src/providers/ToolSystemRole.ts@@ -35,6 +35,17 @@ export interface ToolSystemRoleConfig {provider: string;}+/**+ * Select the manifests whose systemRole / API descriptions get injected into the+ * system prompt by ToolSystemRoleProvider.+ *+ * Exported so ActivationResultTrimProcessor can decide, with the exact same+ * predicate, whether an activation tool result's full documentation is already+ * carried by the system prompt and can therefore be trimmed from history.+ */+export const selectToolPromptManifests = (manifests?: LobeToolManifest[]): LobeToolManifest[] =>+ (manifests ?? []).filter((manifest) => manifest.api.length > 0 || manifest.systemRole);+/*** Tool System Role Provider* Responsible for injecting tool-related system roles for models that support tool calling@@ -92,20 +103,16 @@ export class ToolSystemRoleProvider extends BaseSystemRoleProvider {return undefined;}- const tools: Tool[] = manifests- .filter((manifest) => manifest.api.length > 0 || manifest.systemRole)- .map((manifest) => ({- apis: manifest.api.map(- (api): API => ({- desc: api.description,- name: this.toolNameResolver.generate(manifest.identifier, api.name, manifest.type),- }),- ),- description: manifest.meta?.description,- identifier: manifest.identifier,- name: manifest.meta?.title || manifest.identifier,- systemRole: manifest.systemRole,- }));+ const tools: Tool[] = selectToolPromptManifests(manifests).map((manifest) => ({+ apis: manifest.api.map((api): API => ({+ desc: api.description,+ name: this.toolNameResolver.generate(manifest.identifier, api.name, manifest.type),+ })),+ description: manifest.meta?.description,+ identifier: manifest.identifier,+ name: manifest.meta?.title || manifest.identifier,+ systemRole: manifest.systemRole,+ }));if (tools.length === 0) {log('No meaningful tools to inject (all manifests have empty APIs and no systemRole)');diff --git a/packages/context-engine/src/providers/index.ts b/packages/context-engine/src/providers/index.tsindex 49bc14d4a36..4a2a77db5b0 100644--- a/packages/context-engine/src/providers/index.ts+++ b/packages/context-engine/src/providers/index.ts@@ -37,13 +37,13 @@ export {formatSelectedToolsContext,SelectedToolInjector,} from './SelectedToolInjector';-export { SkillContextProvider } from './SkillContextProvider';+export { selectActivatedSkills, SkillContextProvider } from './SkillContextProvider';export { SystemDateProvider } from './SystemDateProvider';export { SystemRoleInjector } from './SystemRoleInjector';export { TaskManagerContextInjector } from './TaskManagerContextInjector';export { TodoInjector } from './TodoInjector';export { ToolDiscoveryProvider } from './ToolDiscoveryProvider';-export { ToolSystemRoleProvider } from './ToolSystemRole';+export { selectToolPromptManifests, ToolSystemRoleProvider } from './ToolSystemRole';export { TopicReferenceContextInjector } from './TopicReferenceContextInjector';export { UserMemoryInjector } from './UserMemoryInjector';