-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathread-handler.ts
More file actions
650 lines (592 loc) · 17.5 KB
/
read-handler.ts
File metadata and controls
650 lines (592 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
import * as fs from "fs";
import * as path from "path";
import ignore from "ignore";
import type { ToolExecutionContext, ToolExecutionFollowUpMessage, ToolExecutionResult } from "./executor";
import { readTextFileWithMetadata } from "../common/file-utils";
import { createSnippet, isAbsoluteFilePath, markFileRead, normalizeFilePath } from "../common/state";
const DEFAULT_LINE_LIMIT = 2000;
const MAX_LINE_LENGTH = 2000;
const PDF_LARGE_PAGE_THRESHOLD = 10;
const PDF_MAX_PAGE_RANGE = 20;
const LINE_NUMBER_WIDTH = 6;
const DEFAULT_GITIGNORE = [
"node_modules/",
".git/",
"dist/",
"build/",
"out/",
".next/",
".nuxt/",
".venv/",
"venv/",
"__pycache__/",
"*.pyc",
"*.pyo",
".pytest_cache/",
".mypy_cache/",
".ruff_cache/",
".gradle/",
".idea/",
".vscode/",
"*.class",
"*.jar",
"*.war",
"target/",
];
type PageRange = {
start: number;
end: number;
count: number;
};
type TextReadResult = {
content: string;
output: string;
startLine: number;
endLine: number;
totalLines: number;
isPartialView: boolean;
encoding: BufferEncoding;
lineEndings: "LF" | "CRLF";
timestamp: number;
};
export async function handleReadTool(
args: Record<string, unknown>,
context: ToolExecutionContext
): Promise<ToolExecutionResult> {
let filePath = typeof args.file_path === "string" ? normalizeFilePath(args.file_path) : "";
if (!filePath.trim()) {
return {
ok: false,
name: "read",
error: 'Missing required "file_path" string.',
};
}
if (!isAbsoluteFilePath(filePath)) {
if (filePath.startsWith("../") || filePath.startsWith("..\\")) {
return {
ok: false,
name: "read",
error: "file_path must be an absolute path.",
};
}
const normalizedSuffix = normalizeRelativeSuffix(filePath);
const isIgnored = loadGitignoreMatcher(context.projectRoot);
const matches = normalizedSuffix ? findSuffixMatches(context.projectRoot, normalizedSuffix, isIgnored) : [];
if (matches.length > 1) {
return {
ok: false,
name: "read",
error:
"file_path must be an absolute path. " +
`The file_path is ambiguous and may refer to multiple files:\n${matches.slice(0, 3).join("\n")}` +
(matches.length > 3 ? `\n...and ${matches.length - 3} more.` : ""),
};
}
const resolvedPath = path.resolve(context.projectRoot, filePath);
if (!fs.existsSync(resolvedPath)) {
if (matches.length > 0) {
return {
ok: false,
name: "read",
error: "file_path must be an absolute path. " + `The file_path "${filePath}" is ambiguous.`,
};
} else {
return {
ok: false,
name: "read",
error: `File not found: ${filePath}`,
};
}
}
filePath = resolvedPath;
}
if (!fs.existsSync(filePath)) {
return {
ok: false,
name: "read",
error: `File not found: ${filePath}`,
};
}
let stat: fs.Stats;
try {
stat = fs.statSync(filePath);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return {
ok: false,
name: "read",
error: `Failed to stat file: ${message}`,
};
}
if (stat.isDirectory()) {
return {
ok: false,
name: "read",
error: "file_path points to a directory. Use bash ls for directories.",
};
}
const ext = path.extname(filePath).toLowerCase();
try {
if (ext === ".ipynb") {
const output = readNotebook(filePath);
markFileRead(context.sessionId, filePath, {
content: "",
timestamp: Math.floor(stat.mtimeMs),
isPartialView: true,
});
return {
ok: true,
name: "read",
output,
};
}
if (ext === ".pdf") {
const pagesParam = typeof args.pages === "string" ? args.pages.trim() : "";
const buffer = fs.readFileSync(filePath);
const pageCount = countPdfPages(buffer);
const pageRange = pagesParam ? parsePageRange(pagesParam) : null;
if (!pageRange && pageCount !== null && pageCount > PDF_LARGE_PAGE_THRESHOLD) {
return {
ok: false,
name: "read",
error: `PDF has ${pageCount} pages; provide "pages" to read a range.`,
};
}
if (pageRange && pageRange.count > PDF_MAX_PAGE_RANGE) {
return {
ok: false,
name: "read",
error: `PDF page range exceeds ${PDF_MAX_PAGE_RANGE} pages.`,
};
}
if (pageRange && pageCount !== null && pageRange.end > pageCount) {
return {
ok: false,
name: "read",
error: `PDF page range exceeds total page count (${pageCount}).`,
};
}
const base64 = buffer.toString("base64");
markFileRead(context.sessionId, filePath, {
content: "",
timestamp: Math.floor(stat.mtimeMs),
isPartialView: true,
});
return {
ok: true,
name: "read",
output: `data:application/pdf;base64,${base64}`,
metadata: {
mime: "application/pdf",
encoding: "base64",
bytes: buffer.length,
pageCount,
pages: pageRange ? `${pageRange.start}-${pageRange.end}` : null,
},
};
}
if (isImageExtension(ext)) {
const buffer = fs.readFileSync(filePath);
const mime = getImageMimeType(ext);
markFileRead(context.sessionId, filePath, {
content: "",
timestamp: Math.floor(stat.mtimeMs),
isPartialView: true,
});
return {
ok: true,
name: "read",
output: "File loaded.",
metadata: {
mime,
bytes: buffer.length,
},
followUpMessages: [buildImageFollowUpMessage(filePath, mime, buffer)],
};
}
const offset = parseLineNumber(args.offset, "offset");
const limit = parseLineLimit(args.limit);
if (!offset.ok) {
return {
ok: false,
name: "read",
error: offset.error,
};
}
if (!limit.ok) {
return {
ok: false,
name: "read",
error: limit.error,
};
}
const textResult = readTextFile(filePath, offset.value, limit.value);
markFileRead(context.sessionId, filePath, {
content: textResult.content,
timestamp: textResult.timestamp,
offset: textResult.isPartialView ? textResult.startLine : undefined,
limit: textResult.isPartialView ? Math.max(1, textResult.endLine - textResult.startLine + 1) : undefined,
isPartialView: textResult.isPartialView,
encoding: textResult.encoding,
lineEndings: textResult.lineEndings,
});
const snippet = createSnippet(
context.sessionId,
filePath,
textResult.startLine,
textResult.endLine,
textResult.output
);
return {
ok: true,
name: "read",
output: textResult.output,
metadata: snippet
? {
snippet: {
id: snippet.id,
filePath: snippet.filePath,
startLine: snippet.startLine,
endLine: snippet.endLine,
},
}
: undefined,
};
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return {
ok: false,
name: "read",
error: message,
};
}
}
function normalizeRelativeSuffix(relativePath: string): string | null {
const normalized = path.normalize(relativePath).replace(/^(\.\/|\\)+/, "");
return normalized.trim() ? path.sep + normalized : null;
}
function findSuffixMatches(
root: string,
suffix: string,
isIgnored: ((relPath: string, isDir: boolean) => boolean) | null
): string[] {
const matches: string[] = [];
const queue: string[] = [root];
while (queue.length > 0) {
const current = queue.pop();
if (!current) {
continue;
}
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(current, { withFileTypes: true });
} catch {
continue;
}
for (const entry of entries) {
const fullPath = path.join(current, entry.name);
const relPath = path.relative(root, fullPath).replace(/\\/g, "/");
if (isIgnored && isIgnored(relPath, entry.isDirectory())) {
continue;
}
if (entry.isDirectory()) {
queue.push(fullPath);
continue;
}
if (entry.isFile() && fullPath.endsWith(suffix)) {
matches.push(fullPath);
}
}
}
return matches;
}
function loadGitignoreMatcher(projectRoot: string): ((relPath: string, isDir: boolean) => boolean) | null {
const gitignorePath = path.join(projectRoot, ".gitignore");
if (!fs.existsSync(gitignorePath)) {
const ig = ignore();
ig.add(DEFAULT_GITIGNORE);
return (relPath: string, isDir: boolean) => {
if (!relPath) {
return false;
}
const candidate = isDir ? `${relPath}/` : relPath;
return ig.ignores(candidate);
};
}
let content = "";
try {
content = fs.readFileSync(gitignorePath, "utf8");
} catch {
const ig = ignore();
ig.add(DEFAULT_GITIGNORE);
return (relPath: string, isDir: boolean) => {
if (!relPath) {
return false;
}
const candidate = isDir ? `${relPath}/` : relPath;
return ig.ignores(candidate);
};
}
const ig = ignore();
ig.add(DEFAULT_GITIGNORE);
ig.add(content);
return (relPath: string, isDir: boolean) => {
if (!relPath) {
return false;
}
const candidate = isDir ? `${relPath}/` : relPath;
return ig.ignores(candidate);
};
}
function parseLineNumber(
value: unknown,
label: string
): { ok: true; value: number | null } | { ok: false; error: string } {
if (value === undefined || value === null) {
return { ok: true, value: null };
}
const numeric = typeof value === "number" ? value : Number(value);
if (!Number.isFinite(numeric)) {
return { ok: false, error: `${label} must be a number.` };
}
const integer = Math.trunc(numeric);
if (integer < 1) {
return { ok: false, error: `${label} must be >= 1.` };
}
return { ok: true, value: integer };
}
function parseLineLimit(value: unknown): { ok: true; value: number } | { ok: false; error: string } {
if (value === undefined || value === null) {
return { ok: true, value: DEFAULT_LINE_LIMIT };
}
const numeric = typeof value === "number" ? value : Number(value);
if (!Number.isFinite(numeric)) {
return { ok: false, error: "limit must be a number." };
}
const integer = Math.trunc(numeric);
if (integer <= 0) {
return { ok: false, error: "limit must be > 0." };
}
return { ok: true, value: integer };
}
function readTextFile(filePath: string, offset: number | null, limit: number): TextReadResult {
const metadata = readTextFileWithMetadata(filePath);
const raw = metadata.content;
if (!raw) {
return {
content: "",
output: "WARNING: File is empty.",
startLine: offset ?? 1,
endLine: offset ?? 1,
totalLines: 0,
isPartialView: false,
encoding: metadata.encoding,
lineEndings: metadata.lineEndings,
timestamp: metadata.timestamp,
};
}
const lines = raw.split("\n");
if (lines.length === 1 && lines[0] === "") {
return {
content: "",
output: "WARNING: File is empty.",
startLine: offset ?? 1,
endLine: offset ?? 1,
totalLines: 0,
isPartialView: false,
encoding: metadata.encoding,
lineEndings: metadata.lineEndings,
timestamp: metadata.timestamp,
};
}
const startIndex = offset ? offset - 1 : 0;
const endIndex = startIndex + limit;
const selected = lines.slice(startIndex, endIndex);
const startLine = startIndex + 1;
const endLine = selected.length > 0 ? startIndex + selected.length : startLine;
const isPartialView = startLine !== 1 || endLine < lines.length;
return {
content: selected.join("\n"),
output: formatWithLineNumbers(selected, startLine),
startLine,
endLine,
totalLines: lines.length,
isPartialView,
encoding: metadata.encoding,
lineEndings: metadata.lineEndings,
timestamp: metadata.timestamp,
};
}
function formatWithLineNumbers(lines: string[], startLineNumber: number): string {
return lines
.map((line, index) => {
const lineNumber = startLineNumber + index;
const trimmedLine = line.length > MAX_LINE_LENGTH ? line.slice(0, MAX_LINE_LENGTH) : line;
return `${String(lineNumber).padStart(LINE_NUMBER_WIDTH, " ")}\t${trimmedLine}`;
})
.join("\n");
}
function isImageExtension(ext: string): boolean {
return [".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tif", ".tiff", ".svg", ".ico", ".avif"].includes(ext);
}
function getImageMimeType(ext: string): string {
switch (ext) {
case ".jpg":
case ".jpeg":
return "image/jpeg";
case ".gif":
return "image/gif";
case ".webp":
return "image/webp";
case ".bmp":
return "image/bmp";
case ".tif":
case ".tiff":
return "image/tiff";
case ".svg":
return "image/svg+xml";
case ".ico":
return "image/x-icon";
case ".avif":
return "image/avif";
case ".png":
default:
return "image/png";
}
}
function buildImageFollowUpMessage(filePath: string, mime: string, buffer: Buffer): ToolExecutionFollowUpMessage {
const fileName = path.basename(filePath);
return {
role: "system",
content:
`The read tool has loaded \`${fileName}\`. ` + "Use the attached image content to answer the original request.",
contentParams: [
{
type: "image_url",
image_url: {
url: `data:${mime};base64,${buffer.toString("base64")}`,
},
},
],
};
}
function countPdfPages(buffer: Buffer): number | null {
try {
const content = buffer.toString("latin1");
const matches = content.match(/\/Type\s*\/Page\b(?!s)/g);
return matches ? matches.length : 0;
} catch {
return null;
}
}
function parsePageRange(input: string): PageRange {
const trimmed = input.trim();
if (!trimmed) {
throw new Error("pages must be a non-empty string.");
}
if (trimmed.includes(",")) {
throw new Error('pages must be a single range like "1-5" or "3".');
}
const parts = trimmed.split("-").map((part) => part.trim());
if (parts.length === 1) {
const value = parsePositiveInt(parts[0], "pages");
return { start: value, end: value, count: 1 };
}
if (parts.length === 2) {
const start = parsePositiveInt(parts[0], "pages");
const end = parsePositiveInt(parts[1], "pages");
if (end < start) {
throw new Error("pages range end must be >= start.");
}
return { start, end, count: end - start + 1 };
}
throw new Error('pages must be a single range like "1-5" or "3".');
}
function parsePositiveInt(value: string, label: string): number {
const numeric = Number(value);
if (!Number.isFinite(numeric)) {
throw new Error(`${label} must be a number.`);
}
const integer = Math.trunc(numeric);
if (integer < 1) {
throw new Error(`${label} must be >= 1.`);
}
return integer;
}
function readNotebook(filePath: string): string {
const raw = fs.readFileSync(filePath, "utf8");
if (!raw) {
return "WARNING: File is empty.";
}
const parsed = JSON.parse(raw) as {
cells?: Array<{
cell_type?: string;
source?: string[] | string;
outputs?: Array<Record<string, unknown>>;
}>;
};
const lines: string[] = [];
const cells = Array.isArray(parsed.cells) ? parsed.cells : [];
cells.forEach((cell, index) => {
const cellType = cell.cell_type ?? "unknown";
lines.push(`# Cell ${index + 1} (${cellType})`);
const source = normalizeNotebookField(cell.source);
if (source.length > 0) {
lines.push(...source);
}
const outputs = Array.isArray(cell.outputs) ? cell.outputs : [];
outputs.forEach((output, outputIndex) => {
const outputType = typeof output.output_type === "string" ? output.output_type : "output";
lines.push(`# Output ${outputIndex + 1} (${outputType})`);
lines.push(...formatNotebookOutput(output));
});
});
if (lines.length === 0) {
return "WARNING: Notebook has no cells.";
}
return formatWithLineNumbers(lines, 1);
}
function normalizeNotebookField(value: unknown): string[] {
if (Array.isArray(value)) {
return value.map((item) => String(item).replace(/\r?\n$/, ""));
}
if (typeof value === "string") {
return value.split(/\r?\n/);
}
return [];
}
function formatNotebookOutput(output: Record<string, unknown>): string[] {
const lines: string[] = [];
const text = output.text;
if (Array.isArray(text)) {
lines.push(...text.map((item) => String(item).replace(/\r?\n$/, "")));
} else if (typeof text === "string") {
lines.push(...text.split(/\r?\n/));
}
const data = output.data;
if (data && typeof data === "object") {
const record = data as Record<string, unknown>;
const textPlain = record["text/plain"];
if (Array.isArray(textPlain)) {
lines.push(...textPlain.map((item) => String(item).replace(/\r?\n$/, "")));
} else if (typeof textPlain === "string") {
lines.push(...textPlain.split(/\r?\n/));
}
const imagePng = record["image/png"];
if (typeof imagePng === "string") {
lines.push(`[image/png ${imagePng.length} chars]`);
}
const imageJpeg = record["image/jpeg"];
if (typeof imageJpeg === "string") {
lines.push(`[image/jpeg ${imageJpeg.length} chars]`);
}
}
const trace = output.traceback;
if (Array.isArray(trace)) {
lines.push(...trace.map((item) => String(item).replace(/\r?\n$/, "")));
}
if (lines.length === 0) {
lines.push("[output omitted]");
}
return lines;
}