返回源码地图

packages/coding-agent/src/core/tools/truncate.ts

v1.3.0 · 71023aec1546 · 08:文本截断常量和读取契约

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1/**
2 * Shared truncation utilities for tool outputs.
3 *
4 * Truncation is based on two independent limits - whichever is hit first wins:
5 * - Line limit (default: 2000 lines)
6 * - Byte limit (default: 50KB)
7 *
8 * Never returns partial lines (except bash tail truncation edge case).
9 */
10
11export const DEFAULT_MAX_LINES = 2000;
12export const DEFAULT_MAX_BYTES = 50 * 1024; // 50KB
13export const GREP_MAX_LINE_LENGTH = 500; // Max chars per grep match line
14
15export interface TruncationResult {
16 /** The truncated content */
17 content: string;
18 /** Whether truncation occurred */
19 truncated: boolean;
20 /** Which limit was hit: "lines", "bytes", or null if not truncated */
21 truncatedBy: "lines" | "bytes" | null;
22 /** Total number of lines in the original content */
23 totalLines: number;
24 /** Total number of bytes in the original content */
25 totalBytes: number;
26 /** Number of complete lines in the truncated output */
27 outputLines: number;
28 /** Number of bytes in the truncated output */
29 outputBytes: number;
30 /** Whether the last line was partially truncated (only for tail truncation edge case) */
31 lastLinePartial: boolean;
32 /** Whether the first line exceeded the byte limit (for head truncation) */
33 firstLineExceedsLimit: boolean;
34 /** The max lines limit that was applied */
35 maxLines: number;
36 /** The max bytes limit that was applied */
37 maxBytes: number;
38}
39
40export interface TruncationOptions {
41 /** Maximum number of lines (default: 2000) */
42 maxLines?: number;
43 /** Maximum number of bytes (default: 50KB) */
44 maxBytes?: number;
45}
46
47function splitLinesForCounting(content: string): string[] {
48 if (content.length === 0) {
49 return [];
50 }
51 const lines = content.split("\n");
52 if (content.endsWith("\n")) {
53 lines.pop();
54 }
55 return lines;
56}
57
58/**
59 * Format bytes as human-readable size.
60 */
61export function formatSize(bytes: number): string {
62 if (bytes < 1024) {
63 return `${bytes}B`;
64 } else if (bytes < 1024 * 1024) {
65 return `${(bytes / 1024).toFixed(1)}KB`;
66 } else {
67 return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
68 }
69}
70
71/**
72 * Truncate content from the head (keep first N lines/bytes).
73 * Suitable for file reads where you want to see the beginning.
74 *
75 * Never returns partial lines. If first line exceeds byte limit,
76 * returns empty content with firstLineExceedsLimit=true.
77 */
78export function truncateHead(content: string, options: TruncationOptions = {}): TruncationResult {
79 const maxLines = options.maxLines ?? DEFAULT_MAX_LINES;
80 const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
81
82 const totalBytes = Buffer.byteLength(content, "utf-8");
83 const lines = splitLinesForCounting(content);
84 const totalLines = lines.length;
85
86 // Check if no truncation needed
87 if (totalLines <= maxLines && totalBytes <= maxBytes) {
88 return {
89 content,
90 truncated: false,
91 truncatedBy: null,
92 totalLines,
93 totalBytes,
94 outputLines: totalLines,
95 outputBytes: totalBytes,
96 lastLinePartial: false,
97 firstLineExceedsLimit: false,
98 maxLines,
99 maxBytes,
100 };
101 }
102
103 // Check if first line alone exceeds byte limit
104 const firstLineBytes = Buffer.byteLength(lines[0], "utf-8");
105 if (firstLineBytes > maxBytes) {
106 return {
107 content: "",
108 truncated: true,
109 truncatedBy: "bytes",
110 totalLines,
111 totalBytes,
112 outputLines: 0,
113 outputBytes: 0,
114 lastLinePartial: false,
115 firstLineExceedsLimit: true,
116 maxLines,
117 maxBytes,
118 };
119 }
120
121 // Collect complete lines that fit
122 const outputLinesArr: string[] = [];
123 let outputBytesCount = 0;
124 let truncatedBy: "lines" | "bytes" = "lines";
125
126 for (let i = 0; i < lines.length && i < maxLines; i++) {
127 const line = lines[i];
128 const lineBytes = Buffer.byteLength(line, "utf-8") + (i > 0 ? 1 : 0); // +1 for newline
129
130 if (outputBytesCount + lineBytes > maxBytes) {
131 truncatedBy = "bytes";
132 break;
133 }
134
135 outputLinesArr.push(line);
136 outputBytesCount += lineBytes;
137 }
138
139 // If we exited due to line limit
140 if (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) {
141 truncatedBy = "lines";
142 }
143
144 const outputContent = outputLinesArr.join("\n");
145 const finalOutputBytes = Buffer.byteLength(outputContent, "utf-8");
146
147 return {
148 content: outputContent,
149 truncated: true,
150 truncatedBy,
151 totalLines,
152 totalBytes,
153 outputLines: outputLinesArr.length,
154 outputBytes: finalOutputBytes,
155 lastLinePartial: false,
156 firstLineExceedsLimit: false,
157 maxLines,
158 maxBytes,
159 };
160}
161
162/**
163 * Truncate content from the tail (keep last N lines/bytes).
164 * Suitable for bash output where you want to see the end (errors, final results).
165 *
166 * May return partial first line if the last line of original content exceeds byte limit.
167 */
168export function truncateTail(content: string, options: TruncationOptions = {}): TruncationResult {
169 const maxLines = options.maxLines ?? DEFAULT_MAX_LINES;
170 const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
171
172 const totalBytes = Buffer.byteLength(content, "utf-8");
173 const lines = splitLinesForCounting(content);
174 const totalLines = lines.length;
175
176 // Check if no truncation needed
177 if (totalLines <= maxLines && totalBytes <= maxBytes) {
178 return {
179 content,
180 truncated: false,
181 truncatedBy: null,
182 totalLines,
183 totalBytes,
184 outputLines: totalLines,
185 outputBytes: totalBytes,
186 lastLinePartial: false,
187 firstLineExceedsLimit: false,
188 maxLines,
189 maxBytes,
190 };
191 }
192
193 // Work backwards from the end
194 const outputLinesArr: string[] = [];
195 let outputBytesCount = 0;
196 let truncatedBy: "lines" | "bytes" = "lines";
197 let lastLinePartial = false;
198
199 for (let i = lines.length - 1; i >= 0 && outputLinesArr.length < maxLines; i--) {
200 const line = lines[i];
201 const lineBytes = Buffer.byteLength(line, "utf-8") + (outputLinesArr.length > 0 ? 1 : 0); // +1 for newline
202
203 if (outputBytesCount + lineBytes > maxBytes) {
204 truncatedBy = "bytes";
205 // Edge case: if we haven't added ANY lines yet and this line exceeds maxBytes,
206 // take the end of the line (partial)
207 if (outputLinesArr.length === 0) {
208 const truncatedLine = truncateStringToBytesFromEnd(line, maxBytes);
209 outputLinesArr.unshift(truncatedLine);
210 outputBytesCount = Buffer.byteLength(truncatedLine, "utf-8");
211 lastLinePartial = true;
212 }
213 break;
214 }
215
216 outputLinesArr.unshift(line);
217 outputBytesCount += lineBytes;
218 }
219
220 // If we exited due to line limit
221 if (outputLinesArr.length >= maxLines && outputBytesCount <= maxBytes) {
222 truncatedBy = "lines";
223 }
224
225 const outputContent = outputLinesArr.join("\n");
226 const finalOutputBytes = Buffer.byteLength(outputContent, "utf-8");
227
228 return {
229 content: outputContent,
230 truncated: true,
231 truncatedBy,
232 totalLines,
233 totalBytes,
234 outputLines: outputLinesArr.length,
235 outputBytes: finalOutputBytes,
236 lastLinePartial,
237 firstLineExceedsLimit: false,
238 maxLines,
239 maxBytes,
240 };
241}
242
243/**
244 * Truncate a string to fit within a byte limit (from the end).
245 * Handles multi-byte UTF-8 characters correctly.
246 */
247function truncateStringToBytesFromEnd(str: string, maxBytes: number): string {
248 const buf = Buffer.from(str, "utf-8");
249 if (buf.length <= maxBytes) {
250 return str;
251 }
252
253 // Start from the end, skip maxBytes back
254 let start = buf.length - maxBytes;
255
256 // Find a valid UTF-8 boundary (start of a character)
257 while (start < buf.length && (buf[start] & 0xc0) === 0x80) {
258 start++;
259 }
260
261 return buf.slice(start).toString("utf-8");
262}
263
264/**
265 * Truncate a single line to max characters, adding [truncated] suffix.
266 * Used for grep match lines.
267 */
268export function truncateLine(
269 line: string,
270 maxChars: number = GREP_MAX_LINE_LENGTH,
271): { text: string; wasTruncated: boolean } {
272 if (line.length <= maxChars) {
273 return { text: line, wasTruncated: false };
274 }
275 return { text: `${line.slice(0, maxChars)}... [truncated]`, wasTruncated: true };
276}
277
278export interface MiddleTruncationResult {
279 /** The start and end of the content with a `…N chars truncated…` marker between them. */
280 content: string;
281 truncated: boolean;
282 /** Characters left out. */
283 removedChars: number;
284 totalBytes: number;
285 totalLines: number;
286}
287
288/**
289 * Keep the start and the end of `content`, half of `maxBytes` each, and replace the middle with a
290 * `…N chars truncated…` marker, like Codex does for tool output. Cuts only at character boundaries.
291 */
292export function truncateMiddle(content: string, maxBytes: number): MiddleTruncationResult {
293 const buf = Buffer.from(content, "utf-8");
294 const totalLines = splitLinesForCounting(content).length;
295 if (buf.length <= maxBytes) {
296 return { content, truncated: false, removedChars: 0, totalBytes: buf.length, totalLines };
297 }
298 // Continuation bytes (10xxxxxx) are not character starts.
299 const isBoundary = (index: number) => index >= buf.length || (buf[index] & 0xc0) !== 0x80;
300 let headEnd = Math.floor(maxBytes / 2);
301 while (headEnd > 0 && !isBoundary(headEnd)) headEnd--;
302 let tailStart = buf.length - (maxBytes - Math.floor(maxBytes / 2));
303 while (tailStart < buf.length && !isBoundary(tailStart)) tailStart++;
304 const head = buf.subarray(0, headEnd).toString("utf-8");
305 const tail = buf.subarray(tailStart).toString("utf-8");
306 const removedChars = Array.from(buf.subarray(headEnd, tailStart).toString("utf-8")).length;
307 return {
308 content: `${head}…${removedChars} chars truncated…${tail}`,
309 truncated: true,
310 removedChars,
311 totalBytes: buf.length,
312 totalLines,
313 };
314}