π€― 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): forward tools into compression budget on `call_llm` (#14837)
Arvin Xu8ca3f9a3721c
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex 1d0eb01ae36..7dd609f88fb 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -363,11 +363,19 @@ export class GeneralChatAgent implements Agent {/*** Proceed to the next LLM call, inserting compression first when needed.*/- private toLLMCall(payload: GeneralAgentCallLLMInstructionPayload): AgentInstruction {+ private toLLMCall(+ payload: GeneralAgentCallLLMInstructionPayload,+ state: AgentState,+ ): AgentInstruction {const compressionEnabled = this.config.compressionConfig?.enabled ?? true;+ // Mirror RuntimeExecutors.callLlm: when state.forceFinish is set, the+ // executor strips all tools via buildStepToolDelta (deactivatedToolIds: ['*']),+ // so they must not count against the compression budget either β otherwise+ // 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,+ tools: state.forceFinish ? undefined : payload.tools,};if (compressionEnabled) {@@ -435,9 +443,12 @@ export class GeneralChatAgent implements Agent {case 'user_input': {// Check if context compression is enabled and needed before calling LLMconst compressionEnabled = this.config.compressionConfig?.enabled ?? true; // Default to enabled+ // Mirror RuntimeExecutors.callLlm: force-finish steps ship without tools,+ // so they must not count against the compression budget here either.const compressionOptions = {maxWindowToken: this.config.compressionConfig?.maxWindowToken,thresholdRatio: this.config.compressionConfig?.thresholdRatio,+ tools: state.forceFinish ? undefined : state.tools,};if (compressionEnabled) {@@ -620,13 +631,16 @@ export class GeneralChatAgent implements Agent {}// No pending tools, continue to call LLM with tool results- return this.toLLMCall({- messages: state.messages,- model: this.config.modelRuntimeConfig?.model,- parentMessageId,- provider: this.config.modelRuntimeConfig?.provider,- tools: state.tools,- } as GeneralAgentCallLLMInstructionPayload);+ return this.toLLMCall(+ {+ messages: state.messages,+ model: this.config.modelRuntimeConfig?.model,+ parentMessageId,+ provider: this.config.modelRuntimeConfig?.provider,+ tools: state.tools,+ } as GeneralAgentCallLLMInstructionPayload,+ state,+ );}case 'tools_batch_result': {@@ -655,13 +669,16 @@ export class GeneralChatAgent implements Agent {}// No pending tools, continue to call LLM with tool results- return this.toLLMCall({- messages: state.messages,- model: this.config.modelRuntimeConfig?.model,- parentMessageId,- provider: this.config.modelRuntimeConfig?.provider,- tools: state.tools,- } as GeneralAgentCallLLMInstructionPayload);+ return this.toLLMCall(+ {+ messages: state.messages,+ model: this.config.modelRuntimeConfig?.model,+ parentMessageId,+ provider: this.config.modelRuntimeConfig?.provider,+ tools: state.tools,+ } as GeneralAgentCallLLMInstructionPayload,+ state,+ );}case 'sub_agent_result': {@@ -669,13 +686,16 @@ export class GeneralChatAgent implements Agent {const { parentMessageId } = context.payload as SubAgentResultPayload;// Continue to call LLM with updated messages (task message is already in state)- return this.toLLMCall({- messages: state.messages,- model: this.config.modelRuntimeConfig?.model,- parentMessageId,- provider: this.config.modelRuntimeConfig?.provider,- tools: state.tools,- } as GeneralAgentCallLLMInstructionPayload);+ return this.toLLMCall(+ {+ messages: state.messages,+ model: this.config.modelRuntimeConfig?.model,+ parentMessageId,+ provider: this.config.modelRuntimeConfig?.provider,+ tools: state.tools,+ } as GeneralAgentCallLLMInstructionPayload,+ state,+ );}case 'sub_agents_batch_result': {@@ -699,13 +719,16 @@ export class GeneralChatAgent implements Agent {];// Continue to call LLM with updated messages (task messages are already in state)- return this.toLLMCall({- messages: messagesWithPrompt,- model: this.config.modelRuntimeConfig?.model,- parentMessageId,- provider: this.config.modelRuntimeConfig?.provider,- tools: state.tools,- } as GeneralAgentCallLLMInstructionPayload);+ return this.toLLMCall(+ {+ messages: messagesWithPrompt,+ model: this.config.modelRuntimeConfig?.model,+ parentMessageId,+ provider: this.config.modelRuntimeConfig?.provider,+ tools: state.tools,+ } as GeneralAgentCallLLMInstructionPayload,+ state,+ );}case 'compression_result': {diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.tsindex dd9232586d5..0d0b70a5617 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -150,6 +150,57 @@ describe('GeneralChatAgent', () => {expect(result).toEqual(expectCompressionInstruction(state.messages));});++ // LOBE-8973 Bug B: state.tools must feed into the compression budget,+ // otherwise large tool manifests (16-22K tokens observed on openrouter)+ // slip past the threshold and overflow the model context window.+ it('should fold state.tools into the compression budget on init', async () => {+ const compressionConfig = {+ enabled: true,+ maxWindowToken: 200_000,+ thresholdRatio: 0.5,+ };+ const messages = [+ {+ content: '',+ metadata: { usage: { totalOutputTokens: 50_000 } },+ role: 'assistant',+ },+ ] as any;+ const context = createMockContext('init', { model: 'gpt-4o-mini', provider: 'openai' });++ // Without tools: raw=50K, adjusted=62.5K vs 100K threshold β no compression.+ const agentNoTools = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ compressionConfig,+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });+ const noToolsResult = await agentNoTools.runner(context, createMockState({ messages }));+ expect((noToolsResult as any).type).toBe('call_llm');++ // With a chunky tool manifest (~66K tokens) total raw input is ~116K,+ // drift-adjusted ~145K, which crosses the 100K threshold.+ const bigTool = {+ function: {+ description: 'x'.repeat(400_000),+ name: 'big_tool',+ parameters: { properties: {}, type: 'object' },+ },+ type: 'function',+ };+ const agentWithTools = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ compressionConfig,+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });+ const withToolsResult = await agentWithTools.runner(+ context,+ createMockState({ messages, tools: [bigTool] as any }),+ );+ expect((withToolsResult as any).type).toBe('compress_context');+ });});describe('llm_result phase', () => {@@ -715,6 +766,66 @@ describe('GeneralChatAgent', () => {expect(result).toEqual(expectCompressionInstruction(state.messages));});+ // LOBE-8973 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 the+ // tool schemas push the budget over threshold and we burn an extra summarization+ // pass on tokens that won't be sent.+ it('should skip tools from compression budget on force-finish continuation', async () => {+ const compressionConfig = {+ enabled: true,+ maxWindowToken: 200_000,+ thresholdRatio: 0.5,+ };+ const messages = [+ { role: 'user', content: 'Hello' },+ {+ content: '',+ metadata: { usage: { totalOutputTokens: 50_000 } },+ role: 'assistant',+ },+ { role: 'tool', content: 'Result', tool_call_id: 'call-1' },+ ] as any;+ // Chunky tool manifest that alone is enough to push the request over the+ // compression threshold when counted in the budget.+ const bigTool = {+ function: {+ description: 'x'.repeat(400_000),+ name: 'big_tool',+ parameters: { properties: {}, type: 'object' },+ },+ type: 'function',+ };+ const context = createMockContext('tool_result', { parentMessageId: 'tool-msg-1' });++ // Sanity check: without forceFinish, the big tool manifest trips compression.+ const baselineAgent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ compressionConfig,+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });+ const baseline = await baselineAgent.runner(+ context,+ createMockState({ messages, tools: [bigTool] as any }),+ );+ expect((baseline as any).type).toBe('compress_context');++ // With forceFinish set, the executor will drop tools, so the agent must+ // ignore them in the compression check and go straight to call_llm.+ const forceFinishAgent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ compressionConfig,+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });+ const forced = await forceFinishAgent.runner(+ context,+ createMockState({ forceFinish: true, messages, tools: [bigTool] as any }),+ );+ expect((forced as any).type).toBe('call_llm');+ });+it('should return request_human_approve when there are pending tools', async () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },diff --git a/packages/agent-runtime/src/utils/tokenCounter.test.ts b/packages/agent-runtime/src/utils/tokenCounter.test.tsindex 0cad1ada0d5..085e1ffb288 100644--- a/packages/agent-runtime/src/utils/tokenCounter.test.ts+++ b/packages/agent-runtime/src/utils/tokenCounter.test.ts@@ -131,5 +131,37 @@ describe('tokenCounter', () => {expect(result.needsCompression).toBe(false);expect(result.currentTokenCount).toBe(0);});++ // LOBE-8973 Bug B: tool definitions also occupy the input window, so a+ // message payload that fits when tools are absent can overflow once tool+ // definitions are accounted for. Without this, compression only fires on+ // message size and leaves the tool budget to silently push the request+ // past the model's context window (openrouter "ExceededContextWindow").+ it('should count tool definition tokens against the budget', () => {+ const messages = [+ mkMsg({+ role: 'assistant',+ metadata: { usage: { totalOutputTokens: 50_000 } as any } as any,+ }),+ ];+ const options = { driftMultiplier: 1, maxWindowToken: 100_000, thresholdRatio: 0.6 };++ const withoutTools = shouldCompress(messages, options);+ expect(withoutTools.needsCompression).toBe(false);++ // A chunky tool manifest (~20K tokens of JSON) should push us over.+ const bigTool = {+ function: {+ description: 'x'.repeat(80_000),+ name: 'big_tool',+ parameters: { properties: {}, type: 'object' },+ },+ type: 'function',+ };+ const withTools = shouldCompress(messages, { ...options, tools: [bigTool] });++ expect(withTools.needsCompression).toBe(true);+ expect(withTools.currentTokenCount).toBeGreaterThan(withoutTools.currentTokenCount);+ });});});