π€― 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): stop rewriting tool results with placeholder values (#19809)
Arvin Xu6e5ffa4ad536
diff --git a/packages/context-engine/src/index.ts b/packages/context-engine/src/index.tsindex a1207331b12..aed619b2e2c 100644--- a/packages/context-engine/src/index.ts+++ b/packages/context-engine/src/index.ts@@ -43,6 +43,7 @@ export {getSlicedMessages,GroupMessageFlattenProcessor,HistoryTruncateProcessor,+ HYDRATED_TOOL_RESULTS,InputTemplateProcessor,MessageCleanupProcessor,MessageContentProcessor,diff --git a/packages/context-engine/src/processors/GroupRoleTransform.ts b/packages/context-engine/src/processors/GroupRoleTransform.tsindex 965122e413a..60ccf7946a4 100644--- a/packages/context-engine/src/processors/GroupRoleTransform.ts+++ b/packages/context-engine/src/processors/GroupRoleTransform.ts@@ -195,7 +195,11 @@ ${resultContent}return {...msg,content,- // Remove tool-related fields+ // The tool-related fields go away because the result is embedded in the+ // content now, but the content is still a verbatim tool result β keep the+ // provenance so PlaceholderVariablesProcessor does not start rewriting it+ // as if it were ordinary user prose.+ foldedToolResult: { apiName: msg.plugin?.apiName, identifier: msg.plugin?.identifier },plugin: undefined,role: 'user',tool_call_id: undefined,diff --git a/packages/context-engine/src/processors/PlaceholderVariables.ts b/packages/context-engine/src/processors/PlaceholderVariables.tsindex c5480377334..115a907adcc 100644--- a/packages/context-engine/src/processors/PlaceholderVariables.ts+++ b/packages/context-engine/src/processors/PlaceholderVariables.ts@@ -1,3 +1,4 @@+import { PLUGIN_SCHEMA_SEPARATOR } from '@lobechat/const/plugin';import { truncateSurrogateSafe } from '@lobechat/utils';import debug from 'debug';@@ -89,9 +90,70 @@ export const formatPlaceholderValues = (values: PlaceholderValueMap): Record<strObject.entries(values).map(([key, value]) => [key, resolvePlaceholderValue(value)]),);+/**+ * Tool results whose content is a platform-authored *template* that still needs+ * hydrating at the payload boundary.+ *+ * Every other tool result is a *record* of what a tool actually returned, and+ * must be handed to the model byte-for-byte. Substituting into it is wrong on+ * two counts:+ *+ * 1. It lies. An agent that runs `git diff` over a locale file holding+ * `"Updated {{time}}"` should see that file's real contents, not the+ * harness's clock.+ * 2. It breaks the prompt cache, permanently. The value moves between calls, so+ * the rewritten message diverges from the prefix the provider has already+ * cached, and every token after it is re-processed at the uncached price for+ * the rest of the run. That exact diff broke the prefix on 134 of 136 calls+ * of one operation β 43M re-processed tokens, $15 for a single run.+ *+ * Keyed by tool identifier β API names. This is the same activation surface+ * `ActivationResultTrimProcessor` recognises: an activated skill that is NOT+ * injected into the system prompt keeps its tool result as the only channel for+ * the SKILL.md body, and that body references `{{agent_id}}` / `{{topic_id}}`.+ */+export const HYDRATED_TOOL_RESULTS: Readonly<Record<string, readonly string[]>> = {+ // Literal copies of `LobeActivatorIdentifier` / `SkillsIdentifier` β same+ // rationale as ActivationResultTrimProcessor: both are frozen wire values,+ // and importing the tool packages here would invert the dependency.+ 'lobe-activator': ['activateTools', 'activateSkill'],+ 'lobe-skills': ['activateSkill'],+};++/**+ * Resolve a tool result's `(identifier, apiName)`.+ *+ * Prefers `foldedToolResult` β set when a role conversion moved the result into+ * another role's content (GroupRoleTransformProcessor turns another agent's+ * tool results into `role: 'user'` and drops `plugin`), then the structured+ * `plugin` field the flatten processors re-attach, and finally the wire name+ * (`identifier____apiName`) for payload-shaped messages carrying neither.+ */+const resolveToolIdentity = (message: any): { apiName?: string; identifier?: string } => {+ const folded = message?.foldedToolResult as { apiName?: string; identifier?: string } | undefined;+ if (folded) return { apiName: folded.apiName, identifier: folded.identifier };++ const plugin = message?.plugin as { apiName?: string; identifier?: string } | undefined;+ if (plugin?.identifier) return { apiName: plugin.apiName, identifier: plugin.identifier };++ const name = message?.name;+ if (typeof name === 'string' && name.includes(PLUGIN_SCHEMA_SEPARATOR)) {+ const [identifier, apiName] = name.split(PLUGIN_SCHEMA_SEPARATOR);+ return { apiName, identifier };+ }++ return {};+};+export interface PlaceholderVariablesConfig {/** Recursive parsing depth, default is 2 */depth?: number;+ /**+ * Tool identifier β API names whose `role: 'tool'` results get hydrated.+ * Defaults to {@link HYDRATED_TOOL_RESULTS}; every tool result outside it is+ * passed through untouched.+ */+ hydratedToolResults?: Readonly<Record<string, readonly string[]>>;/** Variable generators mapping, key is variable name, value is generator function */variableGenerators: Record<string, () => string>;}@@ -308,6 +370,29 @@ export class PlaceholderVariablesProcessor extends BaseProcessor {super(options);}+ /**+ * Whether a message's `{{...}}` tokens may be substituted.+ *+ * Everything the harness itself assembles β system prompt, injected blocks,+ * user and assistant turns β is fair game, so a user who writes `{{time}}`+ * still gets a live clock. Tool results are not: they are records, and only+ * the activation tools listed in {@link HYDRATED_TOOL_RESULTS} return a+ * template that still needs hydrating.+ *+ * `foldedToolResult` covers the results a role conversion has already moved+ * out of `role: 'tool'` β in a group conversation another agent's results+ * arrive as `role: 'user'`, and they are no less a record for it.+ */+ private shouldHydrate(message: any): boolean {+ if (message?.role !== 'tool' && !message?.foldedToolResult) return true;++ const { apiName, identifier } = resolveToolIdentity(message);+ if (!identifier || !apiName) return false;++ const allowlist = this.config.hydratedToolResults ?? HYDRATED_TOOL_RESULTS;+ return allowlist[identifier]?.includes(apiName) ?? false;+ }+protected async doProcess(context: PipelineContext): Promise<PipelineContext> {const clonedContext = this.cloneContext(context);@@ -344,6 +429,13 @@ export class PlaceholderVariablesProcessor extends BaseProcessor {for (let i = 0; i < clonedContext.messages.length; i++) {const message = clonedContext.messages[i];+ // A tool result outside the hydration allowlist is a verbatim record of+ // what the tool returned β never rewrite it. See HYDRATED_TOOL_RESULTS.+ if (!this.shouldHydrate(message)) {+ log('Skipping non-hydrated tool result at %d (name=%s)', i, message.name);+ continue;+ }+const contentPreview = buildContentPreview(message.content);log(diff --git a/packages/context-engine/src/processors/__tests__/GroupRoleTransform.test.ts b/packages/context-engine/src/processors/__tests__/GroupRoleTransform.test.tsindex aa175f41451..000c17f0266 100644--- a/packages/context-engine/src/processors/__tests__/GroupRoleTransform.test.ts+++ b/packages/context-engine/src/processors/__tests__/GroupRoleTransform.test.ts@@ -199,6 +199,13 @@ describe('GroupRoleTransformProcessor', () => {expect(result.messages[0].content).toContain('</tool_result>');expect(result.messages[0].tool_call_id).toBeUndefined();expect(result.messages[0].plugin).toBeUndefined();+ // The content is still a verbatim tool result even though the role is+ // now `user`; PlaceholderVariablesProcessor keys off this to avoid+ // rewriting it (and breaking the prompt-cache prefix) downstream.+ expect(result.messages[0].foldedToolResult).toEqual({+ apiName: 'getWeather',+ identifier: 'weather-plugin',+ });});it('should keep current agent tool messages unchanged', async () => {@@ -513,6 +520,7 @@ describe('GroupRoleTransformProcessor', () => {<tool_result id="call_weather_1" name="weather-plugin.getWeather">{"temperature": 22, "weather": "ε€δΊ", "humidity": 65}</tool_result>`,+ foldedToolResult: { apiName: 'getWeather', identifier: 'weather-plugin' },id: 'msg_4',plugin: undefined,role: 'user',diff --git a/packages/context-engine/src/processors/__tests__/PlaceholderVariables.toolMessage.test.ts b/packages/context-engine/src/processors/__tests__/PlaceholderVariables.toolMessage.test.tsindex 06630f0eac5..bce2e82737d 100644--- a/packages/context-engine/src/processors/__tests__/PlaceholderVariables.toolMessage.test.ts+++ b/packages/context-engine/src/processors/__tests__/PlaceholderVariables.toolMessage.test.ts@@ -7,10 +7,13 @@ import { PlaceholderVariablesProcessor } from '../PlaceholderVariables';* Regression for placeholder approach.** Confirms that PlaceholderVariablesProcessor does substitute `{{...}}` tokens- * inside `role: 'tool'` messages. If this test ever fails, it means the- * processor is silently skipping tool messages and the lobehub skill identity- * placeholders won't be filled in after the model calls+ * inside the `role: 'tool'` results of the *activation* tools. If this test ever+ * fails, it means the processor is silently skipping them and the lobehub skill+ * identity placeholders won't be filled in after the model calls* `lobe-activator.activateSkill('lobehub')`.+ *+ * The complementary half of the contract β every other tool result is passed+ * through verbatim β lives in `PlaceholderVariables.toolResultPassthrough.test.ts`.*/describe('PlaceholderVariablesProcessor β tool message substitution', () => {const buildContext = (messages: any[]): PipelineContext => ({@@ -72,7 +75,12 @@ describe('PlaceholderVariablesProcessor β tool message substitution', () => {});const ctx = buildContext([- { role: 'tool', tool_call_id: 't1', name: 'foo', content: 'agent={{agent_id}}' },+ {+ role: 'tool',+ tool_call_id: 't1',+ name: 'lobe-skills____activateSkill',+ content: 'agent={{agent_id}}',+ },]);const result = await processor.process(ctx);@@ -118,7 +126,12 @@ describe('PlaceholderVariablesProcessor β tool message substitution', () => {});const ctx = buildContext([- { role: 'tool', tool_call_id: 't1', name: 'foo', content: 'agent=[{{agent_id}}]' },+ {+ role: 'tool',+ tool_call_id: 't1',+ name: 'lobe-skills____activateSkill',+ content: 'agent=[{{agent_id}}]',+ },]);const result = await processor.process(ctx);diff --git a/packages/context-engine/src/processors/__tests__/PlaceholderVariables.toolResultPassthrough.test.ts b/packages/context-engine/src/processors/__tests__/PlaceholderVariables.toolResultPassthrough.test.tsnew file mode 100644index 00000000000..04058f462d0--- /dev/null+++ b/packages/context-engine/src/processors/__tests__/PlaceholderVariables.toolResultPassthrough.test.ts@@ -0,0 +1,210 @@+import { describe, expect, it } from 'vitest';++import type { PipelineContext } from '../../types';+import { HYDRATED_TOOL_RESULTS, PlaceholderVariablesProcessor } from '../PlaceholderVariables';++/**+ * Regression for the prompt-cache break caused by rewriting tool results.+ *+ * An agent ran `git diff` over `locales/en-US/chat.json`, whose i18n source+ * string is literally `"Updated {{time}}"`. The diff landed in a tool result+ * 66k tokens into the context, and because the processor substituted `{{time}}`+ * into *every* message on *every* call, that historical result changed its+ * seconds each time β diverging from the prefix the provider had already cached+ * and forcing all ~300k following tokens to be re-processed at the uncached+ * price. 134 of 136 calls broke, 43M tokens re-processed, $15.47 for one run+ * against a $0.59 baseline.+ *+ * A tool result is a record of what the tool returned. Only the activation+ * tools return a template that still needs hydrating.+ */+describe('PlaceholderVariablesProcessor β tool result passthrough', () => {+ const buildContext = (messages: any[]): PipelineContext => ({+ initialState: { messages: [] },+ isAborted: false,+ messages,+ metadata: {},+ });++ const timeGenerators = { time: () => new Date().toISOString(), topic_id: () => 'tpc_abc' };++ it('leaves a {{time}} that a tool genuinely returned untouched', async () => {+ const processor = new PlaceholderVariablesProcessor({ variableGenerators: timeGenerators });++ const diff = '+ "workingPanel.resources.updatedAt": "Updated {{time}}",';+ const ctx = buildContext([+ {+ role: 'tool',+ tool_call_id: 't1',+ name: 'lobe-local-system____runCommand',+ content: diff,+ },+ ]);++ const result = await processor.process(ctx);++ expect(result.messages[0].content).toBe(diff);+ });++ it('renders the same tool result identically across repeated calls', async () => {+ const diff = 'Updated {{time}} / {{timestamp}}';+ const render = async () => {+ const processor = new PlaceholderVariablesProcessor({+ variableGenerators: {+ time: () => new Date().toISOString(),+ timestamp: () => Date.now().toString(),+ },+ });+ const ctx = buildContext([+ {+ role: 'tool',+ tool_call_id: 't1',+ name: 'lobe-local-system____runCommand',+ content: diff,+ },+ ]);+ return (await processor.process(ctx)).messages[0].content;+ };++ // Byte-stability across calls is the whole point: an unstable byte here is+ // a broken cache prefix and a ~50x price on every token that follows.+ expect(await render()).toBe(await render());+ });++ it('identifies the tool from `plugin` when the wire name is absent', async () => {+ const processor = new PlaceholderVariablesProcessor({ variableGenerators: timeGenerators });++ const ctx = buildContext([+ {+ role: 'tool',+ tool_call_id: 't1',+ plugin: { apiName: 'runCommand', identifier: 'lobe-local-system' },+ content: 'at {{time}}',+ },+ {+ role: 'tool',+ tool_call_id: 't2',+ plugin: { apiName: 'activateSkill', identifier: 'lobe-skills' },+ content: 'topic {{topic_id}}',+ },+ ]);++ const result = await processor.process(ctx);++ expect(result.messages[0].content).toBe('at {{time}}');+ expect(result.messages[1].content).toBe('topic tpc_abc');+ });++ // Regression: GroupRoleTransformProcessor turns another agent's tool results+ // into `role: 'user'` and drops `plugin`, so a role check alone would classify+ // them as ordinary user prose and resume rewriting them β reintroducing the+ // exact break this processor exists to prevent, on the group path only.+ it('passes through a tool result that a role conversion folded into user', async () => {+ const processor = new PlaceholderVariablesProcessor({ variableGenerators: timeGenerators });++ const ctx = buildContext([+ {+ role: 'user',+ foldedToolResult: { apiName: 'runCommand', identifier: 'lobe-local-system' },+ content:+ '<speaker name="Dev" />\n<tool_result id="t1" name="runCommand">\nat {{time}}\n</tool_result>',+ },+ ]);++ const result = await processor.process(ctx);++ expect(result.messages[0].content).toContain('{{time}}');+ });++ it('still hydrates an activation result folded into user', async () => {+ const processor = new PlaceholderVariablesProcessor({ variableGenerators: timeGenerators });++ const ctx = buildContext([+ {+ role: 'user',+ foldedToolResult: { apiName: 'activateSkill', identifier: 'lobe-skills' },+ content: 'topic {{topic_id}}',+ },+ ]);++ const result = await processor.process(ctx);++ expect(result.messages[0].content).toBe('topic tpc_abc');+ });++ it('passes through a folded result whose tool identity was lost', async () => {+ const processor = new PlaceholderVariablesProcessor({ variableGenerators: timeGenerators });++ const ctx = buildContext([{ role: 'user', foldedToolResult: {}, content: 'at {{time}}' }]);++ const result = await processor.process(ctx);++ expect(result.messages[0].content).toBe('at {{time}}');+ });++ it('passes through a tool result that carries no identity at all', async () => {+ const processor = new PlaceholderVariablesProcessor({ variableGenerators: timeGenerators });++ const ctx = buildContext([+ { role: 'tool', tool_call_id: 't1', name: 'foo', content: 'at {{time}}' },+ ]);++ const result = await processor.process(ctx);++ expect(result.messages[0].content).toBe('at {{time}}');+ });++ it('still hydrates the system prompt and the user turn', async () => {+ const processor = new PlaceholderVariablesProcessor({ variableGenerators: timeGenerators });++ const ctx = buildContext([+ { role: 'system', content: 'topic {{topic_id}}' },+ // A user who types `{{time}}` wants a live clock β that path is untouched.+ { role: 'user', content: 'now is {{time}}' },+ { role: 'assistant', content: 'topic {{topic_id}}' },+ ]);++ const result = await processor.process(ctx);++ expect(result.messages[0].content).toBe('topic tpc_abc');+ expect(result.messages[1].content).not.toContain('{{time}}');+ expect(result.messages[2].content).toBe('topic tpc_abc');+ });++ it('honours a caller-supplied allowlist', async () => {+ const processor = new PlaceholderVariablesProcessor({+ hydratedToolResults: { 'lobe-local-system': ['runCommand'] },+ variableGenerators: { topic_id: () => 'tpc_abc' },+ });++ const ctx = buildContext([+ {+ role: 'tool',+ tool_call_id: 't1',+ name: 'lobe-local-system____runCommand',+ content: 'topic {{topic_id}}',+ },+ {+ role: 'tool',+ tool_call_id: 't2',+ name: 'lobe-skills____activateSkill',+ content: 'topic {{topic_id}}',+ },+ ]);++ const result = await processor.process(ctx);++ expect(result.messages[0].content).toBe('topic tpc_abc');+ // Not in the supplied allowlist β the default no longer applies.+ expect(result.messages[1].content).toBe('topic {{topic_id}}');+ });++ it('covers the activation surface ActivationResultTrimProcessor recognises', () => {+ // Both processors must agree on which tool results are platform-authored+ // documents; a skill activated but not injected keeps its tool result as the+ // only channel for a SKILL.md body that references {{agent_id}}.+ expect(HYDRATED_TOOL_RESULTS['lobe-activator']).toContain('activateTools');+ expect(HYDRATED_TOOL_RESULTS['lobe-activator']).toContain('activateSkill');+ expect(HYDRATED_TOOL_RESULTS['lobe-skills']).toContain('activateSkill');+ });+});diff --git a/packages/context-engine/src/processors/index.ts b/packages/context-engine/src/processors/index.tsindex bf491635e4e..02afaa98aad 100644--- a/packages/context-engine/src/processors/index.ts+++ b/packages/context-engine/src/processors/index.ts@@ -21,6 +21,7 @@ export { PlaceholderMessageFilterProcessor } from './PlaceholderMessageFilter';export {buildPlaceholderGenerators,formatPlaceholderValues,+ HYDRATED_TOOL_RESULTS,PlaceholderVariablesProcessor,renderPlaceholderTemplate,} from './PlaceholderVariables';diff --git a/packages/context-engine/src/types.ts b/packages/context-engine/src/types.tsindex 70e5c1e4b7e..ff28965e429 100644--- a/packages/context-engine/src/types.ts+++ b/packages/context-engine/src/types.ts@@ -48,6 +48,13 @@ export interface MessageToolCall {export interface Message {[key: string]: any;content: string | any[];+ /**+ * Set when a role conversion folded a tool result into another role's content+ * (see GroupRoleTransformProcessor). The message is no longer `role: 'tool'`,+ * but its content is still a verbatim record of what a tool returned, so+ * processors that key off the tool role must keep treating it as one.+ */+ foldedToolResult?: { apiName?: string; identifier?: string };role: string;}@@ -136,11 +143,7 @@ export enum ProcessorType {/** Legacy processor type - kept for backward compatibility */export type ProcessorTypeLegacy =- | 'injector'- | 'transformer'- | 'validator'- | 'optimizer'- | 'processor';+ 'injector' | 'transformer' | 'validator' | 'optimizer' | 'processor';/*** Token counter interface