-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathfile_read_tool.cpp
More file actions
1076 lines (985 loc) · 38.7 KB
/
Copy pathfile_read_tool.cpp
File metadata and controls
1076 lines (985 loc) · 38.7 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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "file_read_tool.hpp"
#include "mtime_tracker.hpp"
#include "tool_icons.hpp"
#include "utils/encoding.hpp"
#include "utils/file_operations.hpp"
#include "utils/logger.hpp"
#include "utils/text_file_buffer.hpp"
#include "utils/tool_errors.hpp"
#include "utils/utf8_path.hpp"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cstdint>
#include <filesystem>
#include <fstream>
#include <limits>
#include <optional>
#include <sstream>
#include <string>
#include <vector>
namespace acecode {
namespace {
constexpr size_t kFileReadContentLimit = 48 * 1024;
constexpr size_t kFileReadByteWindowLimit = 32 * 1024;
constexpr size_t kFileReadIoChunkSize = 1024 * 1024;
constexpr uintmax_t kLegacyReadMaterializationLimit =
static_cast<uintmax_t>(512) * 1024 * 1024;
constexpr size_t kLargeFileHintThreshold = 200 * 1024;
constexpr const char* kFileUnchangedStub =
"File unchanged since last read.";
struct ReadRequest {
std::string file_path;
int start_line = 0;
int end_line = 0;
bool has_line_range = false;
bool byte_mode = false;
uint64_t byte_offset = 0;
size_t requested_max_bytes = 0;
size_t effective_max_bytes = kFileReadByteWindowLimit;
};
struct LineReadResult {
bool success = true;
bool needs_materialized_fallback = false;
std::string error;
std::string content;
int actual_start = 0;
int actual_end = 0;
int total_lines = 0;
int displayed_line_count = 0;
bool automatic_truncation = false;
std::optional<int> next_line;
std::optional<uint64_t> next_byte_offset;
};
struct ReadPresentation {
bool partial = false;
bool automatic_truncation = false;
bool byte_mode = false;
uint64_t byte_start = 0;
uint64_t byte_end = 0; // exclusive
std::optional<int> next_line;
std::optional<uint64_t> next_byte_offset;
};
bool json_nonnegative_u64(const nlohmann::json& value, uint64_t& out) {
if (value.is_number_unsigned()) {
out = value.get<uint64_t>();
return true;
}
if (!value.is_number_integer()) return false;
const auto signed_value = value.get<int64_t>();
if (signed_value < 0) return false;
out = static_cast<uint64_t>(signed_value);
return true;
}
bool json_line_number(const nlohmann::json& value, int& out) {
if (!value.is_number_integer()) return false;
const auto number = value.get<int64_t>();
if (number < 0 || number > std::numeric_limits<int>::max()) return false;
out = static_cast<int>(number);
return true;
}
std::optional<ReadRequest> parse_read_request(
const std::string& arguments_json,
std::string& error
) {
const auto args = nlohmann::json::parse(arguments_json, nullptr, false);
if (!args.is_object()) {
error = ToolErrors::parse_failed();
return std::nullopt;
}
if (!args.contains("file_path")) {
error = ToolErrors::missing_parameter("file_path");
return std::nullopt;
}
if (!args["file_path"].is_string()) {
error = ToolErrors::invalid_parameter(
"file_path", "must be a string");
return std::nullopt;
}
ReadRequest request;
request.file_path = args["file_path"].get<std::string>();
if (request.file_path.empty()) {
error = ToolErrors::missing_parameter("file_path");
return std::nullopt;
}
const bool has_start = args.contains("start_line");
const bool has_end = args.contains("end_line");
const bool has_byte_offset = args.contains("byte_offset");
const bool has_max_bytes = args.contains("max_bytes");
if (has_start && !json_line_number(args["start_line"], request.start_line)) {
error = ToolErrors::invalid_parameter(
"start_line", "must be a non-negative integer");
return std::nullopt;
}
if (has_end && !json_line_number(args["end_line"], request.end_line)) {
error = ToolErrors::invalid_parameter(
"end_line", "must be a non-negative integer");
return std::nullopt;
}
// Some models use start/count semantics even though the public field is
// named end_line. A positive reversed pair cannot describe a valid
// inclusive absolute range, so accept that otherwise-invalid shape as the
// common compatibility form: start_line plus a line count.
if (request.start_line > 0 &&
request.end_line > 0 &&
request.end_line < request.start_line) {
const int64_t normalized_end =
static_cast<int64_t>(request.start_line) +
static_cast<int64_t>(request.end_line) - 1;
if (normalized_end > std::numeric_limits<int>::max()) {
error = ToolErrors::invalid_parameter(
"end_line",
"line count produces an end line beyond the supported range");
return std::nullopt;
}
request.end_line = static_cast<int>(normalized_end);
}
if (has_byte_offset &&
!json_nonnegative_u64(args["byte_offset"], request.byte_offset)) {
error = ToolErrors::invalid_parameter(
"byte_offset", "must be a non-negative integer");
return std::nullopt;
}
// Providers that enforce OpenAI structured-output schemas promote every
// declared property into `required`, so a caller cannot omit an optional
// parameter and sends the zero value instead. Treat max_bytes=0 as unset
// rather than out of range.
uint64_t max_bytes = 0;
if (has_max_bytes &&
(!json_nonnegative_u64(args["max_bytes"], max_bytes) ||
max_bytes > kFileReadByteWindowLimit)) {
error = ToolErrors::invalid_parameter(
"max_bytes",
"must be between 1 and " +
std::to_string(kFileReadByteWindowLimit));
return std::nullopt;
}
if (max_bytes > 0) {
if (!has_byte_offset) {
error = ToolErrors::invalid_parameter(
"max_bytes", "requires byte_offset");
return std::nullopt;
}
request.requested_max_bytes = static_cast<size_t>(max_bytes);
request.effective_max_bytes = request.requested_max_bytes;
}
// A line range is only requested when the numbers are meaningful: these are
// 1-indexed, so 0 means "unset" here exactly as it does downstream.
request.has_line_range = request.start_line > 0 || request.end_line > 0;
// A bare byte_offset is the legacy way to opt into byte mode and stays
// meaningful at 0. Once the caller also sends the other properties they are
// schema-filled defaults, so an all-zero combination means "no window
// requested" — reading from byte 0 there would reject empty files outright
// and cut long files down to a single 32 KiB window.
const bool explicit_window = request.byte_offset > 0 || max_bytes > 0;
const bool byte_offset_only =
has_byte_offset && !has_max_bytes && !has_start && !has_end;
request.byte_mode = explicit_window || byte_offset_only;
// Both modes can arrive together only because the caller was forced to send
// the byte parameters it never asked for. Rejecting the combination made
// file_read permanently unusable behind such a provider — every call failed
// and models retried the same read indefinitely. Prefer the explicit line
// range and drop the byte window instead.
if (request.has_line_range && request.byte_mode) {
request.byte_mode = false;
request.byte_offset = 0;
request.requested_max_bytes = 0;
request.effective_max_bytes = kFileReadByteWindowLimit;
}
return request;
}
std::string utf8_prefix_without_marker(const std::string& value, size_t max_bytes) {
if (value.size() <= max_bytes) return value;
return truncate_utf8_prefix(value, max_bytes, "");
}
std::string format_read_metadata_footer(
const FileReadEditMetadata& metadata,
const ReadPresentation& presentation
) {
std::ostringstream oss;
oss << "\n<acecode-read-metadata"
<< " encoding=\"" << metadata.encoding << "\""
<< " line_endings=\"" << metadata.line_ending << "\""
<< " partial=\"" << (presentation.partial ? "true" : "false") << "\"";
if (metadata.start_line > 0 && metadata.end_line > 0) {
oss << " range=\"" << metadata.start_line << "-" << metadata.end_line << "\"";
}
if (presentation.automatic_truncation) {
oss << " truncated=\"true\"";
}
if (presentation.byte_mode) {
oss << " byte_range=\"" << presentation.byte_start
<< "-" << presentation.byte_end << "\"";
}
if (presentation.next_line.has_value()) {
oss << " next_line=\"" << *presentation.next_line << "\"";
}
if (presentation.next_byte_offset.has_value()) {
oss << " next_byte_offset=\"" << *presentation.next_byte_offset << "\"";
}
if (metadata.lossy) {
oss << " lossy=\"true\""
<< " replacements=\"" << metadata.lossy_replacement_count << "\""
<< " editable=\"false\"";
}
oss << " />\n";
return oss.str();
}
std::string format_file_unchanged_stub(
const MtimeTracker::ReadObservation& observation
) {
std::ostringstream oss;
oss << kFileUnchangedStub
<< " The previous file_read result for this same file/window is still current.";
if (!observation.tool_call_id.empty()) {
oss << "\nPrevious file_read tool_call_id: " << observation.tool_call_id;
}
if (!observation.persisted_output_path.empty()) {
oss << "\nFull previous output path: " << observation.persisted_output_path
<< "\nIf full content is needed, call file_read on that saved output path.";
}
oss << "\nDo not call file_read on the original file/window again unless the "
"file changed or a different window is needed.";
return oss.str();
}
uint64_t source_line_start_offset(
const TextFileBuffer& buffer,
int target_line
) {
if (target_line <= 1) {
return buffer.metadata.has_bom
? (buffer.metadata.encoding == TextEncoding::Utf8Bom ? 3 : 2)
: 0;
}
const std::string& raw = buffer.raw_bytes;
size_t pos = buffer.metadata.has_bom
? (buffer.metadata.encoding == TextEncoding::Utf8Bom ? 3 : 2)
: 0;
int line = 1;
if (buffer.metadata.encoding == TextEncoding::Utf16Le ||
buffer.metadata.encoding == TextEncoding::Utf16Be) {
const bool little_endian = buffer.metadata.encoding == TextEncoding::Utf16Le;
auto code_unit_at = [&](size_t at) -> uint16_t {
const auto a = static_cast<unsigned char>(raw[at]);
const auto b = static_cast<unsigned char>(raw[at + 1]);
return little_endian
? static_cast<uint16_t>(a | (static_cast<uint16_t>(b) << 8))
: static_cast<uint16_t>(b | (static_cast<uint16_t>(a) << 8));
};
while (pos + 1 < raw.size() && line < target_line) {
const uint16_t current = code_unit_at(pos);
pos += 2;
if (current == '\r') {
if (pos + 1 < raw.size() && code_unit_at(pos) == '\n') pos += 2;
++line;
} else if (current == '\n') {
++line;
}
}
return static_cast<uint64_t>(pos);
}
while (pos < raw.size() && line < target_line) {
const unsigned char current = static_cast<unsigned char>(raw[pos++]);
if (current == '\r') {
if (pos < raw.size() && raw[pos] == '\n') ++pos;
++line;
} else if (current == '\n') {
++line;
}
}
return static_cast<uint64_t>(pos);
}
bool append_presented_line(
LineReadResult& result,
int line_number,
const std::string& line,
bool include_newline,
bool numbered,
uint64_t source_start,
bool displayed_bytes_map_to_source
) {
const std::string prefix = numbered
? std::to_string(line_number) + ": "
: std::string{};
if (result.content.size() + prefix.size() > kFileReadContentLimit) {
result.automatic_truncation = true;
result.next_line = line_number;
return false;
}
result.content += prefix;
const size_t remaining = kFileReadContentLimit - result.content.size();
if (line.size() > remaining) {
const std::string visible = utf8_prefix_without_marker(line, remaining);
result.content += visible;
result.automatic_truncation = true;
result.next_byte_offset = displayed_bytes_map_to_source
? source_start + static_cast<uint64_t>(visible.size())
: source_start;
result.actual_end = line_number;
++result.displayed_line_count;
return false;
}
result.content += line;
if (include_newline) {
if (result.content.size() == kFileReadContentLimit) {
result.automatic_truncation = true;
result.next_byte_offset =
source_start + static_cast<uint64_t>(line.size());
result.actual_end = line_number;
++result.displayed_line_count;
return false;
}
result.content.push_back('\n');
}
result.actual_end = line_number;
++result.displayed_line_count;
return true;
}
LineReadResult present_materialized_lines(
const TextFileBuffer& buffer,
const ReadRequest& request
) {
LineReadResult result;
const std::vector<std::string> lines =
split_lf_lines_preserve_empty(buffer.text);
result.total_lines = static_cast<int>(lines.size());
const int start = request.start_line > 0 ? request.start_line : 1;
const int requested_end = request.end_line > 0
? request.end_line
: std::numeric_limits<int>::max();
const int end = std::min(requested_end, result.total_lines);
if (result.total_lines == 0 && !request.has_line_range) {
return result;
}
if (result.total_lines == 0 || start > end || start > result.total_lines) {
result.success = false;
result.error = ToolErrors::no_lines_in_range(
start,
request.end_line > 0 ? request.end_line : result.total_lines,
result.total_lines);
return result;
}
result.actual_start = start;
const bool exact_source_mapping =
buffer.metadata.encoding == TextEncoding::Utf8 ||
buffer.metadata.encoding == TextEncoding::Utf8Bom;
for (int line_number = start; line_number <= end; ++line_number) {
const size_t index = static_cast<size_t>(line_number - 1);
const bool original_has_newline =
index + 1 < lines.size() ||
(!buffer.text.empty() && buffer.text.back() == '\n');
const bool include_newline =
request.has_line_range || original_has_newline;
const uint64_t source_start =
source_line_start_offset(buffer, line_number);
if (!append_presented_line(
result,
line_number,
lines[index],
include_newline,
request.has_line_range,
source_start,
exact_source_mapping)) {
if (!result.next_byte_offset.has_value()) {
result.next_line = line_number;
}
break;
}
}
if (result.automatic_truncation &&
!result.next_line.has_value() &&
!result.next_byte_offset.has_value()) {
result.next_line = result.actual_end + 1;
}
return result;
}
LineReadResult stream_utf8_lines(
const std::string& path,
bool has_utf8_bom,
const ReadRequest& request
) {
LineReadResult result;
std::ifstream ifs(path_from_utf8(path), std::ios::binary);
if (!ifs.is_open()) {
result.success = false;
result.error = ToolErrors::cannot_open_file(path);
return result;
}
uint64_t source_offset = has_utf8_bom ? 3 : 0;
if (has_utf8_bom) ifs.seekg(3, std::ios::beg);
const int start = request.start_line > 0 ? request.start_line : 1;
const int end = request.end_line > 0
? request.end_line
: std::numeric_limits<int>::max();
int line_number = 1;
int completed_lines = 0;
bool line_has_bytes = false;
bool line_is_presented = false;
bool stopped = false;
bool pending_cr = false;
uint64_t pending_cr_offset = 0;
std::string pending_utf8;
size_t expected_utf8_bytes = 0;
uint64_t pending_utf8_offset = 0;
auto line_is_selected = [&]() {
return line_number >= start && line_number <= end;
};
auto begin_presented_line = [&]() -> bool {
if (!line_is_selected() || line_is_presented) return true;
const std::string prefix = request.has_line_range
? std::to_string(line_number) + ": "
: std::string{};
if (result.content.size() + prefix.size() > kFileReadContentLimit) {
result.automatic_truncation = true;
result.next_line = line_number;
return false;
}
if (result.actual_start == 0) result.actual_start = line_number;
result.content += prefix;
line_is_presented = true;
return true;
};
auto mark_truncated_inside_line = [&](uint64_t byte_offset) {
result.automatic_truncation = true;
result.next_byte_offset = byte_offset;
result.actual_end = line_number;
if (line_is_presented) ++result.displayed_line_count;
};
auto append_source_token = [&](const std::string& token,
uint64_t token_offset) -> bool {
line_has_bytes = true;
if (!line_is_selected()) return true;
if (!begin_presented_line()) return false;
if (result.content.size() + token.size() > kFileReadContentLimit) {
mark_truncated_inside_line(token_offset);
return false;
}
result.content += token;
return true;
};
auto finish_line = [&](bool has_source_newline,
uint64_t terminator_offset) -> bool {
if (line_is_selected()) {
if (!begin_presented_line()) return false;
if (has_source_newline) {
if (result.content.size() == kFileReadContentLimit) {
mark_truncated_inside_line(terminator_offset);
return false;
}
result.content.push_back('\n');
} else if (request.has_line_range &&
result.content.size() < kFileReadContentLimit) {
// Preserve the established numbered-range presentation. This
// newline is formatting, not unread source content.
result.content.push_back('\n');
}
result.actual_end = line_number;
++result.displayed_line_count;
}
++completed_lines;
if (line_number >= end) return false;
if (line_number == std::numeric_limits<int>::max()) {
result.success = false;
result.error = ToolErrors::too_many_lines_for_line_read();
return false;
}
++line_number;
line_has_bytes = false;
line_is_presented = false;
return true;
};
auto fail_to_materialized_fallback = [&]() {
result.needs_materialized_fallback = true;
stopped = true;
};
std::vector<char> block(kFileReadIoChunkSize);
while (!stopped && ifs.good()) {
ifs.read(block.data(), static_cast<std::streamsize>(block.size()));
const size_t bytes_read = static_cast<size_t>(ifs.gcount());
if (bytes_read == 0) break;
for (size_t i = 0; i < bytes_read; ++i) {
const uint64_t byte_offset = source_offset + i;
const unsigned char byte =
static_cast<unsigned char>(block[i]);
if (pending_cr) {
if (byte != '\n') {
// CR-only and mixed endings need normalization by the
// existing full decoder.
fail_to_materialized_fallback();
break;
}
pending_cr = false;
if (!finish_line(true, pending_cr_offset)) {
stopped = true;
break;
}
continue;
}
if (pending_utf8.empty()) {
if (byte == '\0') {
fail_to_materialized_fallback();
break;
}
if (byte == '\r') {
pending_cr = true;
pending_cr_offset = byte_offset;
continue;
}
if (byte == '\n') {
if (!finish_line(true, byte_offset)) {
stopped = true;
break;
}
continue;
}
if (byte <= 0x7F) {
const std::string token(1, static_cast<char>(byte));
if (!append_source_token(token, byte_offset)) {
stopped = true;
break;
}
continue;
}
if ((byte & 0xE0) == 0xC0) expected_utf8_bytes = 2;
else if ((byte & 0xF0) == 0xE0) expected_utf8_bytes = 3;
else if ((byte & 0xF8) == 0xF0) expected_utf8_bytes = 4;
else {
fail_to_materialized_fallback();
break;
}
pending_utf8.assign(1, static_cast<char>(byte));
pending_utf8_offset = byte_offset;
continue;
}
if ((byte & 0xC0) != 0x80) {
fail_to_materialized_fallback();
break;
}
pending_utf8.push_back(static_cast<char>(byte));
if (pending_utf8.size() == expected_utf8_bytes) {
if (!text_bytes_are_valid_utf8(pending_utf8)) {
fail_to_materialized_fallback();
break;
}
if (!append_source_token(
pending_utf8,
pending_utf8_offset)) {
stopped = true;
break;
}
pending_utf8.clear();
expected_utf8_bytes = 0;
}
}
source_offset += bytes_read;
}
if (result.needs_materialized_fallback || !result.success) return result;
if (!stopped) {
if (pending_cr || !pending_utf8.empty()) {
result.needs_materialized_fallback = true;
return result;
}
if (line_has_bytes) {
finish_line(false, source_offset);
}
}
result.total_lines = completed_lines;
if (result.actual_start == 0) {
result.success = false;
result.error = ToolErrors::no_lines_in_range(
start,
request.end_line > 0 ? request.end_line : completed_lines,
completed_lines);
return result;
}
if (result.automatic_truncation &&
!result.next_line.has_value() &&
!result.next_byte_offset.has_value()) {
result.next_line = result.actual_end + 1;
}
return result;
}
TextBufferResult read_file_probe(
const std::string& path,
uintmax_t file_size
) {
const size_t probe_size = static_cast<size_t>(
std::min<uintmax_t>(file_size, kFileReadIoChunkSize));
std::ifstream ifs(path_from_utf8(path), std::ios::binary);
if (!ifs.is_open()) {
return TextBufferResult{
false,
{},
ToolErrors::cannot_open_file(path)
};
}
std::string probe(probe_size, '\0');
ifs.read(probe.data(), static_cast<std::streamsize>(probe.size()));
probe.resize(static_cast<size_t>(ifs.gcount()));
if (static_cast<uintmax_t>(probe.size()) < file_size) {
trim_trailing_partial_utf8(probe);
}
return decode_text_file_bytes(probe, path, true);
}
std::string large_legacy_materialization_error(
uintmax_t file_size,
const TextFileMetadata& metadata
) {
return ToolErrors::large_text_requires_streaming_encoding(
text_encoding_label(metadata.encoding),
static_cast<size_t>(file_size / (1024 * 1024)),
static_cast<size_t>(
kLegacyReadMaterializationLimit / (1024 * 1024)));
}
ToolResult execute_file_read(
const std::string& arguments_json,
const ToolContext& ctx
) {
std::string parse_error;
auto parsed_request = parse_read_request(arguments_json, parse_error);
if (!parsed_request.has_value()) {
return ToolResult{parse_error, false};
}
ReadRequest request = *parsed_request;
const auto resolved_path = ctx.resolve_scratch_path_alias(request.file_path);
if (!resolved_path.success) {
return ToolResult{resolved_path.error, false};
}
request.file_path = resolved_path.path;
LOG_DEBUG(
"file_read: path=" + request.file_path +
" start=" + std::to_string(request.start_line) +
" end=" + std::to_string(request.end_line) +
" byte_offset=" + std::to_string(request.byte_offset));
auto exists_check = FileOperations::check_file_exists(request.file_path);
if (!exists_check.success) return exists_check;
std::error_code file_ec;
const auto fs_path = path_from_utf8(request.file_path);
if (!std::filesystem::is_regular_file(fs_path, file_ec) || file_ec) {
return ToolResult{
ToolErrors::path_not_regular_file(request.file_path),
false
};
}
const uintmax_t file_size = std::filesystem::file_size(fs_path, file_ec);
if (file_ec) {
return ToolResult{ToolErrors::cannot_open_file(request.file_path), false};
}
auto unchanged_observation =
MtimeTracker::instance().unchanged_read_observation(
request.file_path,
request.start_line,
request.end_line,
request.byte_mode,
request.byte_offset,
request.requested_max_bytes);
if (unchanged_observation.has_value()) {
ToolSummary summary;
summary.verb = "Read";
summary.object = request.file_path;
summary.metrics.emplace_back("cache", "unchanged");
summary.icon = tool_icon("file_read");
ToolResult cached{
format_file_unchanged_stub(*unchanged_observation),
true
};
cached.summary = std::move(summary);
return cached;
}
TextBufferResult probe_result =
file_size <= FileOperations::MAX_EDIT_FILE_SIZE
? read_text_file_buffer(request.file_path, true)
: read_file_probe(request.file_path, file_size);
if (!probe_result.success) {
return ToolResult{probe_result.error, false};
}
FileReadEditMetadata metadata;
metadata.encoding =
text_encoding_label(probe_result.buffer.metadata.encoding);
metadata.line_ending =
line_ending_label(probe_result.buffer.metadata.line_ending);
if (probe_result.buffer.metadata.lossy) {
metadata.encoding += " (lossy)";
metadata.lossy = true;
metadata.lossy_replacement_count =
probe_result.buffer.metadata.lossy_replacement_count;
}
std::string content;
int displayed_line_count = 0;
ReadPresentation presentation;
if (request.byte_mode) {
if (request.byte_offset >= file_size) {
return ToolResult{
ToolErrors::byte_offset_outside_file(
static_cast<size_t>(request.byte_offset),
static_cast<size_t>(file_size)),
false
};
}
std::ifstream ifs(fs_path, std::ios::binary);
if (!ifs.is_open()) {
return ToolResult{
ToolErrors::cannot_open_file(request.file_path),
false
};
}
std::vector<char> io_buffer(kFileReadIoChunkSize);
ifs.rdbuf()->pubsetbuf(
io_buffer.data(),
static_cast<std::streamsize>(io_buffer.size()));
ifs.seekg(static_cast<std::streamoff>(request.byte_offset),
std::ios::beg);
const uint64_t remaining =
static_cast<uint64_t>(file_size) - request.byte_offset;
const size_t to_read = static_cast<size_t>(
std::min<uint64_t>(remaining, request.effective_max_bytes));
std::string raw(to_read, '\0');
ifs.read(raw.data(), static_cast<std::streamsize>(raw.size()));
raw.resize(static_cast<size_t>(ifs.gcount()));
const size_t source_bytes_read = raw.size();
size_t trailing_partial_bytes = 0;
if (request.byte_offset == 0 &&
raw.size() >= 3 &&
static_cast<unsigned char>(raw[0]) == 0xEF &&
static_cast<unsigned char>(raw[1]) == 0xBB &&
static_cast<unsigned char>(raw[2]) == 0xBF) {
raw.erase(0, 3);
}
const bool clean_utf8_window =
!probe_result.buffer.metadata.lossy &&
(probe_result.buffer.metadata.encoding == TextEncoding::Utf8 ||
probe_result.buffer.metadata.encoding == TextEncoding::Utf8Bom);
const bool has_more_source =
request.byte_offset + source_bytes_read < file_size;
if (clean_utf8_window && has_more_source) {
const size_t before_trim = raw.size();
trim_trailing_partial_utf8(raw);
trailing_partial_bytes = before_trim - raw.size();
}
content = normalize_text_to_lf(ensure_utf8(raw));
if (content.size() > kFileReadContentLimit) {
content = utf8_prefix_without_marker(
content,
kFileReadContentLimit);
}
displayed_line_count = static_cast<int>(
std::count(content.begin(), content.end(), '\n'));
if (!content.empty() && content.back() != '\n') {
++displayed_line_count;
}
presentation.partial = true;
presentation.byte_mode = true;
presentation.byte_start = request.byte_offset;
presentation.byte_end =
request.byte_offset +
static_cast<uint64_t>(source_bytes_read - trailing_partial_bytes);
if (presentation.byte_end < file_size) {
presentation.next_byte_offset = presentation.byte_end;
}
MtimeTracker::instance().record_read(
request.file_path,
std::string{},
true,
metadata);
} else {
const bool clean_streamable_utf8 =
!probe_result.buffer.metadata.lossy &&
(probe_result.buffer.metadata.encoding == TextEncoding::Utf8 ||
probe_result.buffer.metadata.encoding == TextEncoding::Utf8Bom) &&
probe_result.buffer.metadata.line_ending != LineEndingStyle::Cr &&
probe_result.buffer.metadata.line_ending != LineEndingStyle::Mixed;
TextBufferResult full_result;
bool has_full_buffer =
file_size <= FileOperations::MAX_EDIT_FILE_SIZE;
if (has_full_buffer) {
full_result = std::move(probe_result);
}
LineReadResult line_result;
if (!has_full_buffer && clean_streamable_utf8) {
line_result = stream_utf8_lines(
request.file_path,
probe_result.buffer.metadata.encoding == TextEncoding::Utf8Bom,
request);
} else {
if (!has_full_buffer) {
if (file_size > kLegacyReadMaterializationLimit) {
return ToolResult{
large_legacy_materialization_error(
file_size,
probe_result.buffer.metadata),
false
};
}
full_result =
read_text_file_buffer(request.file_path, true);
if (!full_result.success) {
return ToolResult{full_result.error, false};
}
has_full_buffer = true;
}
line_result =
present_materialized_lines(full_result.buffer, request);
}
if (line_result.needs_materialized_fallback) {
if (file_size > kLegacyReadMaterializationLimit) {
return ToolResult{
large_legacy_materialization_error(
file_size,
probe_result.buffer.metadata),
false
};
}
full_result = read_text_file_buffer(request.file_path, true);
if (!full_result.success) {
return ToolResult{full_result.error, false};
}
has_full_buffer = true;
line_result =
present_materialized_lines(full_result.buffer, request);
}
if (!line_result.success) {
return ToolResult{line_result.error, false};
}
if (has_full_buffer) {
metadata.encoding =
text_encoding_label(full_result.buffer.metadata.encoding);
metadata.line_ending =
line_ending_label(full_result.buffer.metadata.line_ending);
metadata.lossy = full_result.buffer.metadata.lossy;
metadata.lossy_replacement_count =
full_result.buffer.metadata.lossy_replacement_count;
if (metadata.lossy) metadata.encoding += " (lossy)";
}
if (!metadata.lossy) {
metadata.start_line = line_result.actual_start;
metadata.end_line = line_result.actual_end;
}
content = std::move(line_result.content);
displayed_line_count = line_result.displayed_line_count;
presentation.partial =
request.has_line_range ||
line_result.automatic_truncation ||
metadata.lossy;
presentation.automatic_truncation =
line_result.automatic_truncation;
presentation.next_line = line_result.next_line;
presentation.next_byte_offset =
line_result.next_byte_offset;
MtimeTracker::instance().record_read(
request.file_path,
has_full_buffer ? full_result.buffer.text : std::string{},
presentation.partial,
metadata);
}
MtimeTracker::instance().record_read_observation(
request.file_path,
request.start_line,
request.end_line,
request.byte_mode,
request.byte_offset,
request.requested_max_bytes);
bool hint_added = false;
if (!request.byte_mode &&
!request.has_line_range &&
file_size > kLargeFileHintThreshold) {
if (!content.empty() && content.back() != '\n') content += "\n";
content += "[hint: file is large (" +
std::to_string(file_size / 1024) +
"KB). This read is bounded; use next_line or "
"next_byte_offset from the metadata to continue.]";
hint_added = true;
}
if (presentation.automatic_truncation) {
if (!content.empty() && content.back() != '\n') content += "\n";
content += "[truncated: file_read returned at most " +
std::to_string(kFileReadContentLimit) +
" content bytes.";
if (presentation.next_line.has_value()) {
content += " Continue with start_line=" +
std::to_string(*presentation.next_line) + ".";
} else if (presentation.next_byte_offset.has_value()) {
content += " Continue with byte_offset=" +
std::to_string(*presentation.next_byte_offset) + ".";
}
content += "]";
}
if (metadata.lossy) {
if (!content.empty() && content.back() != '\n') content += "\n";
content += "[note: decoded with " +
std::to_string(metadata.lossy_replacement_count) +
" replacement(s) (U+FFFD); original encoding could not be "
"fully determined; editing is disabled for this lossy read.]";
}
content += format_read_metadata_footer(metadata, presentation);
ToolSummary summary;
summary.verb = "Read";