From d87dd573eff736bbfb2f499f49c044ba9488b08f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 14 Jan 2026 16:23:15 -0800 Subject: [PATCH 1/8] feat: error for large files with informative message rather than truncating --- extensions/cli/src/compaction.ts | 16 +++++++++++----- extensions/cli/src/tools/readFile.ts | 27 +++++++++++++++------------ 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/extensions/cli/src/compaction.ts b/extensions/cli/src/compaction.ts index c52ba0147..692ef19be 100644 --- a/extensions/cli/src/compaction.ts +++ b/extensions/cli/src/compaction.ts @@ -28,6 +28,11 @@ export interface CompactionOptions { systemMessageTokens?: number; } +const COMPACTION_PROMPT = + "Please provide a concise summary of our conversation so far, capturing the key context, decisions made, and current state. Format this as a single comprehensive message that preserves all important information needed to continue our work. You do not need to recap the system message, as this will remain. Make sure it is clear what the current stream of work was at the very end prior to compaction so that you can continue exactly where you left off without missing any information."; + +const COMPACTION_PROMPT_TOKENS = 150; // rough generous token count of ^ + /** * Compacts a chat history into a summarized form * @param chatHistory The current chat history to compact @@ -47,8 +52,7 @@ export async function compactChatHistory( const compactionPrompt: ChatHistoryItem = { message: { role: "user" as const, - content: - "Please provide a concise summary of our conversation so far, capturing the key context, decisions made, and current state. Format this as a single comprehensive message that preserves all important information needed to continue our work. You do not need to recap the system message, as this will remain. Make sure it is clear what the current stream of work was at the very end prior to compaction so that you can continue exactly where you left off without missing any information.", + content: COMPACTION_PROMPT, }, contextItems: [], }; @@ -67,13 +71,15 @@ export async function compactChatHistory( (item) => item.message.role === "system", ); - // Account for system message (if not already in history) AND safety buffer - const SAFETY_BUFFER = 100; + // Account for system message (if not already in history) AND compaction prompt const systemMessageReservation = hasSystemMessageInHistory ? 0 : systemMessageTokens; const availableForInput = - contextLimit - reservedForOutput - systemMessageReservation - SAFETY_BUFFER; + contextLimit - + reservedForOutput - + systemMessageReservation - + COMPACTION_PROMPT_TOKENS; // Check if we need to prune to fit within context while ( diff --git a/extensions/cli/src/tools/readFile.ts b/extensions/cli/src/tools/readFile.ts index bde647a07..9fa2c1630 100644 --- a/extensions/cli/src/tools/readFile.ts +++ b/extensions/cli/src/tools/readFile.ts @@ -3,10 +3,7 @@ import * as fs from "fs"; import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js"; import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; -import { - parseEnvNumber, - truncateByLinesAndChars, -} from "../util/truncateOutput.js"; +import { parseEnvNumber } from "../util/truncateOutput.js"; import { formatToolArgument } from "./formatters.js"; import { Tool } from "./types.js"; @@ -82,20 +79,26 @@ export const readFileTool: Tool = { } const realPath = fs.realpathSync(filepath); const content = fs.readFileSync(realPath, "utf-8"); - // Mark this file as read for the edit tool - markFileAsRead(realPath); const maxLines = getReadFileMaxLines(); const maxChars = getReadFileMaxChars(); + const lineCount = content.split("\n").length; + const charCount = content.length; - const { output: truncatedContent, wasTruncated } = - truncateByLinesAndChars(content, maxLines, maxChars, "file content"); - - if (wasTruncated) { - return `Content of ${filepath} (truncated):\n${truncatedContent}`; + if (charCount > maxChars || lineCount > maxLines) { + throw new ContinueError( + ContinueErrorReason.FileTooLarge, + `File is too large to read: ${filepath} (${charCount.toLocaleString()} characters, ${lineCount.toLocaleString()} lines). ` + + `Maximum allowed: ${maxChars.toLocaleString()} characters or ${maxLines.toLocaleString()} lines. ` + + `To adjust these limits, set CONTINUE_CLI_READ_FILE_MAX_OUTPUT_CHARS or CONTINUE_CLI_READ_FILE_MAX_OUTPUT_LINES environment variables. ` + + `Alternatively, use shell commands like 'head', 'tail', 'sed', or 'grep' to read targeted parts of the file.`, + ); } - return `Content of ${filepath}:\n${truncatedContent}`; + // Mark this file as read for the edit tool + markFileAsRead(realPath); + + return `Content of ${filepath}:\n${content}`; } catch (error) { if (error instanceof ContinueError) { throw error; From d18c6f04ad6ca518f849a78ab6cb8938e8ea1c24 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 14 Jan 2026 17:51:10 -0800 Subject: [PATCH 2/8] fix: compaction updates part 2 --- extensions/cli/src/commands/chat.ts | 31 +++---- .../cli/src/ui/hooks/useChat.compaction.ts | 92 ++++--------------- 2 files changed, 30 insertions(+), 93 deletions(-) diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index 6ee33737d..79a8d9aac 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -34,7 +34,6 @@ import { prependPrompt } from "../util/promptProcessor.js"; import { calculateContextUsagePercentage, countChatHistoryTokens, - shouldAutoCompact, } from "../util/tokenizer.js"; import { ExtendedCommandOptions } from "./BaseCommandOptions.js"; @@ -363,25 +362,17 @@ async function processMessage( telemetryService.logUserPrompt(userInput.length, userInput); // Check if auto-compacting is needed BEFORE adding user message - // Note: This is a preliminary check without tools/systemMessage context. - // The streaming path performs a more accurate check with full context. - if ( - shouldAutoCompact({ - chatHistory: services.chatHistory.getHistory(), - model, - }) - ) { - const newIndex = await handleAutoCompaction( - chatHistory, - model, - llmApi, - isHeadless, - format, - ); - if (newIndex !== null) { - compactionIndex = newIndex; - // Service already updated in handleAutoCompaction via setHistory - } + // The handleAutoCompaction function decides whether compaction is actually needed + const autoCompactionResult = await handleAutoCompaction( + chatHistory, + model, + llmApi, + isHeadless, + format, + ); + if (autoCompactionResult !== null) { + compactionIndex = autoCompactionResult; + // Service already updated in handleAutoCompaction via setHistory } // Add user message to history AFTER potential compaction diff --git a/extensions/cli/src/ui/hooks/useChat.compaction.ts b/extensions/cli/src/ui/hooks/useChat.compaction.ts index 8b6c3b90a..1df84cfc3 100644 --- a/extensions/cli/src/ui/hooks/useChat.compaction.ts +++ b/extensions/cli/src/ui/hooks/useChat.compaction.ts @@ -2,9 +2,9 @@ import type { ChatHistoryItem, Session } from "core/index.js"; import { compactChatHistory } from "../../compaction.js"; import { updateSessionHistory } from "../../session.js"; +import { handleAutoCompaction as coreHandleAutoCompaction } from "../../stream/streamChatResponse.autoCompaction.js"; import { formatError } from "../../util/formatError.js"; import { logger } from "../../util/logger.js"; -import { shouldAutoCompact } from "../../util/tokenizer.js"; interface HandleCompactCommandOptions { chatHistory: ChatHistoryItem[]; @@ -131,85 +131,31 @@ export async function handleAutoCompaction({ compactionIndex: _compactionIndex, setChatHistory, setCompactionIndex, - abortController, + abortController: _abortController, }: HandleAutoCompactionOptions): Promise<{ currentChatHistory: ChatHistoryItem[]; currentCompactionIndex: number | null; }> { - try { - // Check if auto-compaction is needed using ChatHistoryItem directly - // Note: TUI mode doesn't have access to tools/systemMessage at this point, - // so we use a simplified check. The streaming path has full context. - if (!model || !shouldAutoCompact({ chatHistory, model })) { - return { - currentChatHistory: chatHistory, - currentCompactionIndex: _compactionIndex, - }; - } - - logger.info("Auto-compaction triggered for TUI mode"); - - // Compact the unified history - const result = await compactChatHistory(chatHistory, model, llmApi, { - abortController, - }); - - // Keep the system message and append the compaction summary - // This replaces the old messages with a summary to reduce context size - const systemMessage = chatHistory.find( - (item) => item.message.role === "system", - ); - - const compactedMessage: ChatHistoryItem = { - message: { - role: "assistant" as const, - content: result.compactionContent, - }, - contextItems: [], - conversationSummary: result.compactionContent, // Mark this as a summary - }; - - // Create new history with system message (if exists) and compaction summary - const updatedHistory: ChatHistoryItem[] = systemMessage - ? [systemMessage, compactedMessage] - : [compactedMessage]; - - // Add success message to the history that will be returned - const successMessage: ChatHistoryItem = { - message: { - role: "system", - content: "Chat history auto-compacted successfully.", - }, - contextItems: [], - }; - - const finalHistory = [...updatedHistory, successMessage]; - - setChatHistory(finalHistory); - setCompactionIndex(updatedHistory.length - 1); - - return { - currentChatHistory: finalHistory, - currentCompactionIndex: updatedHistory.length - 1, - }; - } catch (error) { - logger.error("Auto-compaction failed:", error); - - // Add error message - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: `Auto-compaction failed: ${formatError(error)}. Continuing without compaction...`, - }, - contextItems: [], - }, - ]); + // Delegate to core handleAutoCompaction which decides whether compaction is needed + // Note: TUI mode doesn't have access to tools/systemMessage at this point, + // so the core function uses a simplified check. + const result = await coreHandleAutoCompaction(chatHistory, model, llmApi, { + isHeadless: false, + callbacks: { + setChatHistory, + setCompactionIndex, + }, + }); + if (!result.wasCompacted) { return { currentChatHistory: chatHistory, - currentCompactionIndex: null, + currentCompactionIndex: _compactionIndex, }; } + + return { + currentChatHistory: result.chatHistory, + currentCompactionIndex: result.compactionIndex, + }; } From b4bc3aedaa2e44149a1898c609405ebb80ca91b2 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 21 Jan 2026 16:35:52 -0800 Subject: [PATCH 3/8] fix: account for different tokenizers --- extensions/cli/src/commands/chat.ts | 5 +- extensions/cli/src/compaction.test.ts | 6 ++ extensions/cli/src/compaction.ts | 4 +- .../streamChatResponse.autoCompaction.ts | 15 +++-- .../cli/src/ui/hooks/useContextPercentage.ts | 2 +- extensions/cli/src/util/tokenizer.test.ts | 64 ++++++++++++------- extensions/cli/src/util/tokenizer.ts | 64 +++++++++++++------ 7 files changed, 110 insertions(+), 50 deletions(-) diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index 79a8d9aac..ed36043b3 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -248,7 +248,10 @@ async function handleAutoCompaction( message: "Auto-compacting triggered", contextUsage: calculateContextUsagePercentage( - countChatHistoryTokens(services.chatHistory.getHistory()), + countChatHistoryTokens( + services.chatHistory.getHistory(), + model, + ), model, ) + "%", }) + "\n", diff --git a/extensions/cli/src/compaction.test.ts b/extensions/cli/src/compaction.test.ts index 24970cd48..6c3d6df4e 100644 --- a/extensions/cli/src/compaction.test.ts +++ b/extensions/cli/src/compaction.test.ts @@ -23,6 +23,12 @@ describe("compaction", () => { model: "test-model", } as ModelConfig; + const claudeModel: ModelConfig = { + name: "claude-3-5-sonnet", + provider: "anthropic", + model: "claude-3-5-sonnet-20241022", + } as ModelConfig; + const mockLlmApi = {} as BaseLlmApi; describe("findCompactionIndex", () => { diff --git a/extensions/cli/src/compaction.ts b/extensions/cli/src/compaction.ts index 692ef19be..d23591f85 100644 --- a/extensions/cli/src/compaction.ts +++ b/extensions/cli/src/compaction.ts @@ -83,11 +83,11 @@ export async function compactChatHistory( // Check if we need to prune to fit within context while ( - countChatHistoryTokens(historyForCompaction) > availableForInput && + countChatHistoryTokens(historyForCompaction, model) > availableForInput && historyToUse.length > 0 ) { logger.debug("Compaction history too long, pruning last message", { - tokenCount: countChatHistoryTokens(historyForCompaction), + tokenCount: countChatHistoryTokens(historyForCompaction, model), availableForInput, historyLength: historyToUse.length, }); diff --git a/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts b/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts index c93f97e78..3086de9eb 100644 --- a/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts +++ b/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts @@ -172,13 +172,16 @@ export async function handleAutoCompaction( typeof systemMessage === "string" ? systemMessage : await systemMessage; const { countChatHistoryItemTokens } = await import("../util/tokenizer.js"); - const systemMessageTokens = countChatHistoryItemTokens({ - message: { - role: "system", - content: resolvedSystemMessage, + const systemMessageTokens = countChatHistoryItemTokens( + { + message: { + role: "system", + content: resolvedSystemMessage, + }, + contextItems: [], }, - contextItems: [], - }); + model, + ); // Compact the history const result = await compactChatHistory(chatHistory, model, llmApi, { diff --git a/extensions/cli/src/ui/hooks/useContextPercentage.ts b/extensions/cli/src/ui/hooks/useContextPercentage.ts index 0d2388828..bc809a01b 100644 --- a/extensions/cli/src/ui/hooks/useContextPercentage.ts +++ b/extensions/cli/src/ui/hooks/useContextPercentage.ts @@ -28,7 +28,7 @@ export function useContextPercentage({ } // Calculate token count and percentage - const tokenCount = countChatHistoryTokens(chatHistory); + const tokenCount = countChatHistoryTokens(chatHistory, model); const percentage = calculateContextUsagePercentage(tokenCount, model); return { diff --git a/extensions/cli/src/util/tokenizer.test.ts b/extensions/cli/src/util/tokenizer.test.ts index f1361732e..e9cbe4d8f 100644 --- a/extensions/cli/src/util/tokenizer.test.ts +++ b/extensions/cli/src/util/tokenizer.test.ts @@ -8,7 +8,6 @@ import { calculateContextUsagePercentage, countChatHistoryItemTokens, countChatHistoryTokens, - countMessageTokens, countToolDefinitionTokens, getModelContextLimit, shouldAutoCompact, @@ -69,7 +68,13 @@ describe("tokenizer", () => { contextItems: [], }; - const tokenCount = countChatHistoryItemTokens(historyItem); + const model: ModelConfig = { + name: "test-model", + model: "test", + provider: "openai", + }; + + const tokenCount = countChatHistoryItemTokens(historyItem, model); expect(tokenCount).toBeGreaterThan(0); expect(tokenCount).toBe(5); // 3 content tokens + 2 role tokens }); @@ -86,7 +91,13 @@ describe("tokenizer", () => { contextItems: [], }; - const tokenCount = countChatHistoryItemTokens(historyItem); + const model: ModelConfig = { + name: "test-model", + model: "test", + provider: "openai", + }; + + const tokenCount = countChatHistoryItemTokens(historyItem, model); expect(tokenCount).toBe(1028); // 2 + 1024 + 2 role tokens }); @@ -109,7 +120,13 @@ describe("tokenizer", () => { contextItems: [], }; - const tokenCount = countChatHistoryItemTokens(historyItem); + const model: ModelConfig = { + name: "test-model", + model: "test", + provider: "openai", + }; + + const tokenCount = countChatHistoryItemTokens(historyItem, model); expect(tokenCount).toBeGreaterThan(20); }); @@ -129,7 +146,13 @@ describe("tokenizer", () => { ], }; - const tokenCount = countChatHistoryItemTokens(historyItem); + const model: ModelConfig = { + name: "test-model", + model: "test", + provider: "openai", + }; + + const tokenCount = countChatHistoryItemTokens(historyItem, model); // 2 (content) + 2 (role) + 4 (context content) + 3 (context name) + 5 (context overhead) = 16 expect(tokenCount).toBe(16); }); @@ -141,21 +164,6 @@ describe("tokenizer", () => { }); }); - describe("countMessageTokens (legacy)", () => { - it("should call countChatHistoryItemTokens", () => { - const historyItem: ChatHistoryItem = { - message: { - role: "user", - content: "Hello world", - }, - contextItems: [], - }; - - const tokenCount = countMessageTokens(historyItem); - expect(tokenCount).toBe(5); // Same as countChatHistoryItemTokens - }); - }); - describe("countChatHistoryTokens", () => { it("should count tokens for multiple messages", () => { const chatHistory: ChatHistoryItem[] = [ @@ -173,14 +181,26 @@ describe("tokenizer", () => { }, ]; - const tokenCount = countChatHistoryTokens(chatHistory); + const model: ModelConfig = { + name: "test-model", + model: "test", + provider: "openai", + }; + + const tokenCount = countChatHistoryTokens(chatHistory, model); expect(tokenCount).toBeGreaterThan(0); // Should include message overhead (3 * 3 = 9 tokens) expect(tokenCount).toBeGreaterThan(9); }); it("should handle empty chat history", () => { - const tokenCount = countChatHistoryTokens([]); + const model: ModelConfig = { + name: "test-model", + model: "test", + provider: "openai", + }; + + const tokenCount = countChatHistoryTokens([], model); expect(tokenCount).toBe(0); }); }); diff --git a/extensions/cli/src/util/tokenizer.ts b/extensions/cli/src/util/tokenizer.ts index 68f10c5f0..9bafeb2c1 100644 --- a/extensions/cli/src/util/tokenizer.ts +++ b/extensions/cli/src/util/tokenizer.ts @@ -23,12 +23,43 @@ export function getModelContextLimit(model: ModelConfig): number { ); } +// Importing a bunch of tokenizers can be very resource intensive (MB-scale per tokenizer) +// Using token counting APIs (e.g. for anthropic) can be complicated and unreliable in many environments +// So for now we will just use super fast gpt-tokenizer and apply safety buffers +// I'm using rough estimates from this article to apply safety buffers to common tokenizers +// which will have HIGHER token counts than gpt. Roughly using token ratio from article + 10% +// https://medium.com/@disparate-ai/not-all-tokens-are-created-equal-7347d549af4d +const ANTHROPIC_TOKEN_MULTIPLIER = 1.23; +const GEMINI_TOKEN_MULTIPLIER = 1.18; +const MISTRAL_TOKEN_MULTIPLIER = 1.26; + +function getAdjustedTokenCountFromModel( + baseTokens: number, + model: ModelConfig, +) { + let multiplier = 1; + const modelName = model.model?.toLowerCase() ?? ""; + if (modelName.includes("claude")) { + multiplier = ANTHROPIC_TOKEN_MULTIPLIER; + } else if (modelName.includes("gemini")) { + multiplier = GEMINI_TOKEN_MULTIPLIER; + } else if (modelName.includes("stral")) { + // devstral, mixtral, mistral, etc + multiplier = MISTRAL_TOKEN_MULTIPLIER; + } + return Math.ceil(baseTokens * multiplier); +} + /** * Count tokens in message content (string or multimodal array) */ -function countContentTokens(content: string | any[]): number { +function countContentTokens( + content: string | any[], + model: ModelConfig, +): number { if (typeof content === "string") { - return encode(content).length; + const count = encode(content).length; + return getAdjustedTokenCountFromModel(count, model); } if (Array.isArray(content)) { @@ -41,7 +72,7 @@ function countContentTokens(content: string | any[]): number { tokenCount += 1024; // Rough estimate for image tokens } } - return tokenCount; + return getAdjustedTokenCountFromModel(tokenCount, model); } return 0; @@ -91,6 +122,7 @@ function countToolOutputTokens( */ export function countChatHistoryItemTokens( historyItem: ChatHistoryItem, + model: ModelConfig, ): number { try { let tokenCount = 0; @@ -98,7 +130,7 @@ export function countChatHistoryItemTokens( const message = historyItem.message; // Count tokens in content - tokenCount += countContentTokens(message.content); + tokenCount += countContentTokens(message.content, model); // Add tokens for role (roughly 1-2 tokens) tokenCount += 2; @@ -154,26 +186,19 @@ export function countChatHistoryItemTokens( } } -/** - * Estimate the token count for a single message (legacy compatibility) - * @param message The message to count tokens for - * @returns The estimated token count - * @deprecated Use countChatHistoryItemTokens instead - */ -export function countMessageTokens(message: ChatHistoryItem): number { - return countChatHistoryItemTokens(message); -} - /** * Estimate the total token count for a chat history * @param chatHistory The chat history to count tokens for * @returns The estimated total token count */ -export function countChatHistoryTokens(chatHistory: ChatHistoryItem[]): number { +export function countChatHistoryTokens( + chatHistory: ChatHistoryItem[], + model: ModelConfig, +): number { let totalTokens = 0; for (const historyItem of chatHistory) { - totalTokens += countChatHistoryItemTokens(historyItem); + totalTokens += countChatHistoryItemTokens(historyItem, model); } // Add some overhead for message structure (roughly 3 tokens per message) @@ -291,6 +316,7 @@ export function countToolDefinitionTokens(tools: ChatCompletionTool[]): number { */ export interface TotalInputTokenParams { chatHistory: ChatHistoryItem[]; + model: ModelConfig; systemMessage?: string; tools?: ChatCompletionTool[]; } @@ -304,7 +330,7 @@ export interface TotalInputTokenParams { export function countTotalInputTokens(params: TotalInputTokenParams): number { const { chatHistory, systemMessage, tools } = params; - let totalTokens = countChatHistoryTokens(chatHistory); + let totalTokens = countChatHistoryTokens(chatHistory, params.model); // Add system message tokens if provided and not already in history if (systemMessage) { @@ -348,6 +374,7 @@ export function shouldAutoCompact(params: AutoCompactParams): boolean { chatHistory, systemMessage, tools, + model, }); const contextLimit = getModelContextLimit(model); const maxTokens = model.defaultCompletionOptions?.maxTokens || 0; @@ -373,7 +400,7 @@ export function shouldAutoCompact(params: AutoCompactParams): boolean { logger.debug("Context usage check", { inputTokens, - historyTokens: countChatHistoryTokens(chatHistory), + historyTokens: countChatHistoryTokens(chatHistory, model), systemTokens, toolTokens, contextLimit, @@ -428,6 +455,7 @@ export function validateContextLength(params: ValidateContextLengthParams): { chatHistory, systemMessage, tools, + model, }); const contextLimit = getModelContextLimit(model); const maxTokens = model.defaultCompletionOptions?.maxTokens || 0; From c754289118dec863a1dc6f802ad5347c370d8796 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 21 Jan 2026 17:37:17 -0800 Subject: [PATCH 4/8] feat: proportional output truncation for read and bash --- extensions/cli/src/compaction.ts | 11 +++ .../src/stream/streamChatResponse.helpers.ts | 9 ++- extensions/cli/src/tools/index.tsx | 10 ++- extensions/cli/src/tools/readFile.ts | 23 ++++-- .../cli/src/tools/runTerminalCommand.ts | 70 ++++++++++++----- extensions/cli/src/tools/types.ts | 11 ++- extensions/cli/src/util/tokenizer.test.ts | 76 +++++++++++-------- extensions/cli/src/util/tokenizer.ts | 35 +++++---- 8 files changed, 166 insertions(+), 79 deletions(-) diff --git a/extensions/cli/src/compaction.ts b/extensions/cli/src/compaction.ts index d23591f85..00c6ea3f5 100644 --- a/extensions/cli/src/compaction.ts +++ b/extensions/cli/src/compaction.ts @@ -10,6 +10,13 @@ import { getModelContextLimit, } from "./util/tokenizer.js"; +// Buffer cap for auto-compaction threshold calculation +// Threshold formula: contextLength - maxTokens - Min(maxTokens, AUTO_COMPACT_BUFFER_CAP) +export const AUTO_COMPACT_BUFFER_CAP = 15_000; + +// Default context length when model config doesn't specify one +export const DEFAULT_CONTEXT_LENGTH = 200_000; + export interface CompactionResult { compactedHistory: ChatHistoryItem[]; compactionIndex: number; @@ -65,6 +72,9 @@ export async function compactChatHistory( const maxTokens = model.defaultCompletionOptions?.maxTokens; const reservedForOutput = maxTokens === undefined ? Math.ceil(contextLimit * 0.35) : maxTokens; + // Additional buffer matching the auto-compaction threshold formula: + // contextLength - maxTokens - Min(maxTokens, 20k) + const compactionBuffer = Math.min(reservedForOutput, AUTO_COMPACT_BUFFER_CAP); // Check if system message is already in the history to avoid double-counting const hasSystemMessageInHistory = chatHistory.some( @@ -78,6 +88,7 @@ export async function compactChatHistory( const availableForInput = contextLimit - reservedForOutput - + compactionBuffer - systemMessageReservation - COMPACTION_PROMPT_TOKENS; diff --git a/extensions/cli/src/stream/streamChatResponse.helpers.ts b/extensions/cli/src/stream/streamChatResponse.helpers.ts index a60b10af4..205a76fe8 100644 --- a/extensions/cli/src/stream/streamChatResponse.helpers.ts +++ b/extensions/cli/src/stream/streamChatResponse.helpers.ts @@ -491,6 +491,10 @@ export async function executeStreamedToolCalls( }> { // Strategy: queue permissions (preserve order), then run approved tools in parallel. // If any permission is rejected, cancel the remaining tools in this batch. + // + // NOTE: parallelToolCallCount is passed to each tool so they can divide their + // output limits accordingly to avoid context overflow. Bash/Read do this for now + const parallelToolCallCount = preprocessedCalls.length; type IndexedCall = { index: number; call: PreprocessedToolCall }; const indexedCalls: IndexedCall[] = preprocessedCalls.map((call, index) => ({ @@ -574,7 +578,10 @@ export async function executeStreamedToolCalls( name: call.name, arguments: call.arguments, }); - const toolResult = await executeToolCall(call); + + const toolResult = await executeToolCall(call, { + parallelToolCallCount, + }); const entry: ToolResultWithStatus = { role: "tool", tool_call_id: call.id, diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index b6db81234..36246eb83 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -37,6 +37,7 @@ import { type Tool, type ToolCall, type ToolParametersSchema, + type ToolRunContext, ParameterSchema, PreprocessedToolCall, } from "./types.js"; @@ -206,6 +207,7 @@ export function convertMcpToolToContinueTool(mcpTool: MCPTool): Tool { export async function executeToolCall( toolCall: PreprocessedToolCall, + options: { parallelToolCallCount: number } = { parallelToolCallCount: 1 }, ): Promise { const startTime = Date.now(); @@ -213,16 +215,22 @@ export async function executeToolCall( logger.debug("Executing tool", { toolName: toolCall.name, arguments: toolCall.arguments, + parallelToolCallCount: options.parallelToolCallCount, }); // Track edits if Git AI is enabled (no-op if not enabled) await services.gitAiIntegration.trackToolUse(toolCall, "PreToolUse"); + const context: ToolRunContext = { + toolCallId: toolCall.id, + parallelToolCallCount: options.parallelToolCallCount, + }; + // IMPORTANT: if preprocessed args are present, uses preprocessed args instead of original args // Preprocessed arg names may be different const result = await toolCall.tool.run( toolCall.preprocessResult?.args ?? toolCall.arguments, - { toolCallId: toolCall.id }, + context, ); const duration = Date.now() - startTime; diff --git a/extensions/cli/src/tools/readFile.ts b/extensions/cli/src/tools/readFile.ts index 9fa2c1630..e66c5a12e 100644 --- a/extensions/cli/src/tools/readFile.ts +++ b/extensions/cli/src/tools/readFile.ts @@ -6,7 +6,7 @@ import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; import { parseEnvNumber } from "../util/truncateOutput.js"; import { formatToolArgument } from "./formatters.js"; -import { Tool } from "./types.js"; +import { Tool, ToolRunContext } from "./types.js"; // Output truncation defaults const DEFAULT_READ_FILE_MAX_CHARS = 100000; // ~25k tokens @@ -64,7 +64,10 @@ export const readFileTool: Tool = { ], }; }, - run: async (args: { filepath: string }): Promise => { + run: async ( + args: { filepath: string }, + context?: ToolRunContext, + ): Promise => { try { let { filepath } = args; if (filepath.startsWith("./")) { @@ -80,16 +83,26 @@ export const readFileTool: Tool = { const realPath = fs.realpathSync(filepath); const content = fs.readFileSync(realPath, "utf-8"); - const maxLines = getReadFileMaxLines(); - const maxChars = getReadFileMaxChars(); + // Divide limits by parallel tool call count to avoid context overflow + const parallelCount = context?.parallelToolCallCount ?? 1; + const baseMaxLines = getReadFileMaxLines(); + const baseMaxChars = getReadFileMaxChars(); + const maxLines = Math.floor(baseMaxLines / parallelCount); + const maxChars = Math.floor(baseMaxChars / parallelCount); const lineCount = content.split("\n").length; const charCount = content.length; if (charCount > maxChars || lineCount > maxLines) { + // Include note about single-tool limit when parallel calls reduce the limit + const parallelNote = + parallelCount > 1 + ? ` (Note: limit reduced due to ${parallelCount} parallel tool calls. Single-tool limit: ${baseMaxChars.toLocaleString()} characters or ${baseMaxLines.toLocaleString()} lines.)` + : ""; + throw new ContinueError( ContinueErrorReason.FileTooLarge, `File is too large to read: ${filepath} (${charCount.toLocaleString()} characters, ${lineCount.toLocaleString()} lines). ` + - `Maximum allowed: ${maxChars.toLocaleString()} characters or ${maxLines.toLocaleString()} lines. ` + + `Maximum allowed: ${maxChars.toLocaleString()} characters or ${maxLines.toLocaleString()} lines.${parallelNote} ` + `To adjust these limits, set CONTINUE_CLI_READ_FILE_MAX_OUTPUT_CHARS or CONTINUE_CLI_READ_FILE_MAX_OUTPUT_LINES environment variables. ` + `Alternatively, use shell commands like 'head', 'tail', 'sed', or 'grep' to read targeted parts of the file.`, ); diff --git a/extensions/cli/src/tools/runTerminalCommand.ts b/extensions/cli/src/tools/runTerminalCommand.ts index df8a8beea..061200d1b 100644 --- a/extensions/cli/src/tools/runTerminalCommand.ts +++ b/extensions/cli/src/tools/runTerminalCommand.ts @@ -15,10 +15,10 @@ import { truncateOutputFromStart, } from "../util/truncateOutput.js"; -import { Tool } from "./types.js"; +import { Tool, ToolRunContext } from "./types.js"; // Output truncation defaults -const DEFAULT_BASH_MAX_CHARS = 50000; +const DEFAULT_BASH_MAX_CHARS = 50000; // ~12.5k tokens const DEFAULT_BASH_MAX_LINES = 1000; function getBashMaxChars(): number { @@ -102,13 +102,23 @@ IMPORTANT: To edit files, use Edit/MultiEdit tools instead of bash commands (sed ], }; }, - run: async ({ - command, - timeout, - }: { - command: string; - timeout?: number; - }): Promise => { + run: async ( + { + command, + timeout, + }: { + command: string; + timeout?: number; + }, + context?: ToolRunContext, + ): Promise => { + // Divide limits by parallel tool call count to avoid context overflow + const parallelCount = context?.parallelToolCallCount ?? 1; + const baseMaxChars = getBashMaxChars(); + const baseMaxLines = getBashMaxLines(); + const maxChars = Math.floor(baseMaxChars / parallelCount); + const maxLines = Math.floor(baseMaxLines / parallelCount); + return new Promise((resolve, reject) => { // Use same shell logic as core implementation const { shell, args } = getShellCommand(command); @@ -131,6 +141,20 @@ IMPORTANT: To edit files, use Edit/MultiEdit tools instead of bash commands (sed TIMEOUT_MS = parseInt(process.env.TEST_TERMINAL_TIMEOUT, 10); } + /** + * Appends a note about reduced limits when parallel tool calls are in effect. + */ + const appendParallelLimitNote = (output: string): string => { + if (parallelCount > 1) { + return ( + output + + `\n\n(Note: output limit reduced due to ${parallelCount} parallel tool calls. ` + + `Single-tool limit: ${baseMaxChars.toLocaleString()} characters or ${baseMaxLines.toLocaleString()} lines.)` + ); + } + return output; + }; + const resetTimeout = () => { if (timeoutId) { clearTimeout(timeoutId); @@ -142,12 +166,14 @@ IMPORTANT: To edit files, use Edit/MultiEdit tools instead of bash commands (sed let output = stdout + (stderr ? `\nStderr: ${stderr}` : ""); output += `\n\n[Command timed out after ${TIMEOUT_MS / 1000} seconds of no output]`; - resolve( - truncateOutputFromStart(output, { - maxChars: getBashMaxChars(), - maxLines: getBashMaxLines(), - }).output, - ); + const truncationResult = truncateOutputFromStart(output, { + maxChars, + maxLines, + }); + const finalOutput = truncationResult.wasTruncated + ? appendParallelLimitNote(truncationResult.output) + : truncationResult.output; + resolve(finalOutput); }, TIMEOUT_MS); }; @@ -192,12 +218,14 @@ IMPORTANT: To edit files, use Edit/MultiEdit tools instead of bash commands (sed output = stdout + `\nStderr: ${stderr}`; } - resolve( - truncateOutputFromStart(output, { - maxChars: getBashMaxChars(), - maxLines: getBashMaxLines(), - }).output, - ); + const truncationResult = truncateOutputFromStart(output, { + maxChars, + maxLines, + }); + const finalOutput = truncationResult.wasTruncated + ? appendParallelLimitNote(truncationResult.output) + : truncationResult.output; + resolve(finalOutput); }); child.on("error", (error) => { diff --git a/extensions/cli/src/tools/types.ts b/extensions/cli/src/tools/types.ts index 544c6d970..fb8011ef1 100644 --- a/extensions/cli/src/tools/types.ts +++ b/extensions/cli/src/tools/types.ts @@ -32,13 +32,22 @@ export interface PreprocessToolCallResult { context?: { toolCallId: string }; } +export interface ToolRunContext { + toolCallId: string; + /** + * Number of tool calls being executed in parallel. + * Tools should divide their output limits by this number to avoid context overflow. + */ + parallelToolCallCount: number; +} + export interface Tool { name: string; displayName: string; description: string; parameters: ToolParametersSchema; preprocess?: (args: any) => Promise; - run: (args: any, context?: { toolCallId: string }) => Promise; + run: (args: any, context?: ToolRunContext) => Promise; readonly?: boolean; // Indicates if the tool is readonly isBuiltIn: boolean; evaluateToolCallPolicy?: ( diff --git a/extensions/cli/src/util/tokenizer.test.ts b/extensions/cli/src/util/tokenizer.test.ts index e9cbe4d8f..7c9d5c937 100644 --- a/extensions/cli/src/util/tokenizer.test.ts +++ b/extensions/cli/src/util/tokenizer.test.ts @@ -2,9 +2,13 @@ import { ModelConfig } from "@continuedev/config-yaml"; import type { ChatHistoryItem } from "core/index.js"; import { beforeEach, describe, expect, it, vi } from "vitest"; +import { + AUTO_COMPACT_BUFFER_CAP, + DEFAULT_CONTEXT_LENGTH, +} from "../compaction.js"; + import { logger } from "./logger.js"; import { - AUTO_COMPACT_THRESHOLD, calculateContextUsagePercentage, countChatHistoryItemTokens, countChatHistoryTokens, @@ -54,7 +58,7 @@ describe("tokenizer", () => { provider: "openai", }; - expect(getModelContextLimit(model)).toBe(200_000); + expect(getModelContextLimit(model)).toBe(DEFAULT_CONTEXT_LENGTH); }); }); @@ -249,8 +253,7 @@ describe("tokenizer", () => { it("should compact when input tokens exceed threshold with maxTokens", () => { const model = createModel(1000, 200); // 1000 context, 200 max output - // Available for input: 1000 - 200 = 800 - // Threshold: 800 * 0.8 = 640 + // Threshold: 1000 - 200 - min(200, 20k) = 1000 - 200 - 200 = 600 const chatHistory = createChatHistory(650); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); @@ -258,9 +261,8 @@ describe("tokenizer", () => { it("should not compact when input tokens are below threshold with maxTokens", () => { const model = createModel(1000, 200); // 1000 context, 200 max output - // Available for input: 1000 - 200 = 800 - // Threshold: 800 * 0.8 = 640 - const chatHistory = createChatHistory(600); // Below threshold + // Threshold: 1000 - 200 - min(200, 20k) = 600 + const chatHistory = createChatHistory(550); // Below threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(false); }); @@ -268,18 +270,17 @@ describe("tokenizer", () => { it("should use 35% default reservation when maxTokens is not set", () => { const model = createModel(1000); // No maxTokens // Reserved: 1000 * 0.35 = 350 - // Available for input: 1000 - 350 = 650 - // Threshold: 650 * 0.8 = 520 - const chatHistory = createChatHistory(530); // Above threshold + // Threshold: 1000 - 350 - min(350, 20k) = 1000 - 350 - 350 = 300 + const chatHistory = createChatHistory(350); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); }); it("should not compact when below default threshold without maxTokens", () => { const model = createModel(1000); // No maxTokens - // Available for input: 1000 - 350 = 650 - // Threshold: 650 * 0.8 = 520 - const chatHistory = createChatHistory(500); // Below threshold + // Reserved: 1000 * 0.35 = 350 + // Threshold: 1000 - 350 - min(350, 20k) = 300 + const chatHistory = createChatHistory(250); // Below threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(false); }); @@ -303,17 +304,16 @@ describe("tokenizer", () => { }); it("should handle edge case with very small context limit", () => { - const model = createModel(100, 50); // Small context - // Available: 100 - 50 = 50 - // Threshold: 50 * 0.8 = 40 - const chatHistory = createChatHistory(45); // Above threshold + const model = createModel(200, 50); // Small context + // Threshold: 200 - 50 - min(50, 20k) = 200 - 50 - 50 = 100 + const chatHistory = createChatHistory(110); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); }); it("should log debug information correctly", () => { const model = createModel(1000, 200); - const chatHistory = createChatHistory(600); + const chatHistory = createChatHistory(550); shouldAutoCompact({ chatHistory, model }); @@ -325,9 +325,8 @@ describe("tokenizer", () => { contextLimit: 1000, maxTokens: 200, reservedForOutput: 200, - availableForInput: 800, - usage: expect.any(String), - threshold: `${Math.round(AUTO_COMPACT_THRESHOLD * 100)}%`, + compactionBuffer: 200, + compactionThreshold: 600, shouldCompact: expect.any(Boolean), }); }); @@ -335,7 +334,8 @@ describe("tokenizer", () => { it("should handle model with zero maxTokens correctly", () => { const model = createModel(1000, 0); // Explicit zero // Should use default 35% reservation: 1000 * 0.35 = 350 - const chatHistory = createChatHistory(530); // Above threshold + // Threshold: 1000 - 350 - min(350, 20k) = 300 + const chatHistory = createChatHistory(350); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); }); @@ -344,9 +344,8 @@ describe("tokenizer", () => { it("should prevent Claude 3.5 Sonnet context overflow", () => { // Claude 3.5 Sonnet: 200k context, often uses 4k max_tokens const model = createModel(200_000, 4_000); - // Available: 200k - 4k = 196k - // Threshold: 196k * 0.8 = 156.8k - const chatHistory = createChatHistory(160_000); // Above threshold + // Threshold: 200k - 4k - min(4k, 20k) = 200k - 4k - 4k = 192k + const chatHistory = createChatHistory(193_000); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); }); @@ -354,22 +353,35 @@ describe("tokenizer", () => { it("should prevent GPT-4 context overflow", () => { // GPT-4: 128k context, often uses 4k max_tokens const model = createModel(128_000, 4_000); - // Available: 128k - 4k = 124k - // Threshold: 124k * 0.8 = 99.2k - const chatHistory = createChatHistory(100_000); // Above threshold + // Threshold: 128k - 4k - min(4k, 20k) = 128k - 4k - 4k = 120k + const chatHistory = createChatHistory(121_000); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); }); it("should handle models with very high max_tokens", () => { - // Some models allow very high max_tokens (e.g., 64k like in the error message) + // Some models allow very high max_tokens (e.g., 64k) const model = createModel(200_000, 64_000); - // Available: 200k - 64k = 136k - // Threshold: 136k * 0.8 = 108.8k - const chatHistory = createChatHistory(110_000); // Above threshold + // Threshold: 200k - 64k - min(64k, 20k) = 200k - 64k - 20k = 116k + const chatHistory = createChatHistory(120_000); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); }); + + it("should cap buffer at AUTO_COMPACT_BUFFER_CAP for large maxTokens", () => { + // When maxTokens > AUTO_COMPACT_BUFFER_CAP, buffer should be capped + const contextLength = 200_000; + const maxTokens = 64_000; + const model = createModel(contextLength, maxTokens); + // Threshold: contextLength - maxTokens - min(maxTokens, AUTO_COMPACT_BUFFER_CAP) + const threshold = + contextLength - + maxTokens - + Math.min(maxTokens, AUTO_COMPACT_BUFFER_CAP); + const chatHistory = createChatHistory(threshold - 1000); // Below threshold + + expect(shouldAutoCompact({ chatHistory, model })).toBe(false); + }); }); }); diff --git a/extensions/cli/src/util/tokenizer.ts b/extensions/cli/src/util/tokenizer.ts index 9bafeb2c1..8faf13aba 100644 --- a/extensions/cli/src/util/tokenizer.ts +++ b/extensions/cli/src/util/tokenizer.ts @@ -3,14 +3,12 @@ import type { ChatHistoryItem } from "core/index.js"; import { encode } from "gpt-tokenizer"; import type { ChatCompletionTool } from "openai/resources/chat/completions.mjs"; +import { + AUTO_COMPACT_BUFFER_CAP, + DEFAULT_CONTEXT_LENGTH, +} from "../compaction.js"; + import { logger } from "./logger.js"; - -// Global auto-compact threshold (80% of context limit) -// This is intentionally not configurable to ensure consistent behavior -// across all usage scenarios. Change this value only for testing purposes. -export const AUTO_COMPACT_THRESHOLD = 0.8; - -const DEFAULT_CONTEXT_LENGTH_FOR_COMPACTION = 200_000; /** * Get the context length limit for a model * @param modelName The model name @@ -18,8 +16,7 @@ const DEFAULT_CONTEXT_LENGTH_FOR_COMPACTION = 200_000; */ export function getModelContextLimit(model: ModelConfig): number { return ( - model.defaultCompletionOptions?.contextLength ?? - DEFAULT_CONTEXT_LENGTH_FOR_COMPACTION + model.defaultCompletionOptions?.contextLength ?? DEFAULT_CONTEXT_LENGTH ); } @@ -384,19 +381,22 @@ export function shouldAutoCompact(params: AutoCompactParams): boolean { // (64k/200k with claude = 32%, round up to give a buffer) const reservedForOutput = maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35); - const availableForInput = contextLimit - reservedForOutput; + // Additional buffer to trigger compaction before hitting context limit + // Threshold formula: contextLength - maxTokens - Min(maxTokens, 20k) + const compactionBuffer = Math.min(reservedForOutput, AUTO_COMPACT_BUFFER_CAP); + const compactionThreshold = + contextLimit - reservedForOutput - compactionBuffer; // Ensure we have positive space available for input - if (availableForInput <= 0) { + if (compactionThreshold <= 0) { throw new Error( `max_tokens is larger than context_length, which should not be possible. Please check your configuration.`, ); } - const usage = inputTokens / availableForInput; - const toolTokens = tools ? countToolDefinitionTokens(tools) : 0; const systemTokens = systemMessage ? encode(systemMessage).length : 0; + const shouldCompact = inputTokens >= compactionThreshold; logger.debug("Context usage check", { inputTokens, @@ -406,13 +406,12 @@ export function shouldAutoCompact(params: AutoCompactParams): boolean { contextLimit, maxTokens, reservedForOutput, - availableForInput, - usage: `${Math.round(usage * 100)}%`, - threshold: `${Math.round(AUTO_COMPACT_THRESHOLD * 100)}%`, - shouldCompact: usage >= AUTO_COMPACT_THRESHOLD, + compactionBuffer, + compactionThreshold, + shouldCompact, }); - return usage >= AUTO_COMPACT_THRESHOLD; + return shouldCompact; } /** From 1d8aa4b1e435c83871a2fc6763c7b9bd42355446 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 21 Jan 2026 17:42:48 -0800 Subject: [PATCH 5/8] test: fix tests for change from 20k to 15k autocompaction buffer --- .../cli/src/tools/gitAiIntegration.test.ts | 1 + extensions/cli/src/util/tokenizer.test.ts | 20 +++++++++---------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/extensions/cli/src/tools/gitAiIntegration.test.ts b/extensions/cli/src/tools/gitAiIntegration.test.ts index d9d2c85e2..3b8ab2992 100644 --- a/extensions/cli/src/tools/gitAiIntegration.test.ts +++ b/extensions/cli/src/tools/gitAiIntegration.test.ts @@ -103,6 +103,7 @@ describe("Git AI Integration - executeToolCall", () => { }, { toolCallId: "test-edit-id", + parallelToolCallCount: 1, }, ); }); diff --git a/extensions/cli/src/util/tokenizer.test.ts b/extensions/cli/src/util/tokenizer.test.ts index 7c9d5c937..aa532f86c 100644 --- a/extensions/cli/src/util/tokenizer.test.ts +++ b/extensions/cli/src/util/tokenizer.test.ts @@ -253,7 +253,7 @@ describe("tokenizer", () => { it("should compact when input tokens exceed threshold with maxTokens", () => { const model = createModel(1000, 200); // 1000 context, 200 max output - // Threshold: 1000 - 200 - min(200, 20k) = 1000 - 200 - 200 = 600 + // Threshold: 1000 - 200 - min(200, 15k) = 1000 - 200 - 200 = 600 const chatHistory = createChatHistory(650); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); @@ -261,7 +261,7 @@ describe("tokenizer", () => { it("should not compact when input tokens are below threshold with maxTokens", () => { const model = createModel(1000, 200); // 1000 context, 200 max output - // Threshold: 1000 - 200 - min(200, 20k) = 600 + // Threshold: 1000 - 200 - min(200, 15k) = 600 const chatHistory = createChatHistory(550); // Below threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(false); @@ -270,7 +270,7 @@ describe("tokenizer", () => { it("should use 35% default reservation when maxTokens is not set", () => { const model = createModel(1000); // No maxTokens // Reserved: 1000 * 0.35 = 350 - // Threshold: 1000 - 350 - min(350, 20k) = 1000 - 350 - 350 = 300 + // Threshold: 1000 - 350 - min(350, 15k) = 1000 - 350 - 350 = 300 const chatHistory = createChatHistory(350); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); @@ -279,7 +279,7 @@ describe("tokenizer", () => { it("should not compact when below default threshold without maxTokens", () => { const model = createModel(1000); // No maxTokens // Reserved: 1000 * 0.35 = 350 - // Threshold: 1000 - 350 - min(350, 20k) = 300 + // Threshold: 1000 - 350 - min(350, 15k) = 300 const chatHistory = createChatHistory(250); // Below threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(false); @@ -305,7 +305,7 @@ describe("tokenizer", () => { it("should handle edge case with very small context limit", () => { const model = createModel(200, 50); // Small context - // Threshold: 200 - 50 - min(50, 20k) = 200 - 50 - 50 = 100 + // Threshold: 200 - 50 - min(50, 15k) = 200 - 50 - 50 = 100 const chatHistory = createChatHistory(110); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); @@ -334,7 +334,7 @@ describe("tokenizer", () => { it("should handle model with zero maxTokens correctly", () => { const model = createModel(1000, 0); // Explicit zero // Should use default 35% reservation: 1000 * 0.35 = 350 - // Threshold: 1000 - 350 - min(350, 20k) = 300 + // Threshold: 1000 - 350 - min(350, 15k) = 300 const chatHistory = createChatHistory(350); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); @@ -344,7 +344,7 @@ describe("tokenizer", () => { it("should prevent Claude 3.5 Sonnet context overflow", () => { // Claude 3.5 Sonnet: 200k context, often uses 4k max_tokens const model = createModel(200_000, 4_000); - // Threshold: 200k - 4k - min(4k, 20k) = 200k - 4k - 4k = 192k + // Threshold: 200k - 4k - min(4k, 15k) = 200k - 4k - 4k = 192k const chatHistory = createChatHistory(193_000); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); @@ -353,7 +353,7 @@ describe("tokenizer", () => { it("should prevent GPT-4 context overflow", () => { // GPT-4: 128k context, often uses 4k max_tokens const model = createModel(128_000, 4_000); - // Threshold: 128k - 4k - min(4k, 20k) = 128k - 4k - 4k = 120k + // Threshold: 128k - 4k - min(4k, 15k) = 128k - 4k - 4k = 120k const chatHistory = createChatHistory(121_000); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); @@ -362,8 +362,8 @@ describe("tokenizer", () => { it("should handle models with very high max_tokens", () => { // Some models allow very high max_tokens (e.g., 64k) const model = createModel(200_000, 64_000); - // Threshold: 200k - 64k - min(64k, 20k) = 200k - 64k - 20k = 116k - const chatHistory = createChatHistory(120_000); // Above threshold + // Threshold: 200k - 64k - min(64k, 15k) = 200k - 64k - 15k = 121k + const chatHistory = createChatHistory(125_000); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); }); From f1527e761c49effe85fdd135a05a31add4c60349 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 21 Jan 2026 17:54:56 -0800 Subject: [PATCH 6/8] chore: remove error message part explaining env vars --- extensions/cli/src/tools/readFile.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/extensions/cli/src/tools/readFile.ts b/extensions/cli/src/tools/readFile.ts index e66c5a12e..961b375b3 100644 --- a/extensions/cli/src/tools/readFile.ts +++ b/extensions/cli/src/tools/readFile.ts @@ -103,8 +103,7 @@ export const readFileTool: Tool = { ContinueErrorReason.FileTooLarge, `File is too large to read: ${filepath} (${charCount.toLocaleString()} characters, ${lineCount.toLocaleString()} lines). ` + `Maximum allowed: ${maxChars.toLocaleString()} characters or ${maxLines.toLocaleString()} lines.${parallelNote} ` + - `To adjust these limits, set CONTINUE_CLI_READ_FILE_MAX_OUTPUT_CHARS or CONTINUE_CLI_READ_FILE_MAX_OUTPUT_LINES environment variables. ` + - `Alternatively, use shell commands like 'head', 'tail', 'sed', or 'grep' to read targeted parts of the file.`, + `Consider using terminal commands like 'head', 'tail', 'sed', or 'grep' to read targeted parts of the file.`, ); } From 30d7fe75ddceec2138f401b597365f7d08a34fca Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 21 Jan 2026 18:31:02 -0800 Subject: [PATCH 7/8] test: fix comapction tests etc --- .../cli/src/compaction.infiniteLoop.test.ts | 1 + extensions/cli/src/compaction.ts | 100 ++++++++++++-- .../streamChatResponse.autoCompaction.test.ts | 24 ++-- .../streamChatResponse.autoCompaction.ts | 7 +- ...treamChatResponse.autoContinuation.test.ts | 4 +- extensions/cli/src/util/tokenizer.test.ts | 128 ++++++++++++++---- extensions/cli/src/util/tokenizer.ts | 98 +++----------- 7 files changed, 220 insertions(+), 142 deletions(-) diff --git a/extensions/cli/src/compaction.infiniteLoop.test.ts b/extensions/cli/src/compaction.infiniteLoop.test.ts index 68319b4a0..d31734d6d 100644 --- a/extensions/cli/src/compaction.infiniteLoop.test.ts +++ b/extensions/cli/src/compaction.infiniteLoop.test.ts @@ -14,6 +14,7 @@ vi.mock("./stream/streamChatResponse.js", () => ({ vi.mock("./util/tokenizer.js", () => ({ countChatHistoryTokens: vi.fn(), getModelContextLimit: vi.fn(), + getModelMaxTokens: vi.fn(), })); describe("compaction infinite loop prevention", () => { diff --git a/extensions/cli/src/compaction.ts b/extensions/cli/src/compaction.ts index 00c6ea3f5..4132bb97f 100644 --- a/extensions/cli/src/compaction.ts +++ b/extensions/cli/src/compaction.ts @@ -1,21 +1,23 @@ import { ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import type { ChatHistoryItem } from "core/index.js"; +import { encode } from "gpt-tokenizer"; +import { ChatCompletionTool } from "openai/resources.mjs"; import { streamChatResponse } from "./stream/streamChatResponse.js"; import { StreamCallbacks } from "./stream/streamChatResponse.types.js"; import { logger } from "./util/logger.js"; import { countChatHistoryTokens, + countToolDefinitionTokens, + countTotalInputTokens, getModelContextLimit, + getModelMaxTokens, } from "./util/tokenizer.js"; -// Buffer cap for auto-compaction threshold calculation -// Threshold formula: contextLength - maxTokens - Min(maxTokens, AUTO_COMPACT_BUFFER_CAP) +// Buffer cap/ratio for auto-compaction threshold calculation export const AUTO_COMPACT_BUFFER_CAP = 15_000; - -// Default context length when model config doesn't specify one -export const DEFAULT_CONTEXT_LENGTH = 200_000; +export const AUTO_COMPACT_BUFFER_RATIO = 0.8; export interface CompactionResult { compactedHistory: ChatHistoryItem[]; @@ -69,12 +71,7 @@ export async function compactChatHistory( let historyForCompaction = [...historyToUse, compactionPrompt]; const contextLimit = getModelContextLimit(model); - const maxTokens = model.defaultCompletionOptions?.maxTokens; - const reservedForOutput = - maxTokens === undefined ? Math.ceil(contextLimit * 0.35) : maxTokens; - // Additional buffer matching the auto-compaction threshold formula: - // contextLength - maxTokens - Min(maxTokens, 20k) - const compactionBuffer = Math.min(reservedForOutput, AUTO_COMPACT_BUFFER_CAP); + const maxTokens = getModelMaxTokens(model); // Check if system message is already in the history to avoid double-counting const hasSystemMessageInHistory = chatHistory.some( @@ -85,10 +82,10 @@ export async function compactChatHistory( const systemMessageReservation = hasSystemMessageInHistory ? 0 : systemMessageTokens; + const availableForInput = contextLimit - - reservedForOutput - - compactionBuffer - + maxTokens - systemMessageReservation - COMPACTION_PROMPT_TOKENS; @@ -239,3 +236,80 @@ export function getHistoryForLLM( ? [systemMessage, ...messagesFromCompaction] : messagesFromCompaction; } + +/** + * Parameters for auto-compaction check + */ +export interface AutoCompactParams { + chatHistory: ChatHistoryItem[]; + model: ModelConfig; + systemMessage?: string; + tools?: ChatCompletionTool[]; +} + +/** + * Get a descriptive message for auto-compaction that shows the context limit + * @param model The model configuration + * @returns A descriptive message explaining why compaction is needed + */ +export function getAutoCompactMessage(model: ModelConfig): string { + const limit = getModelContextLimit(model); + return `Approaching context limit (${(limit / 1000).toFixed(0)}K tokens). Auto-compacting chat history...`; +} + +/** + * Check if the chat history exceeds the auto-compact threshold. + * Accounts for system message and tool definitions in the calculation. + * @param params Object containing chatHistory, model, optional systemMessage, and optional tools + * @returns Whether auto-compacting should be triggered + */ +export function shouldAutoCompact(params: AutoCompactParams): boolean { + const { chatHistory, model, systemMessage, tools } = params; + + const inputTokens = countTotalInputTokens({ + chatHistory, + systemMessage, + tools, + model, + }); + const contextLimit = getModelContextLimit(model); + const maxTokens = getModelMaxTokens(model); + + // Additional buffer matching the auto-compaction threshold formula + const ratioCompactionBuffer = Math.ceil( + (1 - AUTO_COMPACT_BUFFER_RATIO) * (contextLimit - maxTokens), + ); + const safeCompactionBuffer = Math.max(maxTokens, ratioCompactionBuffer); + const compactionBuffer = Math.min( + safeCompactionBuffer, + AUTO_COMPACT_BUFFER_CAP, + ); + + const compactionThreshold = contextLimit - maxTokens - compactionBuffer; + + // Ensure we have positive space available for input + if (compactionThreshold <= 0) { + throw new Error( + `max_tokens is larger than context_length, which should not be possible. Please check your configuration.`, + ); + } + + const toolTokens = tools ? countToolDefinitionTokens(tools) : 0; + const systemTokens = systemMessage ? encode(systemMessage).length : 0; + const shouldCompact = inputTokens >= compactionThreshold; + + logger.debug("Context usage check", { + inputTokens, + historyTokens: countChatHistoryTokens(chatHistory, model), + systemTokens, + toolTokens, + contextLimit, + maxTokens, + reservedForOutput: maxTokens, + compactionBuffer, + compactionThreshold, + shouldCompact, + }); + + return shouldCompact; +} diff --git a/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts b/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts index 20c654c40..21b0a5651 100644 --- a/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts @@ -7,6 +7,8 @@ import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; // Mock dependencies vi.mock("../compaction.js", () => ({ compactChatHistory: vi.fn(), + shouldAutoCompact: vi.fn(), + getAutoCompactMessage: vi.fn(), })); vi.mock("../session.js", () => ({ @@ -22,8 +24,6 @@ vi.mock("../session.js", () => ({ })); vi.mock("../util/tokenizer.js", () => ({ - shouldAutoCompact: vi.fn(), - getAutoCompactMessage: vi.fn(), countChatHistoryItemTokens: vi.fn(() => 100), // Mock return value })); @@ -82,7 +82,7 @@ describe("handleAutoCompaction", () => { }); it("should return original history when auto-compaction is not needed", async () => { - const { shouldAutoCompact } = await import("../util/tokenizer.js"); + const { shouldAutoCompact } = await import("../compaction.js"); const mockedShouldAutoCompact = shouldAutoCompact as any; mockedShouldAutoCompact.mockReturnValue(false); @@ -108,10 +108,8 @@ describe("handleAutoCompaction", () => { }); it("should perform auto-compaction when context limit is approaching", async () => { - const { shouldAutoCompact, getAutoCompactMessage } = await import( - "../util/tokenizer.js" - ); - const { compactChatHistory } = await import("../compaction.js"); + const { compactChatHistory, shouldAutoCompact, getAutoCompactMessage } = + await import("../compaction.js"); const { updateSessionHistory } = await import("../session.js"); vi.mocked(shouldAutoCompact).mockReturnValue(true); @@ -184,10 +182,8 @@ describe("handleAutoCompaction", () => { }); it("should handle compaction errors gracefully", async () => { - const { shouldAutoCompact, getAutoCompactMessage } = await import( - "../util/tokenizer.js" - ); - const { compactChatHistory } = await import("../compaction.js"); + const { compactChatHistory, shouldAutoCompact, getAutoCompactMessage } = + await import("../compaction.js"); const { logger } = await import("../util/logger.js"); vi.mocked(shouldAutoCompact).mockReturnValue(true); @@ -227,10 +223,8 @@ describe("handleAutoCompaction", () => { }); it("should not call system message callback in headless mode", async () => { - const { shouldAutoCompact, getAutoCompactMessage } = await import( - "../util/tokenizer.js" - ); - const { compactChatHistory } = await import("../compaction.js"); + const { compactChatHistory, shouldAutoCompact, getAutoCompactMessage } = + await import("../compaction.js"); vi.mocked(shouldAutoCompact).mockReturnValue(true); vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); diff --git a/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts b/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts index 3086de9eb..156e9fa35 100644 --- a/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts +++ b/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts @@ -4,11 +4,14 @@ import type { ChatHistoryItem } from "core/index.js"; import type { ChatCompletionTool } from "openai/resources/chat/completions.mjs"; import React from "react"; -import { compactChatHistory } from "../compaction.js"; +import { + compactChatHistory, + getAutoCompactMessage, + shouldAutoCompact, +} from "../compaction.js"; import { updateSessionHistory } from "../session.js"; import { formatError } from "../util/formatError.js"; import { logger } from "../util/logger.js"; -import { getAutoCompactMessage, shouldAutoCompact } from "../util/tokenizer.js"; interface AutoCompactionCallbacks { // For streaming mode diff --git a/extensions/cli/src/stream/streamChatResponse.autoContinuation.test.ts b/extensions/cli/src/stream/streamChatResponse.autoContinuation.test.ts index 42a6ec05f..8f4e95a2b 100644 --- a/extensions/cli/src/stream/streamChatResponse.autoContinuation.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.autoContinuation.test.ts @@ -11,6 +11,8 @@ import { streamChatResponse } from "./streamChatResponse.js"; vi.mock("../compaction.js", () => ({ compactChatHistory: vi.fn(), pruneLastMessage: vi.fn((history) => history.slice(0, -1)), + shouldAutoCompact: vi.fn(), + getAutoCompactMessage: vi.fn(() => "Auto-compacting..."), })); vi.mock("../session.js", () => ({ @@ -19,8 +21,6 @@ vi.mock("../session.js", () => ({ })); vi.mock("../util/tokenizer.js", () => ({ - shouldAutoCompact: vi.fn(), - getAutoCompactMessage: vi.fn(() => "Auto-compacting..."), countChatHistoryItemTokens: vi.fn(() => 100), validateContextLength: vi.fn(() => ({ isValid: true })), })); diff --git a/extensions/cli/src/util/tokenizer.test.ts b/extensions/cli/src/util/tokenizer.test.ts index aa532f86c..acd1c7428 100644 --- a/extensions/cli/src/util/tokenizer.test.ts +++ b/extensions/cli/src/util/tokenizer.test.ts @@ -4,17 +4,18 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { AUTO_COMPACT_BUFFER_CAP, - DEFAULT_CONTEXT_LENGTH, + AUTO_COMPACT_BUFFER_RATIO, + shouldAutoCompact, } from "../compaction.js"; import { logger } from "./logger.js"; import { + DEFAULT_CONTEXT_LENGTH, calculateContextUsagePercentage, countChatHistoryItemTokens, countChatHistoryTokens, countToolDefinitionTokens, getModelContextLimit, - shouldAutoCompact, } from "./tokenizer.js"; // Mock the logger @@ -251,9 +252,29 @@ describe("tokenizer", () => { ]; }; + // Helper to calculate threshold using the new formula + const calculateThreshold = ( + contextLength: number, + maxTokens: number, + ): number => { + const ratioCompactionBuffer = Math.ceil( + (1 - AUTO_COMPACT_BUFFER_RATIO) * (contextLength - maxTokens), + ); + const safeCompactionBuffer = Math.max(maxTokens, ratioCompactionBuffer); + const compactionBuffer = Math.min( + safeCompactionBuffer, + AUTO_COMPACT_BUFFER_CAP, + ); + return contextLength - maxTokens - compactionBuffer; + }; + it("should compact when input tokens exceed threshold with maxTokens", () => { const model = createModel(1000, 200); // 1000 context, 200 max output - // Threshold: 1000 - 200 - min(200, 15k) = 1000 - 200 - 200 = 600 + // ratioBuffer = ceil(0.2 * 800) = 160, safeBuffer = max(200, 160) = 200 + // compactionBuffer = min(200, 15k) = 200 + // Threshold: 1000 - 200 - 200 = 600 + const threshold = calculateThreshold(1000, 200); + expect(threshold).toBe(600); const chatHistory = createChatHistory(650); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); @@ -261,16 +282,20 @@ describe("tokenizer", () => { it("should not compact when input tokens are below threshold with maxTokens", () => { const model = createModel(1000, 200); // 1000 context, 200 max output - // Threshold: 1000 - 200 - min(200, 15k) = 600 - const chatHistory = createChatHistory(550); // Below threshold + const threshold = calculateThreshold(1000, 200); + const chatHistory = createChatHistory(threshold - 100); // Below threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(false); }); it("should use 35% default reservation when maxTokens is not set", () => { const model = createModel(1000); // No maxTokens - // Reserved: 1000 * 0.35 = 350 - // Threshold: 1000 - 350 - min(350, 15k) = 1000 - 350 - 350 = 300 + // Default maxTokens = min(1000 * 0.35, 64k) = 350 + // ratioBuffer = ceil(0.2 * 650) = 130, safeBuffer = max(350, 130) = 350 + // compactionBuffer = min(350, 15k) = 350 + // Threshold: 1000 - 350 - 350 = 300 + const threshold = calculateThreshold(1000, 350); + expect(threshold).toBe(300); const chatHistory = createChatHistory(350); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); @@ -278,14 +303,26 @@ describe("tokenizer", () => { it("should not compact when below default threshold without maxTokens", () => { const model = createModel(1000); // No maxTokens - // Reserved: 1000 * 0.35 = 350 - // Threshold: 1000 - 350 - min(350, 15k) = 300 + // Threshold: 300 (calculated above) const chatHistory = createChatHistory(250); // Below threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(false); }); - it("should throw error when maxTokens >= contextLength", () => { + it("should throw error when threshold becomes zero or negative", () => { + // With extremely high maxTokens relative to context, threshold can become <= 0 + const model = createModel(1000, 800); // maxTokens is 80% of context + // ratioBuffer = ceil(0.2 * 200) = 40, safeBuffer = max(800, 40) = 800 + // compactionBuffer = min(800, 15k) = 800 + // Threshold: 1000 - 800 - 800 = -600 (negative!) + const chatHistory = createChatHistory(1); // Minimal input + + expect(() => shouldAutoCompact({ chatHistory, model })).toThrow( + "max_tokens is larger than context_length, which should not be possible. Please check your configuration.", + ); + }); + + it("should throw error when maxTokens equals contextLength", () => { const model = createModel(1000, 1000); // maxTokens equals contextLength const chatHistory = createChatHistory(1); // Minimal input @@ -294,7 +331,7 @@ describe("tokenizer", () => { ); }); - it("should throw error when maxTokens > contextLength", () => { + it("should throw error when maxTokens exceeds contextLength", () => { const model = createModel(1000, 1200); // maxTokens exceeds contextLength const chatHistory = createChatHistory(1); // Minimal input @@ -305,7 +342,11 @@ describe("tokenizer", () => { it("should handle edge case with very small context limit", () => { const model = createModel(200, 50); // Small context - // Threshold: 200 - 50 - min(50, 15k) = 200 - 50 - 50 = 100 + // ratioBuffer = ceil(0.2 * 150) = 30, safeBuffer = max(50, 30) = 50 + // compactionBuffer = min(50, 15k) = 50 + // Threshold: 200 - 50 - 50 = 100 + const threshold = calculateThreshold(200, 50); + expect(threshold).toBe(100); const chatHistory = createChatHistory(110); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); @@ -314,6 +355,8 @@ describe("tokenizer", () => { it("should log debug information correctly", () => { const model = createModel(1000, 200); const chatHistory = createChatHistory(550); + const expectedBuffer = 200; // max(200, ceil(0.2*800)=160) = 200, min(200, 15k) = 200 + const expectedThreshold = 1000 - 200 - expectedBuffer; shouldAutoCompact({ chatHistory, model }); @@ -325,17 +368,21 @@ describe("tokenizer", () => { contextLimit: 1000, maxTokens: 200, reservedForOutput: 200, - compactionBuffer: 200, - compactionThreshold: 600, + compactionBuffer: expectedBuffer, + compactionThreshold: expectedThreshold, shouldCompact: expect.any(Boolean), }); }); it("should handle model with zero maxTokens correctly", () => { const model = createModel(1000, 0); // Explicit zero - // Should use default 35% reservation: 1000 * 0.35 = 350 - // Threshold: 1000 - 350 - min(350, 15k) = 300 - const chatHistory = createChatHistory(350); // Above threshold + // When maxTokens is 0, getModelMaxTokens returns 0 (not the default) + // ratioBuffer = ceil(0.2 * 1000) = 200, safeBuffer = max(0, 200) = 200 + // compactionBuffer = min(200, 15k) = 200 + // Threshold: 1000 - 0 - 200 = 800 + const threshold = calculateThreshold(1000, 0); + expect(threshold).toBe(800); + const chatHistory = createChatHistory(threshold + 50); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); }); @@ -344,8 +391,12 @@ describe("tokenizer", () => { it("should prevent Claude 3.5 Sonnet context overflow", () => { // Claude 3.5 Sonnet: 200k context, often uses 4k max_tokens const model = createModel(200_000, 4_000); - // Threshold: 200k - 4k - min(4k, 15k) = 200k - 4k - 4k = 192k - const chatHistory = createChatHistory(193_000); // Above threshold + // ratioBuffer = ceil(0.2 * 196k) = 39200, safeBuffer = max(4k, 39200) = 39200 + // compactionBuffer = min(39200, 15k) = 15000 + // Threshold: 200k - 4k - 15k = 181k + const threshold = calculateThreshold(200_000, 4_000); + expect(threshold).toBe(181_000); + const chatHistory = createChatHistory(threshold + 1000); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); }); @@ -353,8 +404,12 @@ describe("tokenizer", () => { it("should prevent GPT-4 context overflow", () => { // GPT-4: 128k context, often uses 4k max_tokens const model = createModel(128_000, 4_000); - // Threshold: 128k - 4k - min(4k, 15k) = 128k - 4k - 4k = 120k - const chatHistory = createChatHistory(121_000); // Above threshold + // ratioBuffer = ceil(0.2 * 124k) = 24800, safeBuffer = max(4k, 24800) = 24800 + // compactionBuffer = min(24800, 15k) = 15000 + // Threshold: 128k - 4k - 15k = 109k + const threshold = calculateThreshold(128_000, 4_000); + expect(threshold).toBe(109_000); + const chatHistory = createChatHistory(threshold + 1000); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); }); @@ -362,26 +417,41 @@ describe("tokenizer", () => { it("should handle models with very high max_tokens", () => { // Some models allow very high max_tokens (e.g., 64k) const model = createModel(200_000, 64_000); - // Threshold: 200k - 64k - min(64k, 15k) = 200k - 64k - 15k = 121k - const chatHistory = createChatHistory(125_000); // Above threshold + // ratioBuffer = ceil(0.2 * 136k) = 27200, safeBuffer = max(64k, 27200) = 64000 + // compactionBuffer = min(64k, 15k) = 15000 + // Threshold: 200k - 64k - 15k = 121k + const threshold = calculateThreshold(200_000, 64_000); + expect(threshold).toBe(121_000); + const chatHistory = createChatHistory(threshold + 1000); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); }); it("should cap buffer at AUTO_COMPACT_BUFFER_CAP for large maxTokens", () => { - // When maxTokens > AUTO_COMPACT_BUFFER_CAP, buffer should be capped + // When computed buffer > AUTO_COMPACT_BUFFER_CAP, buffer should be capped const contextLength = 200_000; const maxTokens = 64_000; const model = createModel(contextLength, maxTokens); - // Threshold: contextLength - maxTokens - min(maxTokens, AUTO_COMPACT_BUFFER_CAP) - const threshold = - contextLength - - maxTokens - - Math.min(maxTokens, AUTO_COMPACT_BUFFER_CAP); + const threshold = calculateThreshold(contextLength, maxTokens); const chatHistory = createChatHistory(threshold - 1000); // Below threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(false); }); + + it("should use ratio-based buffer when maxTokens is small", () => { + // When maxTokens is small, ratio-based buffer should take precedence + const contextLength = 100_000; + const maxTokens = 1_000; + const model = createModel(contextLength, maxTokens); + // ratioBuffer = ceil(0.2 * 99k) = 19800, safeBuffer = max(1k, 19800) = 19800 + // compactionBuffer = min(19800, 15k) = 15000 + // Threshold: 100k - 1k - 15k = 84k + const threshold = calculateThreshold(contextLength, maxTokens); + expect(threshold).toBe(84_000); + const chatHistory = createChatHistory(threshold + 1000); // Above threshold + + expect(shouldAutoCompact({ chatHistory, model })).toBe(true); + }); }); }); diff --git a/extensions/cli/src/util/tokenizer.ts b/extensions/cli/src/util/tokenizer.ts index 8faf13aba..24317d47f 100644 --- a/extensions/cli/src/util/tokenizer.ts +++ b/extensions/cli/src/util/tokenizer.ts @@ -3,12 +3,13 @@ import type { ChatHistoryItem } from "core/index.js"; import { encode } from "gpt-tokenizer"; import type { ChatCompletionTool } from "openai/resources/chat/completions.mjs"; -import { - AUTO_COMPACT_BUFFER_CAP, - DEFAULT_CONTEXT_LENGTH, -} from "../compaction.js"; - import { logger } from "./logger.js"; + +const DEFAULT_MAX_TOKENS_RATIO = 0.35; +const MAX_MAX_TOKENS = 64_000; +// Default context length when model config doesn't specify one +export const DEFAULT_CONTEXT_LENGTH = 200_000; + /** * Get the context length limit for a model * @param modelName The model name @@ -20,6 +21,17 @@ export function getModelContextLimit(model: ModelConfig): number { ); } +export function getModelMaxTokens(model: ModelConfig): number { + const contextLimit = getModelContextLimit(model); + const maxTokens = model.defaultCompletionOptions?.maxTokens; + + return maxTokens === undefined + ? Math.ceil( + Math.min(contextLimit * DEFAULT_MAX_TOKENS_RATIO, MAX_MAX_TOKENS), + ) + : maxTokens; +} + // Importing a bunch of tokenizers can be very resource intensive (MB-scale per tokenizer) // Using token counting APIs (e.g. for anthropic) can be complicated and unreliable in many environments // So for now we will just use super fast gpt-tokenizer and apply safety buffers @@ -348,82 +360,6 @@ export function countTotalInputTokens(params: TotalInputTokenParams): number { return totalTokens; } -/** - * Parameters for auto-compaction check - */ -export interface AutoCompactParams { - chatHistory: ChatHistoryItem[]; - model: ModelConfig; - systemMessage?: string; - tools?: ChatCompletionTool[]; -} - -/** - * Check if the chat history exceeds the auto-compact threshold. - * Accounts for system message and tool definitions in the calculation. - * @param params Object containing chatHistory, model, optional systemMessage, and optional tools - * @returns Whether auto-compacting should be triggered - */ -export function shouldAutoCompact(params: AutoCompactParams): boolean { - const { chatHistory, model, systemMessage, tools } = params; - - const inputTokens = countTotalInputTokens({ - chatHistory, - systemMessage, - tools, - model, - }); - const contextLimit = getModelContextLimit(model); - const maxTokens = model.defaultCompletionOptions?.maxTokens || 0; - - // Calculate available space considering max_tokens reservation - // If maxTokens is not set, reserve 35% of context for output as a safe default - // (64k/200k with claude = 32%, round up to give a buffer) - const reservedForOutput = - maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35); - // Additional buffer to trigger compaction before hitting context limit - // Threshold formula: contextLength - maxTokens - Min(maxTokens, 20k) - const compactionBuffer = Math.min(reservedForOutput, AUTO_COMPACT_BUFFER_CAP); - const compactionThreshold = - contextLimit - reservedForOutput - compactionBuffer; - - // Ensure we have positive space available for input - if (compactionThreshold <= 0) { - throw new Error( - `max_tokens is larger than context_length, which should not be possible. Please check your configuration.`, - ); - } - - const toolTokens = tools ? countToolDefinitionTokens(tools) : 0; - const systemTokens = systemMessage ? encode(systemMessage).length : 0; - const shouldCompact = inputTokens >= compactionThreshold; - - logger.debug("Context usage check", { - inputTokens, - historyTokens: countChatHistoryTokens(chatHistory, model), - systemTokens, - toolTokens, - contextLimit, - maxTokens, - reservedForOutput, - compactionBuffer, - compactionThreshold, - shouldCompact, - }); - - return shouldCompact; -} - -/** - * Get a descriptive message for auto-compaction that shows the context limit - * @param model The model configuration - * @returns A descriptive message explaining why compaction is needed - */ -export function getAutoCompactMessage(model: ModelConfig): string { - const limit = getModelContextLimit(model); - return `Approaching context limit (${(limit / 1000).toFixed(0)}K tokens). Auto-compacting chat history...`; -} - /** * Parameters for context length validation */ From c0a930919fe93ce7ad6a0eaf3546a956dee02383 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 22 Jan 2026 11:21:30 -0800 Subject: [PATCH 8/8] fix: linting issue mising parallel count --- extensions/cli/src/tools/subagent.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cli/src/tools/subagent.test.ts b/extensions/cli/src/tools/subagent.test.ts index e4f2d61ea..3af2ff4bf 100644 --- a/extensions/cli/src/tools/subagent.test.ts +++ b/extensions/cli/src/tools/subagent.test.ts @@ -97,7 +97,7 @@ describe("subagentTool", () => { prompt: "Subagent prompt", subagent_name: "code-agent", }, - { toolCallId: "tool-call-id" }, + { toolCallId: "tool-call-id", parallelToolCallCount: 1 }, ); expect(vi.mocked(executeSubAgent)).toHaveBeenCalledTimes(1);