feat: proportional output truncation for read and bash

This commit is contained in:
Dallin Romney 2026-01-21 17:37:17 -08:00
parent b4bc3aedaa
commit c754289118
8 changed files with 166 additions and 79 deletions

View file

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

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

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

View file

@ -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<string> => {
run: async (
args: { filepath: string },
context?: ToolRunContext,
): Promise<string> => {
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.`,
);

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

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

View file

@ -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;
}
/**