use std::sync::Arc;
use async_trait::async_trait;
use rpi_agent::agent_tool::AgentTool;
use rpi_agent::error::AgentError;
use rpi_agent::types::{AgentToolResult, TextContentOrImage, ToolResultPartial};
use rpi_ai::types::{
ConstrainedSamplingConfig, ConstrainedStrictness, ImageContent, ImageContentType, Tool,
};
use schemars::JsonSchema;
use serde::Deserialize;
use tokio_util::sync::CancellationToken;
use crate::env::{ExecutionEnv, FileKind};
use crate::error::FileError;
use crate::file_io::{
resolve_client_path, FileIOOperation, FileIOReadRange, FileIORouter, FileIOSnapshot,
};
use crate::image::{detect_supported_image_mime_type, encode_base64};
use crate::path_utils::resolve_read_tool_path;
use crate::tools::tool_context::ExecutionToolContext;
use crate::truncate::{
format_size, truncate_head, TruncationLimit, TruncationOptions, TruncationResult,
DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES,
};
#[path = "read_preview.rs"]
mod preview;
use preview::{read_text_preview, TextPage, READ_CHUNK_BYTES};
#[derive(Debug, Clone, JsonSchema, Deserialize)]
pub struct ReadInput {
pub path: String,
#[serde(default)]
pub offset: Option<u32>,
#[serde(default)]
pub limit: Option<u32>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct ReadToolDetails {
#[serde(skip_serializing_if = "Option::is_none")]
pub truncation: Option<TruncationResult>,
}
pub struct ReadToolOptions {
pub auto_resize_images: bool,
pub image_processor: Option<Arc<dyn ReadImageProcessor>>,
}
impl Clone for ReadToolOptions {
fn clone(&self) -> Self {
Self {
auto_resize_images: self.auto_resize_images,
image_processor: self.image_processor.clone(),
}
}
}
impl std::fmt::Debug for ReadToolOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ReadToolOptions")
.field("auto_resize_images", &self.auto_resize_images)
.field("image_processor", &self.image_processor.is_some())
.finish()
}
}
impl Default for ReadToolOptions {
fn default() -> Self {
Self {
auto_resize_images: true,
image_processor: None,
}
}
}
pub trait ReadImageProcessor: Send + Sync {
fn process(
&self,
bytes: &[u8],
mime_type: &str,
auto_resize: bool,
) -> Result<ProcessedImage, String>;
}
pub struct ProcessedImage {
pub data: String,
pub mime_type: String,
pub hints: Vec<String>,
}
pub struct ReadTool {
schema: Tool,
env: Arc<dyn ExecutionEnv>,
file_io: Option<Arc<FileIORouter>>,
options: ReadToolOptions,
image_processor: Option<Arc<dyn ReadImageProcessor>>,
}
impl ReadTool {
fn schema() -> Tool {
let params = schemars::schema_for!(ReadInput);
Tool {
name: "read".to_string(),
description: format!(
"Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). \
Images are sent as attachments. For text files, output is truncated to {DEFAULT_MAX_LINES} \
lines or {kb}KB (whichever is hit first). Use offset/limit for large files. When you need \
the full file, continue with offset until complete.",
kb = DEFAULT_MAX_BYTES / 1024
),
parameters: rpi_ai::types::Schema::new(serde_json::to_value(params).unwrap_or_default()),
constrained_sampling: Some(ConstrainedSamplingConfig::JsonSchema { strict: ConstrainedStrictness::Prefer }),
}
}
}
pub fn create_read_tool(
context: &ExecutionToolContext,
options: Option<ReadToolOptions>,
) -> Arc<dyn AgentTool> {
let options = options.unwrap_or_default();
let image_processor = options.image_processor.clone();
Arc::new(ReadTool {
schema: ReadTool::schema(),
env: context.env().clone(),
file_io: context.file_io().cloned(),
options,
image_processor,
})
}
#[async_trait]
impl AgentTool for ReadTool {
fn schema(&self) -> &Tool {
&self.schema
}
fn label(&self) -> &str {
"read"
}
async fn execute(
&self,
_tool_call_id: &str,
params: serde_json::Value,
signal: CancellationToken,
_on_update: Arc<dyn Fn(ToolResultPartial) + Send + Sync>,
) -> Result<AgentToolResult, AgentError> {
let input: ReadInput = serde_json::from_value(params)
.map_err(|e| AgentError::Validation(format!("read input invalid: {e}")))?;
if let Some(router) = &self.file_io {
if let Some(client) = router
.select(FileIOOperation::Read)
.await
.map_err(|e| file_err_to_agent(e.into()))?
{
let abs = resolve_client_path(self.env.cwd(), &input.path)
.map_err(|e| file_err_to_agent(e.into()))?;
return client_text_result(&client, &abs, &input, &signal).await;
}
}
let abs = resolve_read_tool_path(&*self.env, &input.path, Some(&signal))
.await
.map_err(file_err_to_agent)?;
let local = tokio::select! {
biased;
_ = signal.cancelled() => Err(FileError::aborted().with_path(&abs)),
result = read_local(&*self.env, &abs, &input, &signal) => result,
}
.map_err(file_err_to_agent)?;
let page = match local {
LocalRead::Page(page) => page,
LocalRead::Bytes(bytes) => {
if let Some(mime) = detect_supported_image_mime_type(&bytes) {
return Ok(image_result(
mime,
&bytes,
&self.options,
self.image_processor.as_deref(),
));
}
eager_text_page(&bytes, &input)
}
};
text_result(page, &input)
}
}
enum LocalRead {
Page(TextPage),
Bytes(Vec<u8>),
}
async fn read_local(
env: &dyn ExecutionEnv,
path: &str,
input: &ReadInput,
signal: &CancellationToken,
) -> Result<LocalRead, FileError> {
let large_file = env
.file_info(path, Some(signal))
.await
.is_ok_and(|info| info.kind == FileKind::File && info.size > READ_CHUNK_BYTES as u64);
if large_file {
if let Some(file) = env.open_read_file(path).await? {
let length = file
.native_metadata()
.filter(|metadata| metadata.is_file())
.map(|metadata| metadata.len());
if let Some(length) = length.filter(|length| *length > READ_CHUNK_BYTES as u64) {
let first = file.read_range(0, READ_CHUNK_BYTES).await?;
if detect_supported_image_mime_type(&first).is_some() {
return file.read_all().await.map(LocalRead::Bytes);
}
let page = read_text_preview(&*file, length, first, input).await?;
return Ok(LocalRead::Page(page));
}
}
}
env.read_binary_file(path, Some(signal))
.await
.map(LocalRead::Bytes)
}
fn start_line(input: &ReadInput) -> usize {
input.offset.unwrap_or(1).saturating_sub(1) as usize
}
fn eager_text_page(bytes: &[u8], input: &ReadInput) -> TextPage {
let text = String::from_utf8_lossy(bytes);
let lines: Vec<_> = text.split('\n').collect();
let start = start_line(input);
let selection = lines.get(start..).unwrap_or_default();
let selected_lines = selection
.len()
.min(input.limit.map_or(usize::MAX, |limit| limit as usize));
TextPage {
truncation: truncate_head(
&selection[..selected_lines].join("\n"),
TruncationOptions::default(),
),
file_lines: lines.len(),
selected_lines,
first_line_bytes: selection.first().map_or(0, |line| line.len()),
}
}
fn text_result(page: TextPage, input: &ReadInput) -> Result<AgentToolResult, AgentError> {
let TextPage {
truncation,
file_lines,
selected_lines,
first_line_bytes,
} = page;
let start = start_line(input);
if start >= file_lines {
return Err(AgentError::Tool(format!(
"Offset {} is beyond end of file ({file_lines} lines total)",
input.offset.unwrap_or(1),
)));
}
let first = start + 1;
let (output, details) = if truncation.first_line_exceeds_limit {
(
format!(
"[Line {first} is {}, exceeds {} limit. Use bash: sed -n '{first}p' {} | head -c {DEFAULT_MAX_BYTES}]",
format_size(first_line_bytes),
format_size(DEFAULT_MAX_BYTES),
input.path,
),
Some(truncation),
)
} else if truncation.truncated {
let end = start + truncation.output_lines;
let next = end + 1;
let budget = if truncation.truncated_by == Some(TruncationLimit::Lines) {
String::new()
} else {
format!(" ({} limit)", format_size(DEFAULT_MAX_BYTES))
};
let mut output = truncation.content.clone();
output.push_str(&format!(
"\n\n[Showing lines {first}-{end} of {file_lines}{budget}. Use offset={next} to continue.]"
));
(output, Some(truncation))
} else {
let mut output = truncation.content;
let end = start + selected_lines;
if input.limit.is_some() && end < file_lines {
let remaining = file_lines - end;
let next = end + 1;
output.push_str(&format!(
"\n\n[{remaining} more lines in file. Use offset={next} to continue.]"
));
}
(output, None)
};
let details = details.map_or(serde_json::Value::Null, |truncation| {
serde_json::to_value(ReadToolDetails {
truncation: Some(truncation),
})
.unwrap_or(serde_json::Value::Null)
});
Ok(AgentToolResult {
content: vec![TextContentOrImage::text(output)],
details,
..Default::default()
})
}
async fn client_text_result(
client: &FileIOSnapshot,
absolute_path: &str,
input: &ReadInput,
signal: &CancellationToken,
) -> Result<AgentToolResult, AgentError> {
let offset = input.offset.unwrap_or(1).max(1);
let display_lines = input
.limit
.map(|n| n as usize)
.unwrap_or(DEFAULT_MAX_LINES)
.min(DEFAULT_MAX_LINES);
let text = client
.read_text(
absolute_path,
FileIOReadRange::Lines {
offset_1based: offset,
limit: display_lines as u32 + 1,
},
signal,
)
.await
.map_err(|e| file_err_to_agent(e.into()))?;
let lines = crate::truncate::split_lines_for_counting(&text);
let has_sentinel = lines.len() > display_lines;
let selected = if has_sentinel {
let selected_lines = &lines[..display_lines];
let mut selected = selected_lines.join("\n");
if selected_lines.last() == Some(&"") {
selected.push('\n');
}
selected
} else {
text
};
let truncation = truncate_head(
&selected,
TruncationOptions {
max_lines: Some(display_lines),
max_bytes: Some(DEFAULT_MAX_BYTES),
},
);
let mut output = truncation.content.clone();
if truncation.first_line_exceeds_limit {
output = format!(
"[Line {offset} exceeds {} display limit. Client text was not displayed.]",
format_size(DEFAULT_MAX_BYTES)
);
} else if has_sentinel || truncation.truncated {
let next = u64::from(offset) + truncation.output_lines as u64;
output.push_str(&format!("\n\n[More content may remain; total line count unknown. Use offset={next} to continue.]"));
}
Ok(AgentToolResult {
content: vec![TextContentOrImage::text(output)],
details: serde_json::Value::Null,
..Default::default()
})
}
fn image_result(
mime: &str,
bytes: &[u8],
options: &ReadToolOptions,
processor: Option<&dyn ReadImageProcessor>,
) -> AgentToolResult {
if let Some(proc) = processor {
match proc.process(bytes, mime, options.auto_resize_images) {
Ok(p) => {
let hints = if p.hints.is_empty() {
String::new()
} else {
format!("\n{}", p.hints.join("\n"))
};
return AgentToolResult {
content: vec![
TextContentOrImage::text(format!(
"Read image file [{}]{}",
p.mime_type, hints
)),
TextContentOrImage::Image(ImageContent {
kind: ImageContentType,
data: p.data.into(),
mime_type: p.mime_type,
}),
],
details: serde_json::Value::Null,
..Default::default()
};
}
Err(message) => {
return AgentToolResult {
content: vec![TextContentOrImage::text(format!(
"Read image file [{mime}]\n{message}"
))],
details: serde_json::Value::Null,
..Default::default()
};
}
}
}
if mime == "image/bmp" {
return AgentToolResult {
content: vec![TextContentOrImage::text(
"Read image file [image/bmp]\n[Image omitted: configure an imageProcessor to convert BMP images.]",
)],
details: serde_json::Value::Null,
..Default::default()
};
}
AgentToolResult {
content: vec![
TextContentOrImage::text(format!("Read image file [{mime}]")),
TextContentOrImage::Image(ImageContent {
kind: ImageContentType,
data: encode_base64(bytes).into(),
mime_type: mime.to_string(),
}),
],
details: serde_json::Value::Null,
..Default::default()
}
}
fn file_err_to_agent(e: crate::error::FileError) -> AgentError {
AgentError::Tool(e.to_string())
}