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