diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/file_read_tool.rs b/src/crates/assembly/core/src/agentic/tools/implementations/file_read_tool.rs index 9684b339bd..f0b958d3ec 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/file_read_tool.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/file_read_tool.rs @@ -32,7 +32,8 @@ use tool_runtime::fs::document::{ is_supported_document_path, DocumentPageSelection, DocumentPagination, PdfTextCoverage, }; use tool_runtime::fs::read_file::{ - build_read_file_presentation, read_file_from_reader, read_file_tail_from_reader, ReadFileResult, + build_read_file_presentation_with_budget, read_file_from_reader, read_file_tail_from_reader, + ReadCallBudget, ReadFileResult, DEFAULT_READ_MAX_LINES, }; #[cfg(any(feature = "document-read", feature = "tools-miniapp"))] use tool_runtime::fs::read_file::{read_text, read_text_tail}; @@ -44,7 +45,8 @@ pub struct FileReadTool { } /// Default cap on characters returned by a single Read call (excluding wrapper text). -pub const DEFAULT_READ_MAX_TOTAL_CHARS: usize = 64_000; +pub const DEFAULT_READ_MAX_TOTAL_CHARS: usize = + tool_runtime::fs::read_file::DEFAULT_READ_MAX_TOTAL_CHARS; // Coverage metadata remains complete; a tiny line window must not emit an unbounded gap list. const MAX_PDF_OCR_PAGE_RANGES: usize = 32; #[cfg(feature = "document-read")] @@ -75,7 +77,7 @@ impl Default for FileReadTool { impl FileReadTool { pub fn new() -> Self { Self { - default_max_lines_to_read: 2000, + default_max_lines_to_read: DEFAULT_READ_MAX_LINES, max_line_chars: 2000, max_total_chars: DEFAULT_READ_MAX_TOTAL_CHARS, } @@ -93,6 +95,10 @@ impl FileReadTool { } } + fn call_budget(&self) -> ReadCallBudget { + ReadCallBudget::new(self.default_max_lines_to_read, self.max_total_chars) + } + fn already_served_result( logical_path: &str, coverage: crate::agentic::session::ReviewReadCoverage, @@ -356,9 +362,11 @@ Use pages to select units after inspecting page_kind/page_count, especially when Ok(format!( r#"Read a file from the active workspace, including a remote workspace. Use LS/Glob for directories and an image tool for images. -Returns numbered lines (line number, tab, text). Choose the window needed for the task; the default is up to {} lines. File content is capped at {} characters per line and {} characters per call. Follow next_offset for additional lines when useful. A truncated line needs another inspection method; rereading the same line window cannot recover its omitted characters. Use only complete source text for Edit. +Returns numbered lines (line number, tab, text). Prefer one call per file: omit limit to use the whole per-call budget of up to {max_lines} lines and {max_total_chars} characters in total, which covers most files at once. Set offset/limit only for a range you already know, or after Grep located it in a file larger than that budget; do not page a large file window by window. The continuation note states how many lines remain and whether one more call can return all of them. Separately, each returned line is capped at {max_line_chars} characters and a longer line ends with [truncated]. A truncated line needs another inspection method; rereading the same line window cannot recover its omitted characters. Use only complete source text for Edit. {document_guidance}"#, - self.default_max_lines_to_read, self.max_line_chars, self.max_total_chars + max_lines = self.default_max_lines_to_read, + max_total_chars = self.max_total_chars, + max_line_chars = self.max_line_chars, )) } @@ -387,7 +395,7 @@ Returns numbered lines (line number, tab, text). Choose the window needed for th }, "limit": { "type": "number", - "description": "Positive integer number of lines to return. Choose a window that covers the relevant context." + "description": "Positive integer number of lines to return. Omit it to read up to the full per-call budget in one call; set it only when a specific range is enough." } }, "required": ["file_path"], @@ -679,8 +687,11 @@ Returns numbered lines (line number, tab, text). Choose the window needed for th ) } .map_err(OpenBitFunError::tool)?; - let presentation = - build_read_file_presentation(&resolved.logical_path, &read_file_result); + let presentation = build_read_file_presentation_with_budget( + &resolved.logical_path, + &read_file_result, + self.call_budget(), + ); return Ok(vec![ToolResult::Result { data: json!({ "file_path": resolved.logical_path, @@ -832,7 +843,11 @@ Returns numbered lines (line number, tab, text). Choose the window needed for th } } - let presentation = build_read_file_presentation(&resolved.logical_path, &read_file_result); + let presentation = build_read_file_presentation_with_budget( + &resolved.logical_path, + &read_file_result, + self.call_budget(), + ); let mut result_for_assistant = presentation.result_for_assistant; let mut data = json!({ @@ -920,7 +935,7 @@ Returns numbered lines (line number, tab, text). Choose the window needed for th } else { "keep pages omitted".to_string() }; - format!("To continue this extraction, {same_selection} and use offset={next_offset}; or choose a narrower pages range starting at offset=1.") + format!("To continue this extraction, {same_selection} and use offset={next_offset} without limit; or choose a narrower pages range starting at offset=1.") } else { "Choose another pages range if more context is needed.".to_string() }; diff --git a/src/crates/assembly/core/src/agentic/tools/tool_result_storage.rs b/src/crates/assembly/core/src/agentic/tools/tool_result_storage.rs index 952f203aa7..0c688b4a55 100644 --- a/src/crates/assembly/core/src/agentic/tools/tool_result_storage.rs +++ b/src/crates/assembly/core/src/agentic/tools/tool_result_storage.rs @@ -19,8 +19,10 @@ use openbitfun_agent_tools::{DEFAULT_MAX_TOOL_RESULT_CHARS, PERSISTED_OUTPUT_TAG use std::collections::HashSet; use std::path::Path; -/// Keep in sync with `FileReadTool::DEFAULT_READ_MAX_TOTAL_CHARS` plus wrapper overhead. -pub(crate) const READ_MAX_TOOL_RESULT_CHARS: usize = 72_000; +/// Read's own per-call content cap plus room for its wrapper text, so a full +/// default Read window is returned inline instead of being persisted. +pub(crate) const READ_MAX_TOOL_RESULT_CHARS: usize = + crate::agentic::tools::implementations::file_read_tool::DEFAULT_READ_MAX_TOTAL_CHARS + 8_000; const READ_TOOL_NAME: &str = "Read"; diff --git a/src/crates/execution/tool-execution/src/fs/read_file.rs b/src/crates/execution/tool-execution/src/fs/read_file.rs index 9c37c2e4aa..86f6f91e9f 100644 --- a/src/crates/execution/tool-execution/src/fs/read_file.rs +++ b/src/crates/execution/tool-execution/src/fs/read_file.rs @@ -13,6 +13,9 @@ pub struct ReadFileResult { pub content_truncated: bool, /// Selected source lines whose contents were clipped by the per-line limit. pub truncated_lines: Vec, + /// Characters the lines after `end_line` would occupy in a follow-up call + /// that starts at `end_line + 1`, rendered with the same per-line limit. + pub remaining_chars: usize, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -22,6 +25,34 @@ pub struct ReadFilePresentation { pub next_offset: Option, } +/// Per-call budgets a Read implementation advertises in its continuation +/// guidance. A follow-up call that omits `limit` returns the whole remaining +/// window in one step only when it fits both budgets. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ReadCallBudget { + pub max_lines: usize, + pub max_total_chars: usize, +} + +impl ReadCallBudget { + pub const fn new(max_lines: usize, max_total_chars: usize) -> Self { + Self { + max_lines, + max_total_chars, + } + } +} + +impl Default for ReadCallBudget { + fn default() -> Self { + Self::new(DEFAULT_READ_MAX_LINES, DEFAULT_READ_MAX_TOTAL_CHARS) + } +} + +/// Default line and character window a single Read call may return. +pub const DEFAULT_READ_MAX_LINES: usize = 2000; +pub const DEFAULT_READ_MAX_TOTAL_CHARS: usize = 64_000; + fn read_file_lines_read(result: &ReadFileResult) -> usize { if result.total_lines == 0 || result.end_line < result.start_line { 0 @@ -33,6 +64,14 @@ fn read_file_lines_read(result: &ReadFileResult) -> usize { pub fn build_read_file_presentation( logical_path: &str, result: &ReadFileResult, +) -> ReadFilePresentation { + build_read_file_presentation_with_budget(logical_path, result, ReadCallBudget::default()) +} + +pub fn build_read_file_presentation_with_budget( + logical_path: &str, + result: &ReadFileResult, + budget: ReadCallBudget, ) -> ReadFilePresentation { let lines_read = read_file_lines_read(result); let mut result_for_assistant = if result.total_lines == 0 { @@ -52,17 +91,37 @@ pub fn build_read_file_presentation( let has_more = lines_read > 0 && result.end_line < result.total_lines; let next_start_line = has_more.then_some(result.end_line + 1); if let Some(next_start) = next_start_line { - if result.hit_total_char_limit { - result_for_assistant.push_str(&format!( - "\n\n[Output truncated after reaching the Read tool size limit. Use offset={} and limit to continue reading.]", - next_start - )); + // State what one more call can still return. Without the remaining + // count and the per-call budget, callers page a large file window by + // window instead of continuing in one step. "Fits" must hold for both + // budgets, or a long-line tail would be promised and then cut again. + let remaining_lines = result.total_lines - result.end_line; + let fits_in_one_call = + remaining_lines <= budget.max_lines && result.remaining_chars <= budget.max_total_chars; + let window = if result.hit_total_char_limit { + "Output truncated after reaching the Read tool size limit".to_string() } else { - result_for_assistant.push_str(&format!( - "\n\n[Showing lines {}-{} of {} total. Use offset={} and limit to continue reading.]", - result.start_line, result.end_line, result.total_lines, next_start - )); - } + format!( + "Showing lines {}-{} of {} total", + result.start_line, result.end_line, result.total_lines + ) + }; + let next_step = if fits_in_one_call { + format!("All of it fits in one call: use offset={next_start} without limit.") + } else { + format!( + "Use offset={} without limit to read up to {} lines and {} characters per call, or offset/limit for a known range.", + next_start, budget.max_lines, budget.max_total_chars + ) + }; + let unit = if remaining_lines == 1 { + "line" + } else { + "lines" + }; + result_for_assistant.push_str(&format!( + "\n\n[{window} ({remaining_lines} {unit} remaining). {next_step}]" + )); } if !result.truncated_lines.is_empty() { result_for_assistant.push_str(&format!( @@ -419,6 +478,7 @@ struct ReadLineSelection { hit_total_char_limit: bool, content_truncated: bool, truncated_lines: Vec, + remaining_chars: usize, tail_lines: Option>, } @@ -454,18 +514,24 @@ impl ReadLineSelection { hit_total_char_limit: false, content_truncated: false, truncated_lines: Vec::new(), + remaining_chars: 0, tail_lines: tail.then(VecDeque::new), }) } fn push(&mut self, line: String, truncated: bool) { self.total_lines += 1; - if self.tail_lines.is_none() - && (self.total_lines < self.start_line - || self.total_lines > self.end_line - || self.hit_total_char_limit) - { - return; + if self.tail_lines.is_none() { + if self.total_lines < self.start_line { + return; + } + if self.total_lines > self.end_line || self.hit_total_char_limit { + // Measure without rendering: everything past the returned + // window only feeds the continuation guidance. + let chars = rendered_line_chars(self.total_lines, line.chars().count(), truncated); + self.add_remaining(chars); + return; + } } let line = if truncated { format!("{line} [truncated]") @@ -484,13 +550,19 @@ impl ReadLineSelection { fn select(&mut self, line_number: usize, line: String, truncated: bool) { let rendered = format!("{line_number:>6}\t{line}"); + let rendered_chars = rendered.chars().count(); + if self.hit_total_char_limit { + self.add_remaining(rendered_chars); + return; + } let next_chars = self .selected_chars .saturating_add(usize::from(!self.selected_lines.is_empty())) - .saturating_add(rendered.chars().count()); + .saturating_add(rendered_chars); if next_chars > self.max_total_chars { self.hit_total_char_limit = true; self.content_truncated = true; + self.add_remaining(rendered_chars); } else { self.content_truncated |= truncated; if truncated { @@ -501,6 +573,15 @@ impl ReadLineSelection { } } + fn add_remaining(&mut self, rendered_chars: usize) { + // Rendered lines are never empty, so a non-zero total means a newline + // separator precedes this line in the follow-up output. + self.remaining_chars = self + .remaining_chars + .saturating_add(usize::from(self.remaining_chars > 0)) + .saturating_add(rendered_chars); + } + fn finish(mut self) -> Result { if self.total_lines == 0 { return Ok(ReadFileResult { @@ -511,6 +592,7 @@ impl ReadLineSelection { hit_total_char_limit: false, content_truncated: false, truncated_lines: Vec::new(), + remaining_chars: 0, }); } if let Some(tail_lines) = self.tail_lines.take() { @@ -520,9 +602,6 @@ impl ReadLineSelection { .saturating_add(1); for (number, line, truncated) in tail_lines { self.select(number, line, truncated); - if self.hit_total_char_limit { - break; - } } } if self.start_line > self.total_lines { @@ -546,15 +625,28 @@ impl ReadLineSelection { hit_total_char_limit: self.hit_total_char_limit, content_truncated: self.content_truncated, truncated_lines: self.truncated_lines, + remaining_chars: self.remaining_chars, }) } } +/// Character count of `format!("{line_number:>6}\t{line}")`, with the +/// `[truncated]` marker `push` appends to clipped lines. +fn rendered_line_chars(line_number: usize, line_chars: usize, truncated: bool) -> usize { + const TRUNCATED_MARKER_CHARS: usize = " [truncated]".len(); + let digits = line_number + .checked_ilog10() + .map_or(1, |log| log as usize + 1); + let number_width = digits.max(6); + number_width + 1 + line_chars + if truncated { TRUNCATED_MARKER_CHARS } else { 0 } +} + #[cfg(test)] mod tests { use super::{ - build_read_file_presentation, read_file, read_file_bytes_bounded, read_file_lines_read, - read_file_tail, read_text, read_text_tail, ReadFileResult, + build_read_file_presentation, build_read_file_presentation_with_budget, read_file, + read_file_bytes_bounded, read_file_lines_read, read_file_tail, read_text, read_text_tail, + ReadCallBudget, ReadFileResult, }; use std::fs; use std::path::PathBuf; @@ -841,6 +933,7 @@ mod tests { hit_total_char_limit: false, content_truncated: false, truncated_lines: Vec::new(), + remaining_chars: 0, }; let presentation = build_read_file_presentation("src/lib.rs", &result); @@ -852,7 +945,122 @@ mod tests { .contains("Read lines 1-2 from src/lib.rs (4 total lines)")); assert!(presentation .result_for_assistant - .contains("Use offset=3 and limit to continue reading.")); + .contains("All of it fits in one call")); + assert!(presentation + .result_for_assistant + .contains("use offset=3 without limit.")); + } + + #[test] + fn continuation_guidance_reports_remaining_lines_beyond_one_call() { + let text = format!("{}last\n", "line\n".repeat(2500)); + let result = read_text(&text, 1, 10, 50, 1000).unwrap(); + let presentation = build_read_file_presentation("big.txt", &result); + + assert_eq!(presentation.next_offset, Some(11)); + assert!(presentation + .result_for_assistant + .contains("(2491 lines remaining)")); + assert!(presentation.result_for_assistant.contains( + "Use offset=11 without limit to read up to 2000 lines and 64000 characters per call" + )); + assert!(!presentation + .result_for_assistant + .contains("fits in one call")); + } + + #[test] + fn remaining_chars_match_the_follow_up_call_output() { + let text = "one\ntwo\nabcdefgh\nfour\n"; + let first = read_text(text, 1, 1, 5, 1000).unwrap(); + let follow_up = read_text(text, 2, 10, 5, 1000).unwrap(); + + assert_eq!(first.remaining_chars, follow_up.content.chars().count()); + assert_eq!(follow_up.remaining_chars, 0); + } + + #[test] + fn remaining_chars_cover_lines_cut_by_the_character_budget() { + let text = "abcdefghij\nnext\nlast\n"; + let cut = read_text(text, 1, 10, 10, 20).unwrap(); + let follow_up = read_text(text, 2, 10, 10, 1000).unwrap(); + + assert!(cut.hit_total_char_limit); + assert_eq!(cut.end_line, 1); + assert_eq!(cut.remaining_chars, follow_up.content.chars().count()); + + let tail_cut = read_text_tail(text, 3, 10, 20).unwrap(); + assert!(tail_cut.hit_total_char_limit); + assert_eq!(tail_cut.remaining_chars, follow_up.content.chars().count()); + } + + #[test] + fn continuation_guidance_does_not_promise_one_call_when_characters_exceed_the_budget() { + let text = format!("short\n{}", format!("{}\n", "x".repeat(50)).repeat(3)); + let result = read_text(&text, 1, 1, 2000, 64_000).unwrap(); + let presentation = build_read_file_presentation_with_budget( + "wide.txt", + &result, + ReadCallBudget::new(2000, 100), + ); + + assert_eq!(presentation.next_offset, Some(2)); + assert!(result.remaining_chars > 100); + assert!(presentation + .result_for_assistant + .contains("(3 lines remaining)")); + assert!(!presentation + .result_for_assistant + .contains("fits in one call")); + assert!(presentation.result_for_assistant.contains( + "Use offset=2 without limit to read up to 2000 lines and 100 characters per call" + )); + } + + #[test] + fn continuation_guidance_uses_the_callers_budget() { + let text = "line\n".repeat(150); + let result = read_text(&text, 1, 20, 2000, 64_000).unwrap(); + + let tight = build_read_file_presentation_with_budget( + "custom.txt", + &result, + ReadCallBudget::new(100, 5000), + ); + assert!(tight.result_for_assistant.contains("(130 lines remaining)")); + assert!(tight + .result_for_assistant + .contains("read up to 100 lines and 5000 characters per call")); + + let roomy = build_read_file_presentation_with_budget( + "custom.txt", + &result, + ReadCallBudget::new(200, 5000), + ); + assert!(roomy + .result_for_assistant + .contains("All of it fits in one call: use offset=21 without limit.")); + } + + #[test] + fn continuation_guidance_after_a_character_cut_still_reports_a_fit() { + let result = read_text("abcdefghij\nnext\n", 1, 10, 10, 20).unwrap(); + let presentation = build_read_file_presentation("long.txt", &result); + + assert!(result.hit_total_char_limit); + assert_eq!(presentation.next_offset, Some(2)); + assert!(presentation.result_for_assistant.contains( + "[Output truncated after reaching the Read tool size limit (1 line remaining). All of it fits in one call" + )); + + let tight = build_read_file_presentation_with_budget( + "long.txt", + &result, + ReadCallBudget::new(2000, 10), + ); + assert!(tight + .result_for_assistant + .contains("read up to 2000 lines and 10 characters per call")); } #[test] @@ -880,6 +1088,7 @@ mod tests { hit_total_char_limit: false, content_truncated: false, truncated_lines: Vec::new(), + remaining_chars: 0, }; assert_eq!(read_file_lines_read(&result), 0);