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 = self.workspace_root.join(&args.path);
66        let workspace_root = self.workspace_root.clone();
67        Box::pin(async move {
68            // Create parent directories if needed
69            if let Some(parent) = file_path.parent()
70                && let Err(e) = tokio::fs::create_dir_all(parent).await
71            {
72                return Ok(ToolResult {
73                    content: vec![OutputContent::Text {
74                        text: format!("failed to create directories: {e}"),
75                    }],
76                    details: None,
77                    is_error: true,
78                    terminate: false,
79                });
80            }
81
82            if let Err(e) = tokio::fs::write(&file_path, &args.content).await {
83                return Ok(ToolResult {
84                    content: vec![OutputContent::Text {
85                        text: format!("failed to write {}: {e}", file_path.display()),
86                    }],
87                    details: None,
88                    is_error: true,
89                    terminate: false,
90                });
91            }
92
93            let inside = file_path.starts_with(&workspace_root);
94            let details = serde_json::json!({
95                "workspace_root": workspace_root.to_string_lossy(),
96                "path": args.path,
97                "inside_workspace": inside,
98            });
99
100            Ok(ToolResult {
101                content: vec![OutputContent::Text {
102                    text: format!("wrote {}", args.path),
103                }],
104                details: Some(details),
105                is_error: false,
106                terminate: false,
107            })
108        })
109    }
110
111    fn execution_mode(&self) -> ExecutionMode {
112        ExecutionMode::Sequential
113    }
114}