Skip to main content

vtcode_core/tools/file_ops/read/
mod.rs

1use super::FileOpsTool;
2use super::is_image_path;
3use super::path_policy::PathSuggestionKind;
4mod legacy;
5mod logging;
6mod segments;
7use crate::config::constants::tools;
8use crate::telemetry::perf::PerfSpan;
9use crate::tools::builder::ToolResponseBuilder;
10use crate::tools::cache::{FILE_CACHE, file_read_cache_config};
11use crate::tools::continuation::{DEFAULT_NEXT_READ_LIMIT, ReadChunkContinuationArgs};
12use crate::tools::handlers::read_file::{ReadFileArgs, ReadFileHandler, ReadFileOutcome};
13use crate::tools::traits::FileTool;
14use crate::tools::types::{Input, PathArgs};
15use anyhow::{Context, Result, anyhow};
16use serde::Deserialize;
17use serde_json::{Value, json};
18use std::path::Path;
19use std::time::UNIX_EPOCH;
20
21pub(crate) const PATCH_READ_CACHE_NONCE: &str = "__vtcode_patch_read_nonce";
22
23const SPOOL_CHUNK_DEFAULT_LIMIT_LINES: usize = DEFAULT_NEXT_READ_LIMIT;
24const SPOOL_CHUNK_MAX_LIMIT_LINES: usize = 50;
25const SPOOL_CHUNK_SENTINEL_MAX_TOKENS: usize = 4096;
26
27#[derive(Clone, Copy, Debug)]
28struct SpoolChunkPlan {
29    offset: usize,
30    limit: usize,
31}
32
33fn is_legacy_read_request(args: &Value, is_image: bool) -> bool {
34    if is_image {
35        return true;
36    }
37
38    if let Some(obj) = args.as_object() {
39        obj.keys().any(|key| {
40            matches!(
41                key.as_str(),
42                "offset_lines"
43                    | "page_size_lines"
44                    | "max_bytes"
45                    | "max_lines"
46                    | "chunk_lines"
47                    | "encoding"
48                    | "max_tokens"
49            )
50        })
51    } else {
52        false
53    }
54}
55
56fn is_new_read_request(args: &Value) -> bool {
57    let new_keys = [
58        "mode",
59        "indentation",
60        "offset",
61        "limit",
62        "o",
63        "l",
64        "offset_bytes",
65        "page_size_bytes",
66        "length",
67    ];
68    new_keys.iter().any(|key| args.get(*key).is_some())
69}
70
71fn looks_like_patch_payload(args: &Value) -> bool {
72    use crate::tools::editing::looks_like_vte_patch;
73
74    args.get("patch").and_then(Value::as_str).is_some_and(looks_like_vte_patch)
75        || args.get("input").and_then(Value::as_str).is_some_and(looks_like_vte_patch)
76        || args.as_str().is_some_and(looks_like_vte_patch)
77}
78
79fn build_read_handler_args(args: &Value, canonical_path: &Path) -> Value {
80    let mut handler_args_json = args.clone();
81    if let Some(obj) = handler_args_json.as_object_mut() {
82        for alias in ["path", "filepath", "target_path", "file"] {
83            obj.remove(alias);
84        }
85        obj.insert("file_path".to_string(), json!(canonical_path.to_string_lossy()));
86
87        if let Some(mode_value) = obj.get("mode").cloned() {
88            let normalized_mode = match mode_value {
89                Value::Null => None,
90                Value::String(raw) => {
91                    let trimmed = raw.trim();
92                    if trimmed.eq_ignore_ascii_case("indentation") {
93                        Some("indentation".to_string())
94                    } else {
95                        Some("slice".to_string())
96                    }
97                }
98                _ => Some("slice".to_string()),
99            };
100
101            if let Some(mode) = normalized_mode {
102                obj.insert("mode".to_string(), json!(mode));
103            } else {
104                obj.remove("mode");
105            }
106        }
107
108        if let Some(indentation_value) = obj.get("indentation").cloned() {
109            match indentation_value {
110                Value::Bool(true) => {
111                    obj.insert("mode".to_string(), json!("indentation"));
112                    obj.insert("indentation".to_string(), json!({}));
113                }
114                Value::Bool(false) | Value::Null => {
115                    obj.remove("indentation");
116                    if obj
117                        .get("mode")
118                        .and_then(Value::as_str)
119                        .is_some_and(|mode| mode.eq_ignore_ascii_case("indentation"))
120                    {
121                        obj.insert("mode".to_string(), json!("slice"));
122                    }
123                }
124                Value::String(text) if text.eq_ignore_ascii_case("true") => {
125                    obj.insert("mode".to_string(), json!("indentation"));
126                    obj.insert("indentation".to_string(), json!({}));
127                }
128                Value::String(text) if text.eq_ignore_ascii_case("false") => {
129                    obj.remove("indentation");
130                    if obj
131                        .get("mode")
132                        .and_then(Value::as_str)
133                        .is_some_and(|mode| mode.eq_ignore_ascii_case("indentation"))
134                    {
135                        obj.insert("mode".to_string(), json!("slice"));
136                    }
137                }
138                Value::Object(_) => {
139                    obj.insert("mode".to_string(), json!("indentation"));
140                }
141                _ => {}
142            }
143        }
144
145        if let Some(src) = obj.get("offset_lines").or_else(|| obj.get("o")).cloned() {
146            obj.entry("offset".to_string()).or_insert(src);
147        }
148        if let Some(src) = obj.get("page_size_lines").or_else(|| obj.get("l")).cloned() {
149            obj.entry("limit".to_string()).or_insert(src);
150        }
151
152        // Map `length` alias to `page_size_bytes` for byte-range reads
153        if let Some(src) = obj.get("length").cloned() {
154            obj.entry("page_size_bytes".to_string()).or_insert(src);
155        }
156
157        // Map start_line/end_line to offset/limit when offset is not already set.
158        if let Some(start) = obj.get("start_line").and_then(parse_usize_value) {
159            obj.entry("offset".to_string()).or_insert(json!(start));
160            if let Some(end) = obj.get("end_line").and_then(parse_usize_value)
161                && end >= start
162                && !obj.contains_key("limit")
163            {
164                // Saturate: user-supplied bounds reach `usize::MAX`, and
165                // release keeps `overflow-checks = true`.
166                obj.insert("limit".to_string(), json!(end.saturating_sub(start).saturating_add(1)));
167            }
168        }
169
170        if obj.get("offset").and_then(parse_usize_value) == Some(0) {
171            obj.insert("offset".to_string(), json!(1));
172        }
173        if obj.get("limit").and_then(parse_usize_value) == Some(0) {
174            obj.remove("limit");
175        }
176    }
177
178    handler_args_json
179}
180
181/// Locate a verbatim line slice using the selected reader's coordinate system.
182pub(crate) fn source_line_offset(args: &Value) -> Option<usize> {
183    if !is_new_read_request(args) && is_legacy_read_request(args, false) {
184        // Legacy line paging is zero-based; modern slice offsets are one-based.
185        let input: Input = serde_json::from_value(args.clone()).ok()?;
186        return Some(input.offset_lines.unwrap_or(0));
187    }
188    let normalized = build_read_handler_args(args, Path::new("source"));
189    let read: ReadFileArgs = serde_json::from_value(normalized).ok()?;
190    if read.offset_bytes.is_some()
191        || read.page_size_bytes.is_some()
192        || !matches!(read.mode, crate::tools::handlers::read_file::ReadMode::Slice)
193    {
194        return None;
195    }
196    read.offset.checked_sub(1)
197}
198
199/// Admit recovery only for an explicit line range the selected reader honors.
200pub(crate) fn bounded_line_read_path(args: &Value, max_lines: usize) -> Option<String> {
201    let path_args: PathArgs = serde_json::from_value(args.clone()).ok()?;
202    let path = Path::new(&path_args.path);
203    if is_image_path(path) {
204        return None;
205    }
206    if is_new_read_request(args) || !is_legacy_read_request(args, false) {
207        let normalized = build_read_handler_args(args, path);
208        // A missing/zero bound uses the handler default, not a targeted range.
209        normalized.get("limit").and_then(parse_usize_value)?;
210        let read: ReadFileArgs = serde_json::from_value(normalized).ok()?;
211        if !(1..=max_lines).contains(&read.limit)
212            || read.effective_line_limit() > max_lines
213            || read.offset == 0
214            || read.offset_bytes.is_some()
215            || read.page_size_bytes.is_some()
216            || !matches!(read.mode, crate::tools::handlers::read_file::ReadMode::Slice)
217        {
218            return None;
219        }
220    } else {
221        let read: Input = serde_json::from_value(args.clone()).ok()?;
222        let limit = read.page_size_lines?;
223        if !(1..=max_lines).contains(&limit) || read.offset_bytes.is_some() || read.page_size_bytes.is_some() {
224            return None;
225        }
226    }
227    Some(path_args.path)
228}
229
230fn parse_usize_value(value: &Value) -> Option<usize> {
231    value
232        .as_u64()
233        .and_then(|n| usize::try_from(n).ok())
234        .or_else(|| value.as_str().and_then(|s| s.parse::<usize>().ok()))
235}
236
237fn has_explicit_limit(args: &Value) -> bool {
238    ["limit", "l", "page_size_lines", "max_lines", "chunk_lines", "end_line"]
239        .iter()
240        .any(|key| args.get(*key).is_some())
241}
242
243fn has_explicit_offset(args: &Value) -> bool {
244    ["offset", "o", "offset_lines", "offset_bytes", "start_line"]
245        .iter()
246        .any(|key| args.get(*key).is_some())
247}
248
249fn is_full_text_read(args: &Value, is_spool_output: bool) -> bool {
250    !is_spool_output && !has_explicit_offset(args) && !has_explicit_limit(args)
251}
252
253use super::restore_exact_text_content;
254
255fn response_size_bytes(response: &Value) -> Option<u64> {
256    response
257        .get("metadata")
258        .and_then(|metadata| metadata.get("data"))
259        .and_then(|data| data.get("size_bytes"))
260        .and_then(Value::as_u64)
261}
262
263fn apply_spool_chunk_defaults(handler_args_json: &mut Value, raw_args: &Value) -> SpoolChunkPlan {
264    let mut offset = 1usize;
265    let mut limit = SPOOL_CHUNK_DEFAULT_LIMIT_LINES;
266
267    if let Some(obj) = handler_args_json.as_object_mut() {
268        offset = obj.get("offset").and_then(parse_usize_value).unwrap_or(1).max(1);
269
270        let requested_limit = if has_explicit_limit(raw_args) {
271            raw_args
272                .get("limit")
273                .or_else(|| raw_args.get("l"))
274                .or_else(|| raw_args.get("page_size_lines"))
275                .or_else(|| raw_args.get("max_lines"))
276                .or_else(|| raw_args.get("chunk_lines"))
277                .and_then(parse_usize_value)
278                .unwrap_or(SPOOL_CHUNK_DEFAULT_LIMIT_LINES)
279        } else {
280            SPOOL_CHUNK_DEFAULT_LIMIT_LINES
281        };
282
283        limit = requested_limit.clamp(1, SPOOL_CHUNK_MAX_LIMIT_LINES);
284
285        obj.insert("offset".to_string(), json!(offset));
286        obj.insert("limit".to_string(), json!(limit));
287        // Preserve narrow chunking behavior by bypassing MIN_BATCH_LIMIT expansion
288        // in ReadFileHandler::handle (which only applies when max_tokens is absent).
289        obj.entry("max_tokens".to_string())
290            .or_insert_with(|| json!(SPOOL_CHUNK_SENTINEL_MAX_TOKENS));
291    }
292
293    SpoolChunkPlan { offset, limit }
294}
295
296fn path_contains_components(path: &Path, needle: &[&str]) -> bool {
297    // Fail closed on empty needle: vacuous-true would mark every path as
298    // privileged, and `windows(0)` would panic without this guard.
299    if needle.is_empty() {
300        return false;
301    }
302    use std::ffi::OsStr;
303    let components: Vec<&OsStr> = path.components().map(|c| c.as_os_str()).collect();
304    components
305        .windows(needle.len())
306        .any(|window| window.iter().zip(needle.iter()).all(|(hay, ndl)| *hay == OsStr::new(ndl)))
307}
308
309fn is_history_jsonl(path: &Path) -> bool {
310    // Fast path: avoid component iteration if extension doesn't match
311    if path.extension().and_then(|ext| ext.to_str()) != Some("jsonl") {
312        return false;
313    }
314
315    path_contains_components(path, &[".vtcode", "history"])
316}
317
318fn is_tool_output_spool_path(path: &Path) -> bool {
319    crate::tools::SpooledOutputReference::recognizes_path(path)
320}
321
322fn pty_session_id_from_tool_output_path(path: &Path) -> Option<String> {
323    let file_name = path.file_name()?.to_str()?;
324    let session_file = file_name.strip_suffix(".txt")?;
325    let session_id = session_file.trim_prefix("write_stdin_");
326    if session_id.starts_with("run-")
327        && session_id.len() > "run-".len()
328        && session_id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
329    {
330        Some(session_id.to_string())
331    } else {
332        None
333    }
334}
335
336fn build_history_cache_key(path: &Path, metadata: &std::fs::Metadata, args: &Value) -> Option<String> {
337    let modified = metadata.modified().ok()?;
338    let mtime = modified.duration_since(UNIX_EPOCH).ok()?.as_millis();
339    let size = metadata.len();
340
341    let mode = args.get("mode").and_then(Value::as_str).unwrap_or("legacy");
342    let indentation = args.get("indentation").and_then(Value::as_str).unwrap_or("");
343    let offset = args
344        .get("offset")
345        .or_else(|| args.get("o"))
346        .or_else(|| args.get("offset_lines"))
347        .or_else(|| args.get("offset_bytes"))
348        .and_then(Value::as_u64)
349        .unwrap_or(0);
350    let limit = args
351        .get("limit")
352        .or_else(|| args.get("l"))
353        .or_else(|| args.get("page_size_lines"))
354        .or_else(|| args.get("page_size_bytes"))
355        .and_then(Value::as_u64)
356        .unwrap_or(0);
357    let max_bytes = args.get("max_bytes").and_then(Value::as_u64).unwrap_or(0);
358    let max_tokens = args.get("max_tokens").and_then(Value::as_u64).unwrap_or(0);
359    let encoding = args.get("encoding").and_then(Value::as_str).unwrap_or("");
360
361    Some(format!(
362        "read_file:history:{}:{}:{}:mode={mode}|indent={indentation}|offset={offset}|limit={limit}|max_bytes={max_bytes}|max_tokens={max_tokens}|encoding={encoding}",
363        path.display(),
364        size,
365        mtime
366    ))
367}
368
369impl FileOpsTool {
370    async fn track_read_snapshot(&self, path: &Path) {
371        if let Err(err) = self.edited_file_monitor.track_read(path).await {
372            tracing::warn!(
373                path = %path.display(),
374                error = %err,
375                "Failed to record edited-file read snapshot"
376            );
377        }
378    }
379
380    fn track_read_text_snapshot(&self, path: &Path, content: &str) {
381        if let Err(err) = self.edited_file_monitor.record_read_text(path, content) {
382            tracing::warn!(
383                path = %path.display(),
384                error = %err,
385                "Failed to record edited-file read snapshot"
386            );
387        }
388    }
389
390    async fn track_exact_text_snapshot(&self, path: &Path, content: &str, size_bytes: u64) {
391        if let Some(exact_content) = restore_exact_text_content(content, size_bytes) {
392            self.track_read_text_snapshot(path, &exact_content);
393        } else {
394            self.track_read_snapshot(path).await;
395        }
396    }
397
398    async fn track_cached_read_snapshot(&self, path: &Path, args: &Value, response: &Value) {
399        if is_full_text_read(args, false)
400            && let Some(content) = response.get("content").and_then(Value::as_str)
401            && let Some(size_bytes) = response_size_bytes(response)
402        {
403            self.track_exact_text_snapshot(path, content, size_bytes).await;
404            return;
405        }
406
407        self.track_read_snapshot(path).await;
408    }
409
410    pub async fn read_file(&self, args: Value) -> Result<Value> {
411        let use_cache = args.get(PATCH_READ_CACHE_NONCE).is_none();
412        self.read_file_with_cache(args, use_cache).await
413    }
414
415    async fn read_file_with_cache(&self, args: Value, use_cache: bool) -> Result<Value> {
416        let mut perf = PerfSpan::new("vtcode.perf.read_file_ms");
417
418        let path_args: PathArgs = PathArgs::deserialize(&args).map_err(|_e| {
419            if looks_like_patch_payload(&args) {
420                return anyhow!(
421                    "Error: Patch content was sent to read_file.\n\
422                    Use apply_patch with {{\"patch\":\"...\"}} \
423                    (or {{\"input\":\"...\"}}).\n\
424                    read_file requires a path parameter."
425                );
426            }
427            let received = serde_json::to_string(&args).unwrap_or_else(|_| "{}".to_string());
428            anyhow!(
429                "Error: Invalid 'read_file' arguments. Missing required path parameter.\n\
430                Received: {received}\n\
431                Expected: {{\"path\": \"file/path\"}} or {{\"file_path\": \"file/path\"}}\n\
432                Accepted path parameters: path, file_path, filepath, target_path, file, p\n\
433                Optional params: offset_lines, limit, max_bytes, max_tokens"
434            )
435        })?;
436
437        let path_str = &path_args.path;
438
439        // Try to resolve the file path
440        let potential_paths = self.resolve_file_path(path_str).await?;
441        let missing_spool_candidate = potential_paths
442            .iter()
443            .find(|candidate| is_tool_output_spool_path(candidate.as_path()))
444            .cloned();
445        let mut directory_candidate = None;
446
447        for candidate_path in &potential_paths {
448            if !tokio::fs::try_exists(candidate_path).await? {
449                continue;
450            }
451
452            let canonical = self.normalize_and_validate_candidate(candidate_path, path_str).await?;
453
454            if self.should_exclude(&canonical).await {
455                continue;
456            }
457
458            let metadata = tokio::fs::metadata(&canonical).await?;
459            if !metadata.is_file() {
460                if metadata.is_dir() && directory_candidate.is_none() {
461                    directory_candidate = Some(canonical);
462                }
463                continue;
464            }
465
466            let size_bytes = metadata.len();
467            let history_jsonl = is_history_jsonl(&canonical);
468            perf.tag("path_class", if history_jsonl { "history_jsonl" } else { "other" });
469            let is_image = is_image_path(&canonical);
470            let is_spool_output = is_tool_output_spool_path(&canonical);
471            let is_legacy_request = is_legacy_read_request(&args, is_image);
472            let is_new_request = is_new_read_request(&args);
473
474            let cache_config = file_read_cache_config();
475            let cache_key = if use_cache
476                && cache_config.enabled
477                && history_jsonl
478                && size_bytes >= cache_config.min_size_bytes as u64
479                && size_bytes <= cache_config.max_size_bytes as u64
480            {
481                build_history_cache_key(&canonical, &metadata, &args)
482            } else {
483                None
484            };
485
486            if let Some(key) = cache_key.as_ref()
487                && let Some(cached) = FILE_CACHE.get_file(key).await
488            {
489                perf.tag("cache", "hit");
490                self.track_cached_read_snapshot(&canonical, &args, &cached).await;
491                return Ok(cached);
492            }
493            perf.tag("cache", if cache_key.is_some() { "miss" } else { "skip" });
494
495            if !is_image && (is_new_request || !is_legacy_request) {
496                let mut handler_args_json = build_read_handler_args(&args, &canonical);
497                let spool_plan = if is_spool_output {
498                    Some(apply_spool_chunk_defaults(&mut handler_args_json, &args))
499                } else {
500                    None
501                };
502                match serde_json::from_value::<ReadFileArgs>(handler_args_json) {
503                    Ok(read_args) => {
504                        let requested_path = self.workspace_relative_display(&canonical);
505                        let handler = ReadFileHandler;
506                        let requested_offset = read_args.offset;
507                        let ReadFileOutcome {
508                            content,
509                            lines_read: lines_returned,
510                            has_more,
511                            line_truncated,
512                            capped_by_limit,
513                            applied_limit,
514                        } = handler.handle_detailed(read_args).await?;
515                        let full_text_read = is_full_text_read(&args, is_spool_output);
516                        let response_content = if full_text_read {
517                            restore_exact_text_content(&content, size_bytes).unwrap_or_else(|| content.clone())
518                        } else {
519                            content.clone()
520                        };
521
522                        let mut builder = ToolResponseBuilder::new(tools::READ_FILE)
523                            .success()
524                            .message(format!("Successfully read file {requested_path}"))
525                            .content(&response_content)
526                            .field("path", json!(requested_path.clone()))
527                            .field("no_spool", json!(true))
528                            .field("content_kind", json!("text"))
529                            .field("encoding", json!("utf8"))
530                            .data("size_bytes", json!(size_bytes))
531                            .data("content_kind", json!("text"))
532                            .data("encoding", json!("utf8"));
533
534                        if line_truncated {
535                            builder = builder
536                                .field("line_truncated", json!(true))
537                                .field("truncated", json!(true))
538                                .field("truncation_reason", json!("oversized_line"));
539                        }
540
541                        if let Some(plan) = spool_plan {
542                            let next_offset = plan.offset.saturating_add(lines_returned);
543
544                            builder = builder
545                                .field("spool_chunked", json!(true))
546                                .field("lines_returned", json!(lines_returned));
547                            if has_more {
548                                builder = builder.field("has_more", json!(true));
549                                builder = builder.field(
550                                    "next_read_args",
551                                    ReadChunkContinuationArgs::new(requested_path.clone(), next_offset, plan.limit)
552                                        .to_value(),
553                                );
554                                builder = builder.field(
555                                    "next_action",
556                                    json!(
557                                        "Call file read again with the `next_read_args` object above verbatim as arguments to get the next chunk, or narrow with `exec_command.cmd` using `rg` and a specific pattern. Re-reading the same offset returns nothing new and counts toward the per-turn spool chunk cap, which blocks further reads."
558                                    ),
559                                );
560                            }
561                        }
562                        // Absolute-cap continuation. Surface a structured way to
563                        // keep reading after the per-call ceiling was reached.
564                        //
565                        // The condition is `has_more && applied_limit == cap` rather
566                        // than `capped_by_limit && has_more`: on the first (clamped)
567                        // page `applied_limit` equals the cap and `capped_by_limit`
568                        // is true, but on every follow-up page the agent passes back
569                        // `applied_limit` as its `limit`, so `effective_limit` is no
570                        // longer *greater* than the cap and `capped_by_limit` becomes
571                        // false. Using `applied_limit == cap` keeps the pagination
572                        // chain alive on every page that actually hit the ceiling,
573                        // instead of dying after a single hop.
574                        // Byte-range reads set `applied_limit` to 0, so they are
575                        // correctly excluded and use their own `offset_bytes`/
576                        // `page_size_bytes` continuation path.
577                        else if has_more && applied_limit == crate::tools::read_limits::absolute_line_cap() {
578                            let next_offset = requested_offset.saturating_add(lines_returned);
579                            let next_action = if capped_by_limit {
580                                "Read clamped to max_read_lines. \
581                                 Call file read again with `next_read_args` verbatim to get subsequent chunks; \
582                                 do not re-read the same range."
583                            } else {
584                                "Call file read again with `next_read_args` verbatim to get subsequent chunks; \
585                                 do not re-read the same range."
586                            };
587                            builder = builder
588                                .field("has_more", json!(true))
589                                .field("capped_by_limit", json!(capped_by_limit))
590                                .field(
591                                    "next_read_args",
592                                    ReadChunkContinuationArgs::new(requested_path.clone(), next_offset, applied_limit)
593                                        .to_value(),
594                                )
595                                .field("next_action", json!(next_action));
596                        }
597
598                        let response = builder.build_json();
599
600                        if full_text_read {
601                            self.track_exact_text_snapshot(&canonical, &response_content, size_bytes).await;
602                        } else {
603                            self.track_read_snapshot(&canonical).await;
604                        }
605                        if let Some(key) = cache_key.as_ref() {
606                            FILE_CACHE.put_file(key.clone(), response.clone()).await;
607                        }
608
609                        return Ok(response);
610                    }
611                    Err(e) => {
612                        if is_new_request {
613                            return Err(anyhow!(
614                                "Failed to parse arguments for read_file handler: {e}. Args: {args:?}"
615                            ));
616                        }
617                    }
618                }
619            }
620
621            // Legacy path
622            let input: Input = serde_json::from_value(args.clone())
623                .context("Error: Invalid 'read_file' arguments for legacy handler.")?;
624
625            // Check if paging/offset is requested
626            let use_paging = input.offset_bytes.is_some()
627                || input.page_size_bytes.is_some()
628                || input.offset_lines.is_some()
629                || input.page_size_lines.is_some();
630
631            let (content, metadata, truncated, line_truncated) = if use_paging {
632                self.read_file_paged(&canonical, &input).await?
633            } else {
634                let (content, metadata, truncated) = self.read_file_legacy(&canonical, &input).await?;
635                let line_truncated = metadata.get("line_truncated").and_then(Value::as_bool).unwrap_or(false);
636                (content, metadata, truncated, line_truncated)
637            };
638
639            let mut builder = ToolResponseBuilder::new(tools::READ_FILE)
640                .success()
641                .message(format!(
642                    "Successfully read {} bytes from {}",
643                    size_bytes,
644                    self.workspace_relative_display(&canonical)
645                ))
646                .content(&content)
647                .field("path", json!(self.workspace_relative_display(&canonical)))
648                .field("no_spool", json!(true));
649
650            // Merge legacy metadata - extract actual data fields, not wrapper structure
651            if let Some(obj) = metadata.as_object() {
652                for (k, v) in obj {
653                    builder = builder.data(k.clone(), v.clone());
654                }
655            }
656
657            // Special legacy fields at top level
658            if let Some(is_truncated) = metadata.get("is_truncated").and_then(Value::as_bool) {
659                builder = builder.field("is_truncated", json!(is_truncated));
660            }
661            if line_truncated {
662                builder = builder.field("line_truncated", json!(true));
663            }
664            if let Some(encoding) = metadata.get("encoding").and_then(Value::as_str) {
665                builder = builder.field("encoding", json!(encoding));
666            }
667            if let Some(content_kind) = metadata.get("content_kind").and_then(Value::as_str) {
668                builder = builder.field("content_kind", json!(content_kind));
669                if matches!(content_kind, "binary" | "image") {
670                    builder = builder.field("binary", json!(true));
671                }
672            }
673            if let Some(mime_type) = metadata.get("mime_type").and_then(Value::as_str) {
674                builder = builder.field("mime_type", json!(mime_type));
675            }
676
677            // Add paging information
678            if use_paging {
679                if let Some(offset_bytes) = input.offset_bytes {
680                    builder = builder.field("offset_bytes", json!(offset_bytes));
681                }
682                if let Some(page_size_bytes) = input.page_size_bytes {
683                    builder = builder.field("page_size_bytes", json!(page_size_bytes));
684                }
685                if let Some(offset_lines) = input.offset_lines {
686                    builder = builder.field("offset_lines", json!(offset_lines));
687                }
688                if let Some(page_size_lines) = input.page_size_lines {
689                    builder = builder.field("page_size_lines", json!(page_size_lines));
690                }
691                if truncated {
692                    builder = builder.field("truncated", json!(true));
693                    builder = builder.field(
694                        "truncation_reason",
695                        json!(if line_truncated {
696                            "oversized_line"
697                        } else {
698                            "reached_end_of_file"
699                        }),
700                    );
701                }
702            }
703
704            let content_kind = metadata.get("content_kind").and_then(Value::as_str).unwrap_or("text");
705            let full_legacy_text_read = !use_paging && !truncated && content_kind == "text";
706            let response = builder.build_json();
707            if full_legacy_text_read {
708                self.track_exact_text_snapshot(&canonical, &content, size_bytes).await;
709            } else {
710                self.track_read_snapshot(&canonical).await;
711            }
712            if let Some(key) = cache_key.as_ref() {
713                FILE_CACHE.put_file(key.clone(), response.clone()).await;
714            }
715
716            return Ok(response);
717        }
718
719        if let Some(spool_path) = missing_spool_candidate {
720            if let Some(session_id) = pty_session_id_from_tool_output_path(&spool_path) {
721                return Err(anyhow!(
722                    "Error: Session output file not found: {}. This looks like command session output. Use write_stdin with session_id=\"{}\" to poll or continue the active session.",
723                    self.workspace_relative_display(&spool_path),
724                    session_id,
725                ));
726            }
727            return Err(anyhow!(
728                "Error: Spool file not found (possibly expired): {}. Re-run the original tool command to regenerate this output.",
729                self.workspace_relative_display(&spool_path),
730            ));
731        }
732
733        if let Some(directory_path) = directory_candidate {
734            let display_path = self.workspace_relative_display(&directory_path);
735            return Err(anyhow!(
736                "Error: Path '{display_path}' is a directory, not a file. Use `exec_command.cmd` with `find` or `ls` to inspect it.",
737            ));
738        }
739
740        let parent_dir = Path::new(path_str)
741            .parent()
742            .map(|p| p.to_string_lossy().to_string())
743            .unwrap_or_else(|| ".".to_string());
744        let suggestion = self.missing_path_suggestion_suffix(path_str, PathSuggestionKind::File).await;
745        Err(anyhow!(
746            "Error: File not found: {}. Tried paths: {}.{} Use `exec_command.cmd` with `find {}` to discover available files.",
747            path_str,
748            potential_paths
749                .iter()
750                .map(|p| self.workspace_relative_display(p))
751                .collect::<Vec<_>>()
752                .join(", "),
753            suggestion,
754            parent_dir
755        ))
756    }
757}
758
759#[cfg(test)]
760mod read_tests;