opi_coding_agent/tool/
read.rs1use std::future::Future;
2use std::path::PathBuf;
3use std::pin::Pin;
4
5use opi_agent::tool::{ExecutionMode, Tool, ToolError, ToolResult};
6use opi_ai::message::{OutputContent, ToolDef};
7use schemars::JsonSchema;
8use serde::Deserialize;
9use tokio_util::sync::CancellationToken;
10
11#[derive(Debug, Deserialize, JsonSchema)]
12pub struct ReadArgs {
13 pub path: String,
15 pub offset: Option<usize>,
17 pub limit: Option<usize>,
19}
20
21pub struct ReadTool {
22 workspace_root: PathBuf,
23 schema: serde_json::Value,
24}
25
26impl ReadTool {
27 pub fn new(workspace_root: PathBuf) -> Self {
28 let schema = schemars::schema_for!(ReadArgs);
29 Self {
30 workspace_root,
31 schema: serde_json::to_value(&schema).unwrap_or_default(),
32 }
33 }
34}
35
36impl Tool for ReadTool {
37 fn definition(&self) -> ToolDef {
38 ToolDef {
39 name: "read".into(),
40 description: "Read file content with optional line range.".into(),
41 input_schema: self.schema.clone(),
42 }
43 }
44
45 fn execute(
46 &self,
47 _call_id: &str,
48 arguments: serde_json::Value,
49 _signal: CancellationToken,
50 _on_update: Option<opi_agent::tool::UpdateCallback>,
51 ) -> Pin<Box<dyn Future<Output = Result<ToolResult, ToolError>> + Send>> {
52 let args: ReadArgs = match serde_json::from_value(arguments) {
53 Ok(a) => a,
54 Err(e) => {
55 return Box::pin(async move {
56 Ok(ToolResult {
57 content: vec![OutputContent::Text {
58 text: format!("invalid arguments: {e}"),
59 }],
60 details: None,
61 is_error: true,
62 terminate: false,
63 })
64 });
65 }
66 };
67 let file_path = self.workspace_root.join(&args.path);
68 let workspace_root = self.workspace_root.clone();
69 Box::pin(async move {
70 let content = match tokio::fs::read_to_string(&file_path).await {
71 Ok(c) => c,
72 Err(e) => {
73 return Ok(ToolResult {
74 content: vec![OutputContent::Text {
75 text: format!("failed to read {}: {e}", file_path.display()),
76 }],
77 details: None,
78 is_error: true,
79 terminate: false,
80 });
81 }
82 };
83
84 let lines: Vec<&str> = content.lines().collect();
85 let offset = args.offset.unwrap_or(1).saturating_sub(1);
86 let offset = offset.min(lines.len());
87 let selected: Vec<&str> = if let Some(limit) = args.limit {
88 lines[offset..].iter().take(limit).copied().collect()
89 } else {
90 lines[offset..].to_vec()
91 };
92
93 let output = selected.join("\n");
94 let inside_workspace = std::fs::canonicalize(&file_path)
95 .ok()
96 .and_then(|cp| {
97 std::fs::canonicalize(&workspace_root)
98 .ok()
99 .map(|cr| cp.starts_with(&cr))
100 })
101 .unwrap_or(false);
102 let details = serde_json::json!({
103 "workspace_root": workspace_root.to_string_lossy(),
104 "path": args.path,
105 "inside_workspace": inside_workspace,
106 });
107
108 let text = format!("{}\n{}", file_path.display(), output);
109
110 Ok(ToolResult {
111 content: vec![OutputContent::Text { text }],
112 details: Some(details),
113 is_error: false,
114 terminate: false,
115 })
116 })
117 }
118
119 fn execution_mode(&self) -> ExecutionMode {
120 ExecutionMode::Parallel
121 }
122}