Skip to main content

opi_coding_agent/tool/
write.rs

1use 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 WriteArgs {
13    /// Relative path within workspace to write.
14    pub path: String,
15    /// Content to write.
16    pub content: String,
17}
18
19pub struct WriteTool {
20    workspace_root: PathBuf,
21    schema: serde_json::Value,
22}
23
24impl WriteTool {
25    pub fn new(workspace_root: PathBuf) -> Self {
26        let schema = schemars::schema_for!(WriteArgs);
27        Self {
28            workspace_root,
29            schema: serde_json::to_value(&schema).unwrap_or_default(),
30        }
31    }
32}
33
34impl Tool for WriteTool {
35    fn definition(&self) -> ToolDef {
36        ToolDef {
37            name: "write".into(),
38            description: "Create or replace a file with the given content.".into(),
39            input_schema: self.schema.clone(),
40        }
41    }
42
43    fn execute(
44        &self,
45        _call_id: &str,
46        arguments: serde_json::Value,
47        _signal: CancellationToken,
48        _on_update: Option<opi_agent::tool::UpdateCallback>,
49    ) -> Pin<Box<dyn Future<Output = Result<ToolResult, ToolError>> + Send>> {
50        let args: WriteArgs = match serde_json::from_value(arguments) {
51            Ok(a) => a,
52            Err(e) => {
53                return Box::pin(async move {
54                    Ok(ToolResult {
55                        content: vec![OutputContent::Text {
56                            text: format!("invalid arguments: {e}"),
57                        }],
58                        details: None,
59                        is_error: true,
60                        terminate: false,
61                    })
62                });
63            }
64        };
65        let file_path = match super::validate_workspace_path(&self.workspace_root, &args.path) {
66            Ok(p) => p,
67            Err(msg) => {
68                return Box::pin(async move {
69                    Ok(ToolResult {
70                        content: vec![OutputContent::Text { text: msg }],
71                        details: None,
72                        is_error: true,
73                        terminate: false,
74                    })
75                });
76            }
77        };
78        let workspace_root = self.workspace_root.clone();
79        let path_for_display = args.path.clone();
80        Box::pin(async move {
81            // Create parent directories if needed
82            if let Some(parent) = file_path.parent()
83                && let Err(e) = tokio::fs::create_dir_all(parent).await
84            {
85                return Ok(ToolResult {
86                    content: vec![OutputContent::Text {
87                        text: format!("failed to create directories: {e}"),
88                    }],
89                    details: None,
90                    is_error: true,
91                    terminate: false,
92                });
93            }
94
95            if let Err(e) = tokio::fs::write(&file_path, &args.content).await {
96                return Ok(ToolResult {
97                    content: vec![OutputContent::Text {
98                        text: format!("failed to write {}: {e}", file_path.display()),
99                    }],
100                    details: None,
101                    is_error: true,
102                    terminate: false,
103                });
104            }
105
106            let details = serde_json::json!({
107                "workspace_root": workspace_root.to_string_lossy(),
108                "path": path_for_display,
109            });
110
111            Ok(ToolResult {
112                content: vec![OutputContent::Text {
113                    text: format!("wrote {}", path_for_display),
114                }],
115                details: Some(details),
116                is_error: false,
117                terminate: false,
118            })
119        })
120    }
121
122    fn execution_mode(&self) -> ExecutionMode {
123        ExecutionMode::Sequential
124    }
125}