feat: CLI tool truncation and docs

This commit is contained in:
Dallin Romney 2026-01-09 15:57:28 -08:00
parent 9a630a025d
commit 34537d926f
10 changed files with 841 additions and 200 deletions

View file

@ -0,0 +1,29 @@
---
title: "CLI Configuration"
description: "Configure Continue CLI behavior with environment variables"
sidebarTitle: "Configuration"
---
Continue CLI tools automatically truncate large outputs to prevent excessive token usage. You can customize these limits using environment variables.
## Environment Variables
| Environment Variable | Tool | Default |
|---------------------|------|--------:|
| `CONTINUE_CLI_BASH_MAX_OUTPUT_CHARS` | Bash | 50,000 |
| `CONTINUE_CLI_BASH_MAX_OUTPUT_LINES` | Bash | 1,000 |
| `CONTINUE_CLI_READ_FILE_MAX_OUTPUT_CHARS` | Read | 500,000 |
| `CONTINUE_CLI_READ_FILE_MAX_OUTPUT_LINES` | Read | 5,000 |
| `CONTINUE_CLI_FETCH_MAX_OUTPUT_LENGTH` | Fetch | 20,000 |
| `CONTINUE_CLI_DIFF_MAX_OUTPUT_LENGTH` | Diff | 50,000 |
| `CONTINUE_CLI_SEARCH_CODE_MAX_RESULTS` | Search | 100 |
| `CONTINUE_CLI_SEARCH_CODE_MAX_RESULT_CHARS` | Search | 1,000 |
## Example
```bash
# Increase limits for verbose build output
export CONTINUE_CLI_BASH_MAX_OUTPUT_CHARS=100000
export CONTINUE_CLI_BASH_MAX_OUTPUT_LINES=2000
cn
```

View file

@ -91,7 +91,8 @@
"cli/overview",
"cli/install",
"cli/quick-start",
"cli/guides"
"cli/guides",
"cli/configuration"
]
},
{

View file

@ -2,8 +2,23 @@ import type { ContextItem } from "core/index.js";
import { fetchUrlContentImpl } from "core/tools/implementations/fetchUrlContent.js";
import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
import {
parseEnvNumber,
truncateOutputFromEnd,
} from "../util/truncateOutput.js";
import { Tool } from "./types.js";
// Output truncation defaults
const DEFAULT_FETCH_MAX_CHARS = 20000;
function getFetchMaxChars(): number {
return parseEnvNumber(
process.env.CONTINUE_CLI_FETCH_MAX_OUTPUT_LENGTH,
DEFAULT_FETCH_MAX_CHARS,
);
}
export const fetchTool: Tool = {
name: "Fetch",
displayName: "Fetch",
@ -54,14 +69,20 @@ export const fetchTool: Tool = {
}
// Format the results for CLI display
return contextItems
.map((item: ContextItem) => {
if (item.name === "Truncation warning") {
return item.content;
}
return item.content;
})
const combinedContent = contextItems
.filter((item: ContextItem) => item.name !== "Truncation warning")
.map((item: ContextItem) => item.content)
.join("\n\n");
// Apply CLI-level truncation
const maxChars = getFetchMaxChars();
const { output: truncatedOutput } = truncateOutputFromEnd(
combinedContent,
maxChars,
"fetched content",
);
return truncatedOutput;
} catch (error) {
if (error instanceof ContinueError) {
throw error;

View file

@ -3,9 +3,32 @@ 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 { formatToolArgument } from "./formatters.js";
import { Tool } from "./types.js";
// Output truncation defaults
const DEFAULT_READ_FILE_MAX_CHARS = 500000; // ~500KB
const DEFAULT_READ_FILE_MAX_LINES = 5000;
function getReadFileMaxChars(): number {
return parseEnvNumber(
process.env.CONTINUE_CLI_READ_FILE_MAX_OUTPUT_CHARS,
DEFAULT_READ_FILE_MAX_CHARS,
);
}
function getReadFileMaxLines(): number {
return parseEnvNumber(
process.env.CONTINUE_CLI_READ_FILE_MAX_OUTPUT_LINES,
DEFAULT_READ_FILE_MAX_LINES,
);
}
// Track files that have been read in the current session
export const readFilesSet = new Set<string>();
export function markFileAsRead(filePath: string) {
@ -62,13 +85,17 @@ export const readFileTool: Tool = {
// Mark this file as read for the edit tool
markFileAsRead(realPath);
const lines = content.split("\n");
if (lines.length > 5000) {
const truncatedContent = lines.slice(0, 5000).join("\n");
return `Content of ${filepath} (truncated to first 5000 lines of ${lines.length} total):\n${truncatedContent}`;
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${content}`;
return `Content of ${filepath}:\n${truncatedContent}`;
} catch (error) {
if (error instanceof ContinueError) {
throw error;

View file

@ -10,10 +10,31 @@ import {
isGitCommitCommand,
isPullRequestCommand,
} from "../telemetry/utils.js";
import { truncateOutputFromStart } from "../util/truncateOutput.js";
import {
parseEnvNumber,
truncateOutputFromStart,
} from "../util/truncateOutput.js";
import { Tool } from "./types.js";
// Output truncation defaults
const DEFAULT_BASH_MAX_CHARS = 50000;
const DEFAULT_BASH_MAX_LINES = 1000;
function getBashMaxChars(): number {
return parseEnvNumber(
process.env.CONTINUE_CLI_BASH_MAX_OUTPUT_CHARS,
DEFAULT_BASH_MAX_CHARS,
);
}
function getBashMaxLines(): number {
return parseEnvNumber(
process.env.CONTINUE_CLI_BASH_MAX_OUTPUT_LINES,
DEFAULT_BASH_MAX_LINES,
);
}
// Helper function to use login shell on Unix/macOS and PowerShell on Windows
function getShellCommand(command: string): { shell: string; args: string[] } {
if (process.platform === "win32") {
@ -121,7 +142,12 @@ 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).output);
resolve(
truncateOutputFromStart(output, {
maxChars: getBashMaxChars(),
maxLines: getBashMaxLines(),
}).output,
);
}, TIMEOUT_MS);
};
@ -166,7 +192,12 @@ IMPORTANT: To edit files, use Edit/MultiEdit tools instead of bash commands (sed
output = stdout + `\nStderr: ${stderr}`;
}
resolve(truncateOutputFromStart(output).output);
resolve(
truncateOutputFromStart(output, {
maxChars: getBashMaxChars(),
maxLines: getBashMaxLines(),
}).output,
);
});
child.on("error", (error) => {

View file

@ -5,6 +5,8 @@ import * as util from "util";
import { ContinueError, ContinueErrorReason } from "core/util/errors.js";
import { findUp } from "find-up";
import { parseEnvNumber } from "../util/truncateOutput.js";
import { Tool } from "./types.js";
const execPromise = util.promisify(child_process.exec);
@ -80,9 +82,23 @@ async function searchWithGrepOrFindstr(
return await execPromise(command, { cwd: searchPath });
}
// Default maximum number of results to display
const DEFAULT_MAX_RESULTS = 100;
const MAX_LINE_LENGTH = 1000;
// Output truncation defaults
const DEFAULT_SEARCH_MAX_RESULTS = 100;
const DEFAULT_SEARCH_MAX_RESULT_CHARS = 1000; // Max chars per result line
function getSearchMaxResults(): number {
return parseEnvNumber(
process.env.CONTINUE_CLI_SEARCH_CODE_MAX_RESULTS,
DEFAULT_SEARCH_MAX_RESULTS,
);
}
function getSearchMaxResultChars(): number {
return parseEnvNumber(
process.env.CONTINUE_CLI_SEARCH_CODE_MAX_RESULT_CHARS,
DEFAULT_SEARCH_MAX_RESULT_CHARS,
);
}
export const searchCodeTool: Tool = {
name: "Search",
@ -168,19 +184,22 @@ export const searchCodeTool: Tool = {
}
// Split the results into lines and limit the number of results
const maxResults = getSearchMaxResults();
const maxResultChars = getSearchMaxResultChars();
const splitLines = stdout.split("\n");
const lines = splitLines.filter((line) => line.length <= MAX_LINE_LENGTH);
const lines = splitLines.filter((line) => line.length <= maxResultChars);
if (lines.length === 0) {
return `No matches found for pattern "${args.pattern}"${
args.file_pattern ? ` in files matching "${args.file_pattern}"` : ""
}.`;
}
const truncated = lines.length > DEFAULT_MAX_RESULTS;
const limitedLines = lines.slice(0, DEFAULT_MAX_RESULTS);
const truncated = lines.length > maxResults;
const limitedLines = lines.slice(0, maxResults);
const resultText = limitedLines.join("\n");
const truncationMessage = truncated
? `\n\n[Results truncated: showing ${DEFAULT_MAX_RESULTS} of ${lines.length} matches]`
? `\n\n[Results truncated: showing ${maxResults} of ${lines.length} matches]`
: "";
return `Search results for pattern "${args.pattern}"${

View file

@ -2,8 +2,23 @@ import * as child_process from "child_process";
import * as fs from "fs";
import * as util from "util";
import {
parseEnvNumber,
truncateOutputFromEnd,
} from "../util/truncateOutput.js";
import { Tool } from "./types.js";
// Output truncation defaults
const DEFAULT_DIFF_MAX_CHARS = 50000;
function getDiffMaxChars(): number {
return parseEnvNumber(
process.env.CONTINUE_CLI_DIFF_MAX_OUTPUT_LENGTH,
DEFAULT_DIFF_MAX_CHARS,
);
}
const execPromise = util.promisify(child_process.exec);
export const viewDiffTool: Tool = {
@ -60,7 +75,14 @@ export const viewDiffTool: Tool = {
return "No changes detected in the git repository.";
}
return `Git diff for repository at ${repoPath}:\n\n${stdout}`;
const maxChars = getDiffMaxChars();
const { output: truncatedOutput } = truncateOutputFromEnd(
stdout,
maxChars,
"diff output",
);
return `Git diff for repository at ${repoPath}:\n\n${truncatedOutput}`;
} catch (error) {
return `Error running git diff: ${
error instanceof Error ? error.message : String(error)

View file

@ -9,6 +9,7 @@ import {
countChatHistoryItemTokens,
countChatHistoryTokens,
countMessageTokens,
countToolDefinitionTokens,
getModelContextLimit,
shouldAutoCompact,
} from "./tokenizer.js";
@ -351,4 +352,301 @@ describe("tokenizer", () => {
});
});
});
describe("countToolDefinitionTokens", () => {
it("should return 0 for empty tools array", () => {
expect(countToolDefinitionTokens([])).toBe(0);
});
it("should return 0 for undefined-like input", () => {
// TypeScript types prevent undefined, but test defensive behavior
expect(countToolDefinitionTokens([] as never)).toBe(0);
});
it("should count tokens for a simple tool with name only", () => {
const tools = [
{
type: "function" as const,
function: {
name: "get_weather",
},
},
];
const tokenCount = countToolDefinitionTokens(tools);
// Base overhead (12) + tool tokens + wrapper overhead (12)
expect(tokenCount).toBeGreaterThan(24); // At least base overheads
expect(tokenCount).toBe(27); // 12 + 3 (name) + 12 = 27
});
it("should count tokens for a tool with name and description", () => {
const tools = [
{
type: "function" as const,
function: {
name: "get_weather",
description: "Get the current weather for a location",
},
},
];
const tokenCount = countToolDefinitionTokens(tools);
// 12 (base) + 3 (name) + 10 (description ~40 chars / 4) + 12 (wrapper) = 37
expect(tokenCount).toBeGreaterThan(27);
});
it("should count tokens for a tool with parameters", () => {
const tools = [
{
type: "function" as const,
function: {
name: "get_weather",
description: "Get weather",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The city name",
},
},
required: ["location"],
},
},
},
];
const tokenCount = countToolDefinitionTokens(tools);
expect(tokenCount).toBeGreaterThan(30); // Should include parameter tokens
});
it("should count tokens for multiple tools", () => {
const tools = [
{
type: "function" as const,
function: {
name: "tool_one",
},
},
{
type: "function" as const,
function: {
name: "tool_two",
},
},
];
const singleToolTokens = countToolDefinitionTokens([tools[0]]);
const doubleToolTokens = countToolDefinitionTokens(tools);
// Two tools should have more tokens than one
expect(doubleToolTokens).toBeGreaterThan(singleToolTokens);
});
it("should count tokens for parameters with enum values", () => {
const toolsWithoutEnum = [
{
type: "function" as const,
function: {
name: "set_mode",
parameters: {
type: "object",
properties: {
mode: {
type: "string",
description: "The mode to set",
},
},
},
},
},
];
const toolsWithEnum = [
{
type: "function" as const,
function: {
name: "set_mode",
parameters: {
type: "object",
properties: {
mode: {
type: "string",
description: "The mode to set",
enum: ["fast", "slow", "medium"],
},
},
},
},
},
];
const tokensWithoutEnum = countToolDefinitionTokens(toolsWithoutEnum);
const tokensWithEnum = countToolDefinitionTokens(toolsWithEnum);
// Enum values should add tokens
expect(tokensWithEnum).toBeGreaterThan(tokensWithoutEnum);
});
it("should count tokens for multiple parameters", () => {
const toolWithOneParam = [
{
type: "function" as const,
function: {
name: "search",
parameters: {
type: "object",
properties: {
query: {
type: "string",
},
},
},
},
},
];
const toolWithMultipleParams = [
{
type: "function" as const,
function: {
name: "search",
parameters: {
type: "object",
properties: {
query: {
type: "string",
},
limit: {
type: "number",
},
offset: {
type: "number",
},
},
},
},
},
];
const oneParamTokens = countToolDefinitionTokens(toolWithOneParam);
const multiParamTokens = countToolDefinitionTokens(
toolWithMultipleParams,
);
expect(multiParamTokens).toBeGreaterThan(oneParamTokens);
});
it("should handle tool with empty parameters object", () => {
const tools = [
{
type: "function" as const,
function: {
name: "no_params",
parameters: {
type: "object",
properties: {},
},
},
},
];
const tokenCount = countToolDefinitionTokens(tools);
// Should still return a valid count (base overhead + name)
expect(tokenCount).toBeGreaterThan(0);
});
it("should handle tool without parameters field", () => {
const tools = [
{
type: "function" as const,
function: {
name: "simple_tool",
description: "A simple tool without parameters",
},
},
];
const tokenCount = countToolDefinitionTokens(tools);
expect(tokenCount).toBeGreaterThan(0);
});
describe("real-world tool definitions", () => {
it("should count tokens for a complex tool like read_file", () => {
const tools = [
{
type: "function" as const,
function: {
name: "read_file",
description:
"Use this tool if you need to view the contents of an existing file.",
parameters: {
type: "object",
properties: {
filepath: {
type: "string",
description:
"The path of the file to read. Can be a relative path, absolute path, tilde path, or file:// URI",
},
},
required: ["filepath"],
},
},
},
];
const tokenCount = countToolDefinitionTokens(tools);
expect(tokenCount).toBeGreaterThan(40); // Complex tool should have many tokens
});
it("should count tokens for a multi-tool set", () => {
const tools = [
{
type: "function" as const,
function: {
name: "read_file",
description: "Read a file",
parameters: {
type: "object",
properties: {
filepath: { type: "string", description: "File path" },
},
},
},
},
{
type: "function" as const,
function: {
name: "write_file",
description: "Write to a file",
parameters: {
type: "object",
properties: {
filepath: { type: "string", description: "File path" },
content: { type: "string", description: "Content to write" },
},
},
},
},
{
type: "function" as const,
function: {
name: "search",
description: "Search for files",
parameters: {
type: "object",
properties: {
query: { type: "string", description: "Search query" },
},
},
},
},
];
const tokenCount = countToolDefinitionTokens(tools);
// Multiple tools should have significant token count
expect(tokenCount).toBeGreaterThan(80);
});
});
});
});

View file

@ -1,34 +1,31 @@
import {
DEFAULT_MAX_CHARACTERS,
DEFAULT_MAX_LINES,
getMaxCharacters,
getMaxLines,
parseEnvNumber,
truncateByLinesAndChars,
truncateLinesByCount,
truncateOutputFromEnd,
truncateOutputFromStart,
} from "./truncateOutput.js";
// Test constants matching the bash tool defaults
const DEFAULT_MAX_CHARS = 50000;
const DEFAULT_MAX_LINES = 1000;
const defaultLimits = {
maxChars: DEFAULT_MAX_CHARS,
maxLines: DEFAULT_MAX_LINES,
};
describe("truncateOutputFromStart", () => {
const originalEnv = process.env;
beforeEach(() => {
process.env = { ...originalEnv };
delete process.env.BASH_MAX_OUTPUT_LENGTH;
delete process.env.BASH_MAX_OUTPUT_LINES;
});
afterAll(() => {
process.env = originalEnv;
});
describe("no truncation needed", () => {
it("should return empty string unchanged", () => {
const result = truncateOutputFromStart("");
const result = truncateOutputFromStart("", defaultLimits);
expect(result.output).toBe("");
expect(result.wasTruncated).toBe(false);
});
it("should return short output unchanged", () => {
const input = "hello world\nline 2\nline 3";
const result = truncateOutputFromStart(input);
const result = truncateOutputFromStart(input, defaultLimits);
expect(result.output).toBe(input);
expect(result.wasTruncated).toBe(false);
});
@ -39,14 +36,14 @@ describe("truncateOutputFromStart", () => {
(_, i) => `line ${i + 1}`,
);
const input = lines.join("\n");
const result = truncateOutputFromStart(input);
const result = truncateOutputFromStart(input, defaultLimits);
expect(result.output).toBe(input);
expect(result.wasTruncated).toBe(false);
});
it("should return output at exactly max characters unchanged", () => {
const input = "a".repeat(DEFAULT_MAX_CHARACTERS);
const result = truncateOutputFromStart(input);
const input = "a".repeat(DEFAULT_MAX_CHARS);
const result = truncateOutputFromStart(input, defaultLimits);
expect(result.output).toBe(input);
expect(result.wasTruncated).toBe(false);
});
@ -60,7 +57,7 @@ describe("truncateOutputFromStart", () => {
(_, i) => `line ${i + 1}`,
);
const input = lines.join("\n");
const result = truncateOutputFromStart(input);
const result = truncateOutputFromStart(input, defaultLimits);
expect(result.wasTruncated).toBe(true);
expect(result.output).toContain("(previous 500 lines truncated)");
@ -76,7 +73,7 @@ describe("truncateOutputFromStart", () => {
(_, i) => `line ${i + 1}`,
);
const input = lines.join("\n");
const result = truncateOutputFromStart(input);
const result = truncateOutputFromStart(input, defaultLimits);
expect(result.wasTruncated).toBe(true);
expect(result.output).toContain(
@ -97,7 +94,7 @@ describe("truncateOutputFromStart", () => {
(_, i) => `line ${i + 1}`,
);
const input = lines.join("\n");
const result = truncateOutputFromStart(input);
const result = truncateOutputFromStart(input, defaultLimits);
expect(result.wasTruncated).toBe(true);
expect(result.output).toContain("(previous 1 lines truncated)");
@ -110,12 +107,12 @@ describe("truncateOutputFromStart", () => {
describe("truncation by character count", () => {
it("should truncate when exceeding max characters", () => {
// Create output that exceeds character limit but not line limit
const input = "a".repeat(DEFAULT_MAX_CHARACTERS + 10000);
const result = truncateOutputFromStart(input);
const input = "a".repeat(DEFAULT_MAX_CHARS + 10000);
const result = truncateOutputFromStart(input, defaultLimits);
expect(result.wasTruncated).toBe(true);
expect(result.output.length).toBeLessThanOrEqual(
DEFAULT_MAX_CHARACTERS + 100 /* header allowance */,
DEFAULT_MAX_CHARS + 100 /* header allowance */,
);
expect(result.output).toContain("characters truncated");
});
@ -124,7 +121,7 @@ describe("truncateOutputFromStart", () => {
// Create lines that exceed character limit
const line = "x".repeat(100) + "\n";
const input = line.repeat(600); // 60600 characters, 600 lines
const result = truncateOutputFromStart(input);
const result = truncateOutputFromStart(input, defaultLimits);
expect(result.wasTruncated).toBe(true);
// Should start at a line boundary (after truncation header)
@ -143,12 +140,12 @@ describe("truncateOutputFromStart", () => {
const lines = Array.from({ length: DEFAULT_MAX_LINES * 2 }, () => line);
const input = lines.join("\n");
const result = truncateOutputFromStart(input);
const result = truncateOutputFromStart(input, defaultLimits);
expect(result.wasTruncated).toBe(true);
// Should be truncated by lines first, then by characters
expect(result.output.length).toBeLessThanOrEqual(
DEFAULT_MAX_CHARACTERS + 100 /* header allowance */,
DEFAULT_MAX_CHARS + 100 /* header allowance */,
);
// Should have a single combined message, not duplicate notes
@ -165,23 +162,21 @@ describe("truncateOutputFromStart", () => {
describe("edge cases", () => {
it("should handle single very long line without newlines", () => {
const input = "z".repeat(DEFAULT_MAX_CHARACTERS + 10000);
const result = truncateOutputFromStart(input);
const input = "z".repeat(DEFAULT_MAX_CHARS + 10000);
const result = truncateOutputFromStart(input, defaultLimits);
expect(result.wasTruncated).toBe(true);
expect(result.output).toContain("characters truncated");
// Should keep approximately max chars (plus header)
expect(result.output.length).toBeLessThanOrEqual(
DEFAULT_MAX_CHARACTERS + 100,
);
expect(result.output.length).toBeGreaterThan(DEFAULT_MAX_CHARACTERS);
expect(result.output.length).toBeLessThanOrEqual(DEFAULT_MAX_CHARS + 100);
expect(result.output.length).toBeGreaterThan(DEFAULT_MAX_CHARS);
});
it("should not snap to line boundary if newline is too far into the text", () => {
// Create a massive line followed by a newline far from the truncation point
const leadingChars = DEFAULT_MAX_CHARACTERS + 5000;
const leadingChars = DEFAULT_MAX_CHARS + 5000;
const input = "a".repeat(leadingChars) + "\n" + "b".repeat(10);
const result = truncateOutputFromStart(input);
const result = truncateOutputFromStart(input, defaultLimits);
expect(result.wasTruncated).toBe(true);
// Should cut mid-line since newline is beyond snap threshold into kept text
@ -193,12 +188,10 @@ describe("truncateOutputFromStart", () => {
it("should snap to line boundary if newline is within snap threshold", () => {
// Create text where truncation point lands within snap threshold of a newline
const charsBeforeNewline = DEFAULT_MAX_CHARACTERS / 5; // Well under max
const charsBeforeNewline = DEFAULT_MAX_CHARS / 5; // Well under max
const input =
"a".repeat(charsBeforeNewline) +
"\n" +
"b".repeat(DEFAULT_MAX_CHARACTERS);
const result = truncateOutputFromStart(input);
"a".repeat(charsBeforeNewline) + "\n" + "b".repeat(DEFAULT_MAX_CHARS);
const result = truncateOutputFromStart(input, defaultLimits);
expect(result.wasTruncated).toBe(true);
// Newline should be within snap threshold, so should start with 'b'
@ -209,7 +202,7 @@ describe("truncateOutputFromStart", () => {
it("should handle output with only newlines", () => {
const input = "\n".repeat(DEFAULT_MAX_LINES + 500);
const result = truncateOutputFromStart(input);
const result = truncateOutputFromStart(input, defaultLimits);
expect(result.wasTruncated).toBe(true);
expect(result.output).toContain("lines truncated)");
@ -221,134 +214,216 @@ describe("truncateOutputFromStart", () => {
i % 2 === 0 ? `content line ${i}` : "",
);
const input = lines.join("\n");
const result = truncateOutputFromStart(input);
const result = truncateOutputFromStart(input, defaultLimits);
expect(result.wasTruncated).toBe(true);
expect(result.output).toContain("(previous 200 lines truncated)");
});
});
describe("environment variable configuration", () => {
describe("getMaxCharacters", () => {
it("should return default when env var is not set", () => {
expect(getMaxCharacters()).toBe(DEFAULT_MAX_CHARACTERS);
describe("with custom limits", () => {
it("should use custom character limit", () => {
const input = "a".repeat(1500);
const result = truncateOutputFromStart(input, {
maxChars: 1000,
maxLines: 10000,
});
it("should return env var value when set to valid number", () => {
process.env.BASH_MAX_OUTPUT_LENGTH = "100000";
expect(getMaxCharacters()).toBe(100000);
});
it("should return default when env var is empty string", () => {
process.env.BASH_MAX_OUTPUT_LENGTH = "";
expect(getMaxCharacters()).toBe(DEFAULT_MAX_CHARACTERS);
});
it("should return default when env var is not a number", () => {
process.env.BASH_MAX_OUTPUT_LENGTH = "not-a-number";
expect(getMaxCharacters()).toBe(DEFAULT_MAX_CHARACTERS);
});
it("should return default when env var is zero", () => {
process.env.BASH_MAX_OUTPUT_LENGTH = "0";
expect(getMaxCharacters()).toBe(DEFAULT_MAX_CHARACTERS);
});
it("should return default when env var is negative", () => {
process.env.BASH_MAX_OUTPUT_LENGTH = "-100";
expect(getMaxCharacters()).toBe(DEFAULT_MAX_CHARACTERS);
});
it("should parse integer from float string", () => {
process.env.BASH_MAX_OUTPUT_LENGTH = "12345.67";
expect(getMaxCharacters()).toBe(12345);
});
expect(result.wasTruncated).toBe(true);
expect(result.output).toContain("characters truncated");
// Output should be around 1000 chars plus header
expect(result.output.length).toBeLessThanOrEqual(1100);
});
describe("getMaxLines", () => {
it("should return default when env var is not set", () => {
expect(getMaxLines()).toBe(DEFAULT_MAX_LINES);
it("should use custom line limit", () => {
const lines = Array.from({ length: 100 }, (_, i) => `line ${i + 1}`);
const input = lines.join("\n");
const result = truncateOutputFromStart(input, {
maxChars: 100000,
maxLines: 50,
});
it("should return env var value when set to valid number", () => {
process.env.BASH_MAX_OUTPUT_LINES = "5000";
expect(getMaxLines()).toBe(5000);
});
it("should return default when env var is empty string", () => {
process.env.BASH_MAX_OUTPUT_LINES = "";
expect(getMaxLines()).toBe(DEFAULT_MAX_LINES);
});
it("should return default when env var is not a number", () => {
process.env.BASH_MAX_OUTPUT_LINES = "invalid";
expect(getMaxLines()).toBe(DEFAULT_MAX_LINES);
});
it("should return default when env var is zero", () => {
process.env.BASH_MAX_OUTPUT_LINES = "0";
expect(getMaxLines()).toBe(DEFAULT_MAX_LINES);
});
it("should return default when env var is negative", () => {
process.env.BASH_MAX_OUTPUT_LINES = "-500";
expect(getMaxLines()).toBe(DEFAULT_MAX_LINES);
});
expect(result.wasTruncated).toBe(true);
expect(result.output).toContain("(previous 50 lines truncated)");
expect(result.output).toContain("line 51");
expect(result.output).toContain("line 100");
});
describe("truncateOutputFromStart with custom limits", () => {
it("should use custom character limit from env var", () => {
process.env.BASH_MAX_OUTPUT_LENGTH = "1000";
const input = "a".repeat(1500);
const result = truncateOutputFromStart(input);
expect(result.wasTruncated).toBe(true);
expect(result.output).toContain("characters truncated");
// Output should be around 1000 chars plus header
expect(result.output.length).toBeLessThanOrEqual(1100);
it("should use both custom limits together", () => {
// Create 200 lines of 10 chars each = 2000+ chars, exceeding both limits
const lines = Array.from({ length: 200 }, () => "x".repeat(10));
const input = lines.join("\n");
const result = truncateOutputFromStart(input, {
maxChars: 500,
maxLines: 100,
});
it("should use custom line limit from env var", () => {
process.env.BASH_MAX_OUTPUT_LINES = "50";
const lines = Array.from({ length: 100 }, (_, i) => `line ${i + 1}`);
const input = lines.join("\n");
const result = truncateOutputFromStart(input);
expect(result.wasTruncated).toBe(true);
// Should be truncated by lines first (to 100), then by characters (to ~500)
expect(result.output.length).toBeLessThanOrEqual(600);
});
expect(result.wasTruncated).toBe(true);
expect(result.output).toContain("(previous 50 lines truncated)");
expect(result.output).toContain("line 51");
expect(result.output).toContain("line 100");
it("should not truncate when output is under custom limits", () => {
// Create output that would exceed default limits but not custom ones
const lines = Array.from(
{ length: DEFAULT_MAX_LINES + 500 },
(_, i) => `line ${i}`,
);
const input = lines.join("\n");
const result = truncateOutputFromStart(input, {
maxChars: 100000,
maxLines: 10000,
});
it("should use both custom limits together", () => {
process.env.BASH_MAX_OUTPUT_LENGTH = "500";
process.env.BASH_MAX_OUTPUT_LINES = "100";
// Create 200 lines of 10 chars each = 2000+ chars, exceeding both limits
const lines = Array.from({ length: 200 }, () => "x".repeat(10));
const input = lines.join("\n");
const result = truncateOutputFromStart(input);
expect(result.wasTruncated).toBe(true);
// Should be truncated by lines first (to 100), then by characters (to ~500)
expect(result.output.length).toBeLessThanOrEqual(600);
});
it("should not truncate when output is under custom limits", () => {
process.env.BASH_MAX_OUTPUT_LENGTH = "100000";
process.env.BASH_MAX_OUTPUT_LINES = "10000";
// Create output that would exceed default limits but not custom ones
const lines = Array.from(
{ length: DEFAULT_MAX_LINES + 500 },
(_, i) => `line ${i}`,
);
const input = lines.join("\n");
const result = truncateOutputFromStart(input);
expect(result.wasTruncated).toBe(false);
expect(result.output).toBe(input);
});
expect(result.wasTruncated).toBe(false);
expect(result.output).toBe(input);
});
});
});
describe("parseEnvNumber", () => {
it("should return default when env var is undefined", () => {
expect(parseEnvNumber(undefined, 1000)).toBe(1000);
});
it("should return env var value when set to valid number", () => {
expect(parseEnvNumber("5000", 1000)).toBe(5000);
});
it("should return default when env var is empty string", () => {
expect(parseEnvNumber("", 1000)).toBe(1000);
});
it("should return default when env var is not a number", () => {
expect(parseEnvNumber("not-a-number", 1000)).toBe(1000);
});
it("should return default when env var is zero", () => {
expect(parseEnvNumber("0", 1000)).toBe(1000);
});
it("should return default when env var is negative", () => {
expect(parseEnvNumber("-100", 1000)).toBe(1000);
});
it("should parse integer from float string", () => {
expect(parseEnvNumber("12345.67", 1000)).toBe(12345);
});
});
describe("truncateOutputFromEnd", () => {
it("should return empty string unchanged", () => {
const result = truncateOutputFromEnd("", 1000);
expect(result.output).toBe("");
expect(result.wasTruncated).toBe(false);
});
it("should return short output unchanged", () => {
const input = "hello world";
const result = truncateOutputFromEnd(input, 1000);
expect(result.output).toBe(input);
expect(result.wasTruncated).toBe(false);
});
it("should truncate from end when exceeding max chars", () => {
const input = "a".repeat(100) + "b".repeat(100);
const result = truncateOutputFromEnd(input, 100);
expect(result.wasTruncated).toBe(true);
expect(result.output).toContain("a".repeat(100));
expect(result.output).not.toContain("b");
expect(result.output).toContain("characters");
expect(result.output).toContain("truncated");
});
it("should include context in truncation message", () => {
const input = "x".repeat(200);
const result = truncateOutputFromEnd(input, 100, "file content");
expect(result.wasTruncated).toBe(true);
expect(result.output).toContain("of file content");
});
it("should snap to line boundary when possible", () => {
const input = "line1\nline2\nline3\nline4\nline5";
const result = truncateOutputFromEnd(input, 15);
expect(result.wasTruncated).toBe(true);
// Should end at a line boundary
expect(result.output).toContain("line1\nline2");
});
});
describe("truncateLinesByCount", () => {
it("should return empty string unchanged", () => {
const result = truncateLinesByCount("", 100);
expect(result.output).toBe("");
expect(result.wasTruncated).toBe(false);
});
it("should return output unchanged when under limit", () => {
const input = "line1\nline2\nline3";
const result = truncateLinesByCount(input, 10);
expect(result.output).toBe(input);
expect(result.wasTruncated).toBe(false);
});
it("should truncate lines from end", () => {
const lines = Array.from({ length: 100 }, (_, i) => `line ${i + 1}`);
const input = lines.join("\n");
const result = truncateLinesByCount(input, 50);
expect(result.wasTruncated).toBe(true);
expect(result.output).toContain("line 1");
expect(result.output).toContain("line 50");
expect(result.output).not.toContain("line 51");
expect(result.output).toContain("50 lines");
expect(result.output).toContain("truncated");
});
it("should include context in truncation message", () => {
const lines = Array.from({ length: 100 }, (_, i) => `line ${i + 1}`);
const input = lines.join("\n");
const result = truncateLinesByCount(input, 50, "test output");
expect(result.output).toContain("of test output");
});
});
describe("truncateByLinesAndChars", () => {
it("should return empty string unchanged", () => {
const result = truncateByLinesAndChars("", 100, 1000);
expect(result.output).toBe("");
expect(result.wasTruncated).toBe(false);
});
it("should truncate by lines first", () => {
const lines = Array.from({ length: 100 }, (_, i) => `line ${i + 1}`);
const input = lines.join("\n");
const result = truncateByLinesAndChars(input, 50, 100000);
expect(result.wasTruncated).toBe(true);
expect(result.output).toContain("line 1");
expect(result.output).toContain("line 50");
expect(result.output).not.toContain("line 51");
});
it("should truncate by chars after lines if still too long", () => {
// Create 50 lines of 100 chars each = 5000+ chars
const lines = Array.from({ length: 50 }, () => "x".repeat(100));
const input = lines.join("\n");
const result = truncateByLinesAndChars(input, 100, 500);
expect(result.wasTruncated).toBe(true);
// Output should be around 500 chars plus truncation message
expect(result.output.length).toBeLessThan(700);
});
it("should include context in truncation message", () => {
const lines = Array.from({ length: 100 }, (_, i) => `line ${i + 1}`);
const input = lines.join("\n");
const result = truncateByLinesAndChars(input, 50, 100000, "file content");
expect(result.output).toContain("of file content");
});
});

View file

@ -1,8 +1,12 @@
export const DEFAULT_MAX_CHARACTERS = 50000;
export const DEFAULT_MAX_LINES = 1000;
// Threshold for snapping to line boundaries during character truncation
export const TRUNCATION_LINE_SNAP_THRESHOLD = 1000;
function parseEnvNumber(
/**
* Parses an environment variable as a positive integer.
* Returns the default value if the env var is not set, empty, not a number,
* zero, or negative.
*/
export function parseEnvNumber(
envVar: string | undefined,
defaultValue: number,
): number {
@ -16,35 +20,35 @@ function parseEnvNumber(
return parsed;
}
export function getMaxCharacters(): number {
return parseEnvNumber(
process.env.BASH_MAX_OUTPUT_LENGTH,
DEFAULT_MAX_CHARACTERS,
);
}
export function getMaxLines(): number {
return parseEnvNumber(process.env.BASH_MAX_OUTPUT_LINES, DEFAULT_MAX_LINES);
}
interface TruncationResult {
export interface TruncationResult {
output: string;
wasTruncated: boolean;
}
export interface TruncationLimits {
maxChars: number;
maxLines: number;
}
/**
* Truncates output from the beginning to fit within limits, preserving the end.
* This is the preferred truncation strategy for command output where the most
* recent output is typically most relevant.
*
* Limits: max 50000 characters OR 1000 lines, whichever is smaller.
* When truncated, removes content from the beginning and adds a "(previous output truncated)" note.
*
* @param output - The string to truncate
* @param limits - The character and line limits to apply
*/
export function truncateOutputFromStart(output: string): TruncationResult {
export function truncateOutputFromStart(
output: string,
limits: TruncationLimits,
): TruncationResult {
if (!output) {
return { output, wasTruncated: false };
}
const maxLines = getMaxLines();
const maxCharacters = getMaxCharacters();
const { maxChars, maxLines } = limits;
const lines = output.split("\n");
// Check if we need to truncate by lines first
@ -54,11 +58,11 @@ export function truncateOutputFromStart(output: string): TruncationResult {
const contentAfterLineTruncation = preservedLines.join("\n");
// After line truncation, check character limit
if (contentAfterLineTruncation.length > maxCharacters) {
if (contentAfterLineTruncation.length > maxChars) {
return truncateCharactersFromStart(
contentAfterLineTruncation,
linesTruncated,
maxCharacters,
maxChars,
);
}
@ -69,13 +73,127 @@ export function truncateOutputFromStart(output: string): TruncationResult {
}
// Check character limit
if (output.length > maxCharacters) {
return truncateCharactersFromStart(output, 0, maxCharacters);
if (output.length > maxChars) {
return truncateCharactersFromStart(output, 0, maxChars);
}
return { output, wasTruncated: false };
}
/**
* Truncates output from the end to fit within a character limit, preserving the beginning.
* Useful for content where the beginning is most important (e.g., file content, diffs).
*
* @param output - The string to truncate
* @param maxChars - Maximum characters to keep
* @param context - Optional context for the truncation message (e.g., "file content", "diff")
*/
export function truncateOutputFromEnd(
output: string,
maxChars: number,
context?: string,
): TruncationResult {
if (!output || output.length <= maxChars) {
return { output, wasTruncated: false };
}
const truncatedContent = output.slice(0, maxChars);
// Try to end at a clean line boundary
const lastNewline = truncatedContent.lastIndexOf("\n");
const shouldSnapToLine =
lastNewline !== -1 &&
truncatedContent.length - lastNewline < TRUNCATION_LINE_SNAP_THRESHOLD;
const cleanContent = shouldSnapToLine
? truncatedContent.slice(0, lastNewline)
: truncatedContent;
const actualCharsRemoved = output.length - cleanContent.length;
const contextStr = context ? ` of ${context}` : "";
const suffix = `\n\n(${actualCharsRemoved} characters${contextStr} truncated)`;
return {
output: cleanContent + suffix,
wasTruncated: true,
};
}
/**
* Truncates output by line count from the end, preserving the beginning.
* Useful for file content where the start of the file is most relevant.
*
* @param output - The string to truncate
* @param maxLines - Maximum lines to keep
* @param context - Optional context for the truncation message
*/
export function truncateLinesByCount(
output: string,
maxLines: number,
context?: string,
): TruncationResult {
if (!output) {
return { output, wasTruncated: false };
}
const lines = output.split("\n");
if (lines.length <= maxLines) {
return { output, wasTruncated: false };
}
const preservedLines = lines.slice(0, maxLines);
const linesTruncated = lines.length - maxLines;
const contextStr = context ? ` of ${context}` : "";
return {
output:
preservedLines.join("\n") +
`\n\n(${linesTruncated} lines${contextStr} truncated)`,
wasTruncated: true,
};
}
/**
* Combined truncation: first by lines, then by characters, preserving the beginning.
* Used by readFile tool where both limits apply.
*
* @param output - The string to truncate
* @param maxLines - Maximum lines to keep
* @param maxChars - Maximum characters to keep
* @param context - Optional context for the truncation message
*/
export function truncateByLinesAndChars(
output: string,
maxLines: number,
maxChars: number,
context?: string,
): TruncationResult {
if (!output) {
return { output, wasTruncated: false };
}
// First truncate by lines
const lineResult = truncateLinesByCount(output, maxLines, context);
// Then truncate by characters if needed
if (lineResult.output.length > maxChars) {
const charResult = truncateOutputFromEnd(
lineResult.output,
maxChars,
context,
);
return {
output: charResult.output,
wasTruncated: true,
};
}
return lineResult;
}
// =============================================================================
// Internal helper functions
// =============================================================================
function truncateCharactersFromStart(
text: string,
linesTruncated: number,