Skip to content

Commit 1163104

Browse files
author
linyuan.yang
committed
read tool
1 parent 3fc2c45 commit 1163104

2 files changed

Lines changed: 134 additions & 108 deletions

File tree

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
1-
Reads a text file and returns its content with line numbers in the format "line_number: line_content". Default 2000 lines per call, capped at 50KB of output. Path must be absolute.
1+
Reads a text file. Path must be absolute. Output is capped at 50KB.
22
IMPORTANT: Do NOT use read to search for content inside files. Use grep first to locate exact line numbers, then use offset+limit to read only the relevant section. Reading entire files to find content wastes context and is strongly discouraged.
3-
- offset + limit: read a specific line range (e.g. offset=50 limit=40 reads lines 50–89).
4-
- tail: efficiently read the last N lines (mutually exclusive with offset/limit).
3+
4+
mode (default "line"):
5+
- "line": offset = 1-indexed start line; limit = max lines (default 2000). Example: offset=50 limit=40 reads lines 50–89.
6+
- "byte": offset = 0-indexed start byte; limit = max bytes (capped at 50KB). Use this for tool-overflow spill files — the truncation marker gives exact byte ranges, plug them in directly.
7+
- "endLine": offset = number of lines back from EOF where the read starts; defaults to limit. Pass just limit=N to read the last N lines.
8+
- "endByte": offset = number of bytes back from EOF; defaults to limit. Pass just limit=N to read the last N bytes.
9+
510
- Returns "Did you mean?" suggestions when the file is not found.
611
- Automatically detects and rejects binary files; use read_media_file for binary files.
712
- Use ls to list directory contents instead of reading a directory path.

‎packages/sbot/src/Tools/FileSystem/content/read.ts‎

Lines changed: 126 additions & 105 deletions
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,29 @@ import { DynamicStructuredTool, type StructuredToolInterface } from '@langchain/
77
import { z } from 'zod';
88
import { LoggerService } from '../../../Core/LoggerService';
99
import { createTextContent, createErrorResult, createSuccessResult, MCPToolResult } from 'scorpio.ai';
10-
import { resolvePath, normalizeLineEndings } from '../utils';
10+
import { resolvePath } from '../utils';
1111
import { loadPrompt } from '../../../Core/PromptLoader';
1212

1313
const logger = LoggerService.getLogger('Tools/FileSystem/content/read.ts');
1414

15-
const DEFAULT_LIMIT = 2000;
16-
const MAX_LINE_LENGTH = 2000;
17-
const MAX_LINE_SUFFIX = `... (line truncated to ${MAX_LINE_LENGTH} chars)`;
15+
const DEFAULT_LINE_LIMIT = 2000;
16+
const MAX_LINE = 2000;
1817
const MAX_BYTES = 50 * 1024;
19-
const MAX_BYTES_LABEL = `${MAX_BYTES / 1024}KB`;
18+
const DEFAULT_BYTE_LIMIT = MAX_BYTES;
2019

2120
const BINARY_EXTS = new Set([
2221
'.zip', '.tar', '.gz', '.exe', '.dll', '.so', '.class', '.jar', '.war',
2322
'.7z', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.odt', '.ods',
2423
'.odp', '.bin', '.dat', '.obj', '.o', '.a', '.lib', '.wasm', '.pyc', '.pyo',
2524
]);
2625

26+
enum ReadMode {
27+
Line = 'line',
28+
Byte = 'byte',
29+
EndLine = 'endLine',
30+
EndByte = 'endByte',
31+
}
32+
2733
async function isBinaryFile(filepath: string, fileSize: number): Promise<boolean> {
2834
if (BINARY_EXTS.has(path.extname(filepath).toLowerCase())) return true;
2935
if (fileSize === 0) return false;
@@ -57,50 +63,120 @@ async function countLines(filepath: string): Promise<number> {
5763
return count;
5864
}
5965

60-
async function tailLines(filepath: string, numLines: number): Promise<{ lines: string[]; totalLines: number }> {
61-
const totalLines = await countLines(filepath);
62-
if (totalLines === 0) return { lines: [], totalLines: 0 };
63-
64-
const CHUNK = 1024;
65-
const stats = await fsAsync.stat(filepath);
66-
const fh = await fsAsync.open(filepath, 'r');
66+
async function readByLines(abs: string, startLine: number, limit: number, totalHint?: number): Promise<MCPToolResult> {
67+
const stream = createReadStream(abs, { encoding: 'utf8' });
68+
const rl = createInterface({ input: stream, crlfDelay: Infinity });
69+
const start = startLine - 1;
70+
const raw: string[] = [];
71+
let bytes = 0;
72+
let lineCount = 0;
73+
let truncatedByBytes = false;
74+
let hasMoreLines = false;
6775
try {
68-
const lines: string[] = [];
69-
let position = stats.size;
70-
const buf = Buffer.alloc(CHUNK);
71-
let linesFound = 0;
72-
let remaining = '';
73-
while (position > 0 && linesFound < numLines) {
74-
const size = Math.min(CHUNK, position);
75-
position -= size;
76-
const { bytesRead } = await fh.read(buf, 0, size, position);
77-
if (!bytesRead) break;
78-
const chunk = normalizeLineEndings(buf.subarray(0, bytesRead).toString('utf-8')) + remaining;
79-
const parts = chunk.split('\n');
80-
if (position > 0) remaining = parts.shift()!;
81-
for (let i = parts.length - 1; i >= 0 && linesFound < numLines; i--) {
82-
lines.unshift(parts[i]);
83-
linesFound++;
84-
}
76+
for await (const text of rl) {
77+
lineCount++;
78+
if (lineCount <= start) continue;
79+
if (raw.length >= limit) { hasMoreLines = true; continue; }
80+
const line = text.length > MAX_LINE ? text.substring(0, MAX_LINE) + `... (line truncated to ${MAX_LINE} chars)` : text;
81+
const size = Buffer.byteLength(line, 'utf-8') + (raw.length > 0 ? 1 : 0);
82+
if (bytes + size > MAX_BYTES) { truncatedByBytes = true; hasMoreLines = true; break; }
83+
raw.push(line);
84+
bytes += size;
8585
}
86-
return { lines, totalLines };
86+
} finally {
87+
rl.close();
88+
stream.destroy();
89+
}
90+
91+
if (lineCount < start && !(lineCount === 0 && start === 0)) {
92+
return createErrorResult(`Offset ${startLine} is out of range for this file (${lineCount} lines)`);
93+
}
94+
95+
const lastReadLine = startLine + raw.length - 1;
96+
const nextOffset = lastReadLine + 1;
97+
const completelyRead = !hasMoreLines && !truncatedByBytes;
98+
// truncatedByBytes 时主流程提前 break,lineCount 不是文件总行数;其他情况下 lineCount 才等于总数
99+
const totalKnown = totalHint != null || !truncatedByBytes;
100+
const total = totalHint ?? lineCount;
101+
102+
const parts: string[] = [];
103+
104+
// 前置:起点之前没有读到的行
105+
if (startLine > 1) {
106+
const before = startLine - 1;
107+
parts.push(`(Above: ${before} earlier line${before === 1 ? '' : 's'} (1-${before}) not read. Use mode="line" offset=1 limit=${before} to read them.)`);
108+
}
109+
110+
parts.push(raw.join('\n'));
111+
112+
// 后置:终点之后没有读到的行
113+
if (completelyRead) {
114+
parts.push(`(End of file - total ${total} lines)`);
115+
} else if (totalKnown) {
116+
const after = total - lastReadLine;
117+
parts.push(`(Below: ${after} more line${after === 1 ? '' : 's'} (${nextOffset}-${total}) not read. Use mode="line" offset=${nextOffset} to continue.)`);
118+
} else {
119+
parts.push(`(Below: output capped at ${MAX_BYTES / 1024}KB after reading lines ${startLine}-${lastReadLine}; more lines follow, total unknown. Use mode="line" offset=${nextOffset} to continue.)`);
120+
}
121+
122+
return createSuccessResult(createTextContent(parts.join('\n\n')));
123+
}
124+
125+
async function readByBytes(abs: string, position: number, want: number, fileSize: number): Promise<MCPToolResult> {
126+
if (position > fileSize) {
127+
return createErrorResult(`Byte offset ${position} is past end of file (size ${fileSize})`);
128+
}
129+
let text: string;
130+
let bytesRead: number;
131+
const fh = await fsAsync.open(abs, 'r');
132+
try {
133+
const buf = Buffer.alloc(want);
134+
({ bytesRead } = await fh.read(buf, 0, want, position));
135+
// 对齐 UTF-8 字符边界,避免半截多字节字符
136+
let s = 0, e = bytesRead;
137+
while (s < e && (buf[s] & 0xC0) === 0x80) s++;
138+
while (e > s && (buf[e - 1] & 0xC0) === 0x80) e--;
139+
text = buf.subarray(s, e).toString('utf8');
87140
} finally {
88141
await fh.close();
89142
}
143+
144+
const nextPos = position + bytesRead;
145+
const parts: string[] = [];
146+
147+
// 前置:起点之前未读的字节
148+
if (position > 0) {
149+
parts.push(`(Above: ${position} earlier byte${position === 1 ? '' : 's'} (0-${position - 1}) not read. Use mode="byte" offset=0 limit=${position} to read them.)`);
150+
}
151+
152+
parts.push(text);
153+
154+
// 后置:终点之后未读的字节
155+
if (nextPos >= fileSize) {
156+
parts.push(`(End of file at byte ${fileSize})`);
157+
} else {
158+
const after = fileSize - nextPos;
159+
parts.push(`(Below: ${after} more byte${after === 1 ? '' : 's'} (${nextPos}-${fileSize - 1}) not read. Use mode="byte" offset=${nextPos} to continue.)`);
160+
}
161+
162+
return createSuccessResult(createTextContent(parts.join('\n\n')));
90163
}
91164

92-
/** 读取文件或目录,带行号、分页、二进制检测、"Did you mean?" 提示 */
165+
/** 读取文件,支持 line/byte 模式以及从末尾计数(endLine/endByte) */
93166
export function createReadTool(): StructuredToolInterface {
94167
return new DynamicStructuredTool({
95168
name: 'read',
96169
description: loadPrompt('tools/fs/read.txt'),
97170
schema: z.object({
98171
filePath: z.string().describe('Absolute path to the file'),
99-
offset: z.number().int().min(1).optional().describe('Line number to start reading from (1-indexed), default 1'),
100-
limit: z.number().int().positive().optional().describe(`Max lines to read, default ${DEFAULT_LIMIT}`),
101-
tail: z.number().int().positive().optional().describe('Read the last N lines (mutually exclusive with offset/limit)'),
172+
mode: z.enum(ReadMode).optional()
173+
.describe('line/byte: from start. endLine/endByte: from EOF. Default "line".'),
174+
offset: z.number().int().min(0).optional()
175+
.describe('line: 1-indexed start line. byte: 0-indexed start byte. endLine/endByte: distance from EOF where read starts (defaults to limit so "last N" works with just limit).'),
176+
limit: z.number().int().positive().optional()
177+
.describe(`Max lines (line/endLine, default ${DEFAULT_LINE_LIMIT}) or max bytes (byte/endByte, capped at ${MAX_BYTES / 1024}KB).`),
102178
}) as any,
103-
func: async ({ filePath, offset, limit, tail }: any): Promise<MCPToolResult> => {
179+
func: async ({ filePath, mode, offset, limit }: any): Promise<MCPToolResult> => {
104180
try {
105181
const abs = resolvePath(filePath);
106182

@@ -118,88 +194,33 @@ export function createReadTool(): StructuredToolInterface {
118194
}
119195

120196
const stat = fs.statSync(abs);
121-
122197
if (stat.isDirectory()) {
123198
return createErrorResult(`${abs} is a directory. Use the ls tool to list directory contents.`);
124199
}
125-
126-
// Binary check
127200
if (await isBinaryFile(abs, stat.size)) {
128201
return createErrorResult(`Cannot read binary file: ${abs}`);
129202
}
130203

131-
// Tail mode
132-
if (tail) {
133-
const { lines: tailRaw, totalLines } = await tailLines(abs, tail);
134-
const numbered: string[] = [];
135-
let bytes = 0;
136-
let truncatedByBytes = false;
137-
for (let i = 0; i < tailRaw.length; i++) {
138-
const text = tailRaw[i].length > MAX_LINE_LENGTH
139-
? tailRaw[i].substring(0, MAX_LINE_LENGTH) + MAX_LINE_SUFFIX
140-
: tailRaw[i];
141-
const size = Buffer.byteLength(text, 'utf-8') + (numbered.length > 0 ? 1 : 0);
142-
if (bytes + size > MAX_BYTES) { truncatedByBytes = true; break; }
143-
numbered.push(text);
144-
bytes += size;
145-
}
146-
let output = numbered.join('\n');
147-
if (truncatedByBytes) {
148-
const startLine = totalLines - tailRaw.length + 1;
149-
const actualEnd = startLine + numbered.length - 1;
150-
output += `\n\n(Output capped at ${MAX_BYTES_LABEL}. Showing lines ${startLine}-${actualEnd} of ${totalLines}.)`;
151-
} else {
152-
output += `\n\n(Last ${numbered.length} lines of ${totalLines})`;
153-
}
154-
return createSuccessResult(createTextContent(output));
155-
}
204+
const m: ReadMode = mode ?? ReadMode.Line;
156205

157-
// Stream with line numbers + byte cap
158-
const lim = limit ?? DEFAULT_LIMIT;
159-
const start = (offset ?? 1) - 1;
160-
const stream = createReadStream(abs, { encoding: 'utf8' });
161-
const rl = createInterface({ input: stream, crlfDelay: Infinity });
162-
163-
const raw: string[] = [];
164-
let bytes = 0;
165-
let lineCount = 0;
166-
let truncatedByBytes = false;
167-
let hasMoreLines = false;
168-
169-
try {
170-
for await (const text of rl) {
171-
lineCount++;
172-
if (lineCount <= start) continue;
173-
if (raw.length >= lim) { hasMoreLines = true; continue; }
174-
const line = text.length > MAX_LINE_LENGTH ? text.substring(0, MAX_LINE_LENGTH) + MAX_LINE_SUFFIX : text;
175-
const size = Buffer.byteLength(line, 'utf-8') + (raw.length > 0 ? 1 : 0);
176-
if (bytes + size > MAX_BYTES) { truncatedByBytes = true; hasMoreLines = true; break; }
177-
raw.push(line);
178-
bytes += size;
179-
}
180-
} finally {
181-
rl.close();
182-
stream.destroy();
206+
if (m === ReadMode.Byte || m === ReadMode.EndByte) {
207+
const want = Math.min(limit ?? DEFAULT_BYTE_LIMIT, MAX_BYTES);
208+
const position = m === ReadMode.EndByte
209+
? Math.max(0, stat.size - (offset ?? want))
210+
: (offset ?? 0);
211+
return readByBytes(abs, position, want, stat.size);
183212
}
184213

185-
if (lineCount < start && !(lineCount === 0 && start === 0)) {
186-
return createErrorResult(`Offset ${offset} is out of range for this file (${lineCount} lines)`);
187-
}
188-
189-
const off = offset ?? 1;
190-
const lastReadLine = off + raw.length - 1;
191-
const nextOffset = lastReadLine + 1;
192-
193-
let output = raw.join('\n');
194-
if (truncatedByBytes) {
195-
output += `\n\n(Output capped at ${MAX_BYTES_LABEL}. Showing lines ${off}-${lastReadLine}. Use offset=${nextOffset} to continue.)`;
196-
} else if (hasMoreLines) {
197-
output += `\n\n(Showing lines ${off}-${lastReadLine} of ${lineCount}. Use offset=${nextOffset} to continue.)`;
214+
const lim = limit ?? DEFAULT_LINE_LIMIT;
215+
let startLine: number;
216+
let totalHint: number | undefined;
217+
if (m === ReadMode.EndLine) {
218+
totalHint = await countLines(abs);
219+
startLine = Math.max(1, totalHint - (offset ?? lim) + 1);
198220
} else {
199-
output += `\n\n(End of file - total ${lineCount} lines)`;
221+
startLine = offset ?? 1;
200222
}
201-
202-
return createSuccessResult(createTextContent(output));
223+
return readByLines(abs, startLine, lim, totalHint);
203224
} catch (e: any) {
204225
logger.error(`read ${filePath}: ${e.message}`);
205226
return createErrorResult(e.message);

0 commit comments

Comments
 (0)