🤯 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(agent-runtime): prevent repeated context compression (#18626)
Arvin Xu718a960fb34d
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex 5e601ae6dd3..7a9e68b3907 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -30,6 +30,10 @@ import { shouldCompress } from '../utils/tokenCounter';const TOOL_NOT_ALLOWED_CONTENT ='Tool execution blocked because the tool is not allowed in the current execution scope.';const TOOL_NOT_ALLOWED_REASON = 'tool_not_allowed';+// Leave 35% of the model window for server-side context engineering (system+// role, knowledge, memories, skills, etc.) and the model's completion. The+// initial 50% threshold still supplies the lower side of the hysteresis band.+const DEFAULT_RECOMPRESSION_THRESHOLD_RATIO = 0.65;/*** ChatAgent - The "Brain" of the chat agent@@ -496,6 +500,23 @@ export class GeneralChatAgent implements Agent {return undefined;}+ /**+ * Use hysteresis after the first compression. A freshly compressed context can+ * sit just below the ordinary threshold; applying the same threshold again+ * makes one small tool result trigger another compression before the model can+ * act on it. Keep the initial threshold conservative, then allow the compressed+ * context to grow to a higher watermark before compressing it again.+ */+ private getCompressionThresholdRatio(messages: any[]): number | undefined {+ const initialRatio = this.config.compressionConfig?.thresholdRatio;+ if (!this.findExistingSummary(messages)) return initialRatio;++ const configuredRecompressionRatio = this.config.compressionConfig?.recompressionThresholdRatio;+ if (configuredRecompressionRatio !== undefined) return configuredRecompressionRatio;++ return Math.max(initialRatio ?? 0, DEFAULT_RECOMPRESSION_THRESHOLD_RATIO);+ }+/*** Proceed to the next LLM call, inserting compression first when needed.*/@@ -514,7 +535,7 @@ export class GeneralChatAgent implements Agent {// we'd burn an extra summarization pass on tool tokens that won't be sent.const compressionOptions = {maxWindowToken: this.config.compressionConfig?.maxWindowToken,- thresholdRatio: this.config.compressionConfig?.thresholdRatio,+ thresholdRatio: this.getCompressionThresholdRatio(payloadWithAllowedToolNames.messages),tools: state.forceFinish ? undefined : payloadWithAllowedToolNames.tools,};@@ -585,7 +606,7 @@ export class GeneralChatAgent implements Agent {// so they must not count against the compression budget here either.const compressionOptions = {maxWindowToken: this.config.compressionConfig?.maxWindowToken,- thresholdRatio: this.config.compressionConfig?.thresholdRatio,+ thresholdRatio: this.getCompressionThresholdRatio(state.messages),tools: state.forceFinish ? undefined : this.getTools(state),};diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.tsindex 286ebe4a6b0..93e9ad378a2 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -929,6 +929,109 @@ describe('GeneralChatAgent', () => {expect(result).toEqual(expectCompressionInstruction(state.messages));});+ it('should not immediately recompress a recently compressed context near the initial threshold', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ compressionConfig: {+ enabled: true,+ maxWindowToken: 64_000,+ thresholdRatio: 0.5,+ },+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });+ const state = createMockState({+ messages: [+ {+ content: 'The work is complete; generate analysis.json next.',+ role: 'compressedGroup',+ },+ {+ content: '',+ metadata: { usage: { totalOutputTokens: 26_000 } },+ role: 'assistant',+ },+ { content: 'Directory contents', role: 'tool', tool_call_id: 'call-1' },+ ] as any,+ });++ const result = await agent.runner(+ createMockContext('tool_result', { parentMessageId: 'tool-msg-1' }),+ state,+ );++ expect((result as any).type).toBe('call_llm');+ });++ it('should recompress an existing summary before consuming reserved prompt headroom', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ compressionConfig: {+ enabled: true,+ maxWindowToken: 64_000,+ thresholdRatio: 0.5,+ },+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });+ const state = createMockState({+ messages: [+ { content: 'Existing summary', role: 'compressedGroup' },+ {+ content: '',+ metadata: { usage: { totalOutputTokens: 34_000 } },+ role: 'assistant',+ },+ { content: 'Large tool result', role: 'tool', tool_call_id: 'call-1' },+ ] as any,+ });++ const result = await agent.runner(+ createMockContext('tool_result', { parentMessageId: 'tool-msg-1' }),+ state,+ );++ expect(result).toEqual({+ payload: {+ currentTokenCount: expect.any(Number),+ existingSummary: 'Existing summary',+ messages: state.messages,+ },+ type: 'compress_context',+ });+ });++ it('should honor an explicit recompression threshold below the initial threshold', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ compressionConfig: {+ enabled: true,+ maxWindowToken: 64_000,+ recompressionThresholdRatio: 0.6,+ thresholdRatio: 0.8,+ },+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });+ const state = createMockState({+ messages: [+ { content: 'Existing summary', role: 'compressedGroup' },+ {+ content: '',+ metadata: { usage: { totalOutputTokens: 32_000 } },+ role: 'assistant',+ },+ ] as any,+ });++ const result = await agent.runner(+ createMockContext('tool_result', { parentMessageId: 'tool-msg-1' }),+ state,+ );++ expect((result as any).type).toBe('compress_context');+ });+// follow-up: when state.forceFinish is set, RuntimeExecutors strips// every tool before the LLM call (buildStepToolDelta returns deactivatedToolIds// ['*']). The compression budget must mirror that stripping — otherwise thediff --git a/packages/agent-runtime/src/types/generalAgent.ts b/packages/agent-runtime/src/types/generalAgent.tsindex a5c3646d757..16ce12ff488 100644--- a/packages/agent-runtime/src/types/generalAgent.ts+++ b/packages/agent-runtime/src/types/generalAgent.ts@@ -92,6 +92,8 @@ export interface GeneralAgentConfig {enabled?: boolean;/** Model's max context window token count (default: 128k) */maxWindowToken?: number;+ /** Explicit threshold after a compression summary exists; default 0.65 reserves prompt headroom. */+ recompressionThresholdRatio?: number;/** Threshold ratio for triggering compression (default: 0.5) */thresholdRatio?: number;};