@@ -4,6 +4,24 @@ use std::fs;
44use std:: path:: { Path , PathBuf } ;
55
66const MAX_FILE_SIZE : u64 = 50 * 1024 * 1024 ; // 50MB limit
7+ const MAX_TOOL_OUTPUT_TOKENS : usize = 8_000 ; // ~28KB, prevents excessive context usage
8+
9+ /// Truncate file content if it exceeds token limit for context efficiency
10+ fn truncate_for_context ( content : & str , max_tokens : usize ) -> String {
11+ let estimated_tokens = content. len ( ) / 4 ;
12+ if estimated_tokens > max_tokens {
13+ let truncate_at = max_tokens * 4 ;
14+ let truncated_content = & content[ ..truncate_at. min ( content. len ( ) ) ] ;
15+ format ! (
16+ "{}...\n \n [TRUNCATED: File has ~{} tokens, showing first ~{} tokens. Use search_code or request specific line ranges if you need more.]" ,
17+ truncated_content,
18+ estimated_tokens,
19+ max_tokens
20+ )
21+ } else {
22+ content. to_string ( )
23+ }
24+ }
725
826/// FileSystemTool provides secure file operations sandboxed to a workspace directory
927#[ derive( Clone ) ]
@@ -87,8 +105,10 @@ impl FileSystemTool {
87105 ) ) ) ;
88106 }
89107
90- fs:: read_to_string ( & validated_path)
91- . with_context ( || format ! ( "Failed to read file: {}" , path) )
108+ let content = fs:: read_to_string ( & validated_path)
109+ . with_context ( || format ! ( "Failed to read file: {}" , path) ) ?;
110+
111+ Ok ( truncate_for_context ( & content, MAX_TOOL_OUTPUT_TOKENS ) )
92112 }
93113
94114 /// Read a file that may be outside the workspace
@@ -123,7 +143,10 @@ impl FileSystemTool {
123143 ) ) ) ;
124144 }
125145
126- fs:: read_to_string ( & canonical) . with_context ( || format ! ( "Failed to read file: {}" , original) )
146+ let content = fs:: read_to_string ( & canonical)
147+ . with_context ( || format ! ( "Failed to read file: {}" , original) ) ?;
148+
149+ Ok ( truncate_for_context ( & content, MAX_TOOL_OUTPUT_TOKENS ) )
127150 }
128151
129152 pub fn write_file ( & self , path : & str , content : & str ) -> Result < ( ) > {
0 commit comments