Merge pull request #9567 from continuedev/dallin/compaction-fixes-2

This commit is contained in:
Nate Sesti 2026-01-22 13:15:07 -08:00 • committed by GitHub
commit 29aa68275e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 499 additions and 328 deletions

View file

@ -34,7 +34,6 @@ import { prependPrompt } from "../util/promptProcessor.js";
import {
calculateContextUsagePercentage,
countChatHistoryTokens,
shouldAutoCompact,
} from "../util/tokenizer.js";
import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
@ -249,7 +248,10 @@ async function handleAutoCompaction(
message: "Auto-compacting triggered",
contextUsage:
calculateContextUsagePercentage(
countChatHistoryTokens(services.chatHistory.getHistory()),
countChatHistoryTokens(
services.chatHistory.getHistory(),
model,
),
model,
) + "%",
}) + "\n",
@ -363,25 +365,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

View file

@ -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", () => {

View file

@ -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", () => {

View file

@ -1,15 +1,24 @@
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/ratio for auto-compaction threshold calculation
export const AUTO_COMPACT_BUFFER_CAP = 15_000;
export const AUTO_COMPACT_BUFFER_RATIO = 0.8;
export interface CompactionResult {
compactedHistory: ChatHistoryItem[];
compactionIndex: number;
@ -28,6 +37,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 +61,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: [],
};
@ -58,30 +71,31 @@ 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;
const maxTokens = getModelMaxTokens(model);
// Check if system message is already in the history to avoid double-counting
const hasSystemMessageInHistory = chatHistory.some(
(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 -
maxTokens -
systemMessageReservation -
COMPACTION_PROMPT_TOKENS;
// 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,
});
@ -222,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;
}

View file

@ -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...");

View file

@ -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
@ -172,13 +175,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, {

View file

@ -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 })),
}));

View file

@ -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,

View file

@ -103,6 +103,7 @@ describe("Git AI Integration - executeToolCall", () => {
},
{
toolCallId: "test-edit-id",
parallelToolCallCount: 1,
},
);
});

View file

@ -38,6 +38,7 @@ import {
type Tool,
type ToolCall,
type ToolParametersSchema,
type ToolRunContext,
ParameterSchema,
PreprocessedToolCall,
} from "./types.js";
@ -209,6 +210,7 @@ export function convertMcpToolToContinueTool(mcpTool: MCPTool): Tool {
export async function executeToolCall(
toolCall: PreprocessedToolCall,
options: { parallelToolCallCount: number } = { parallelToolCallCount: 1 },
): Promise<string> {
const startTime = Date.now();
@ -216,16 +218,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;

View file

@ -3,13 +3,10 @@ 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";
import { Tool, ToolRunContext } from "./types.js";
// Output truncation defaults
const DEFAULT_READ_FILE_MAX_CHARS = 100000; // ~25k tokens
@ -67,7 +64,10 @@ export const readFileTool: Tool = {
],
};
},
run: async (args: { filepath: string }): Promise<string> => {
run: async (
args: { filepath: string },
context?: ToolRunContext,
): Promise<string> => {
try {
let { filepath } = args;
if (filepath.startsWith("./")) {
@ -82,20 +82,35 @@ export const readFileTool: Tool = {
}
const realPath = fs.realpathSync(filepath);
const content = fs.readFileSync(realPath, "utf-8");
// 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.${parallelNote} ` +
`Consider using terminal commands like 'head', 'tail', 'sed', or 'grep' to read targeted parts of the file.`,
);
}
// Mark this file as read for the edit tool
markFileAsRead(realPath);
const maxLines = getReadFileMaxLines();
const maxChars = getReadFileMaxChars();
const { output: truncatedContent, wasTruncated } =
truncateByLinesAndChars(content, maxLines, maxChars, "file content");
if (wasTruncated) {
return `Content of ${filepath} (truncated):\n${truncatedContent}`;
}
return `Content of ${filepath}:\n${truncatedContent}`;
return `Content of ${filepath}:\n${content}`;
} catch (error) {
if (error instanceof ContinueError) {
throw error;

View file

@ -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<string> => {
run: async (
{
command,
timeout,
}: {
command: string;
timeout?: number;
},
context?: ToolRunContext,
): Promise<string> => {
// 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) => {

View file

@ -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);

View file

@ -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<PreprocessToolCallResult>;
run: (args: any, context?: { toolCallId: string }) => Promise<string>;
run: (args: any, context?: ToolRunContext) => Promise<string>;
readonly?: boolean; // Indicates if the tool is readonly
isBuiltIn: boolean;
evaluateToolCallPolicy?: (

View file

@ -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,
};
}

View file

@ -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 {

View file

@ -2,16 +2,20 @@ 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,
AUTO_COMPACT_BUFFER_RATIO,
shouldAutoCompact,
} from "../compaction.js";
import { logger } from "./logger.js";
import {
AUTO_COMPACT_THRESHOLD,
DEFAULT_CONTEXT_LENGTH,
calculateContextUsagePercentage,
countChatHistoryItemTokens,
countChatHistoryTokens,
countMessageTokens,
countToolDefinitionTokens,
getModelContextLimit,
shouldAutoCompact,
} from "./tokenizer.js";
// Mock the logger
@ -55,7 +59,7 @@ describe("tokenizer", () => {
provider: "openai",
};
expect(getModelContextLimit(model)).toBe(200_000);
expect(getModelContextLimit(model)).toBe(DEFAULT_CONTEXT_LENGTH);
});
});
@ -69,7 +73,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 +96,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 +125,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 +151,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 +169,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 +186,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);
});
});
@ -227,10 +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
// Available for input: 1000 - 200 = 800
// Threshold: 800 * 0.8 = 640
// 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);
@ -238,33 +282,47 @@ 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
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
// Available for input: 1000 - 350 = 650
// Threshold: 650 * 0.8 = 520
const chatHistory = createChatHistory(530); // Above threshold
// 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);
});
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
// 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
@ -273,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
@ -283,17 +341,22 @@ 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
// 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);
});
it("should log debug information correctly", () => {
const model = createModel(1000, 200);
const chatHistory = createChatHistory(600);
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 });
@ -305,17 +368,21 @@ describe("tokenizer", () => {
contextLimit: 1000,
maxTokens: 200,
reservedForOutput: 200,
availableForInput: 800,
usage: expect.any(String),
threshold: `${Math.round(AUTO_COMPACT_THRESHOLD * 100)}%`,
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
const chatHistory = createChatHistory(530); // 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);
});
@ -324,9 +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);
// Available: 200k - 4k = 196k
// Threshold: 196k * 0.8 = 156.8k
const chatHistory = createChatHistory(160_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);
});
@ -334,19 +404,51 @@ 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
// 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);
});
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
// 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 computed buffer > AUTO_COMPACT_BUFFER_CAP, buffer should be capped
const contextLength = 200_000;
const maxTokens = 64_000;
const model = createModel(contextLength, maxTokens);
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);
});

View file

@ -5,12 +5,11 @@ import type { ChatCompletionTool } from "openai/resources/chat/completions.mjs";
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_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;
const DEFAULT_CONTEXT_LENGTH_FOR_COMPACTION = 200_000;
/**
* Get the context length limit for a model
* @param modelName The model name
@ -18,17 +17,58 @@ 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
);
}
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
// 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 +81,7 @@ function countContentTokens(content: string | any[]): number {
tokenCount += 1024; // Rough estimate for image tokens
}
}
return tokenCount;
return getAdjustedTokenCountFromModel(tokenCount, model);
}
return 0;
@ -91,6 +131,7 @@ function countToolOutputTokens(
*/
export function countChatHistoryItemTokens(
historyItem: ChatHistoryItem,
model: ModelConfig,
): number {
try {
let tokenCount = 0;
@ -98,7 +139,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 +195,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 +325,7 @@ export function countToolDefinitionTokens(tools: ChatCompletionTool[]): number {
*/
export interface TotalInputTokenParams {
chatHistory: ChatHistoryItem[];
model: ModelConfig;
systemMessage?: string;
tools?: ChatCompletionTool[];
}
@ -304,7 +339,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) {
@ -325,79 +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,
});
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);
const availableForInput = contextLimit - reservedForOutput;
// Ensure we have positive space available for input
if (availableForInput <= 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;
logger.debug("Context usage check", {
inputTokens,
historyTokens: countChatHistoryTokens(chatHistory),
systemTokens,
toolTokens,
contextLimit,
maxTokens,
reservedForOutput,
availableForInput,
usage: `${Math.round(usage * 100)}%`,
threshold: `${Math.round(AUTO_COMPACT_THRESHOLD * 100)}%`,
shouldCompact: usage >= AUTO_COMPACT_THRESHOLD,
});
return usage >= AUTO_COMPACT_THRESHOLD;
}
/**
* 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
*/
@ -428,6 +390,7 @@ export function validateContextLength(params: ValidateContextLengthParams): {
chatHistory,
systemMessage,
tools,
model,
});
const contextLimit = getModelContextLimit(model);
const maxTokens = model.defaultCompletionOptions?.maxTokens || 0;