Skip to main content

adk_devtools/tools/
write.rs

1//! `write_file` — create or overwrite a file in the workspace.
2
3use std::sync::Arc;
4
5use adk_core::{Result, Tool, ToolContext};
6use async_trait::async_trait;
7use serde_json::{Value, json};
8
9use crate::error::DevToolError;
10use crate::read_ledger::sha256_hex;
11use crate::tools::read::require_str;
12use crate::workspace::{Precondition, Workspace};
13
14/// Creates or overwrites a file (creating parent directories as needed).
15///
16/// With `expect_sha256` the write happens only when the file's current sha256 is that
17/// digest, or, given `absent`, only when no file exists yet; otherwise it is answered
18/// `devtools.stale` and nothing is written (spec 3.1 §7.26, I66). The digest of what was
19/// written becomes this session and agent's read record, so a following `edit_file`
20/// needs no read.
21///
22/// On Unix the parent directory is opened by descriptor and the file relative to it,
23/// without following a symlink on any component of the target the containment check
24/// resolved, and the precondition is read through the same descriptor (spec 3.1 §10 D4).
25///
26/// # Example
27///
28/// ```rust
29/// use adk_core::Tool;
30/// use adk_devtools::{Workspace, WriteFileTool};
31///
32/// let tool = WriteFileTool::new(Workspace::new("./my-repo"));
33/// assert!(tool.parameters_schema().unwrap()["properties"]["expect_sha256"].is_object());
34/// ```
35pub struct WriteFileTool {
36    workspace: Workspace,
37}
38
39impl WriteFileTool {
40    /// Create a `write_file` tool bound to `workspace`.
41    pub fn new(workspace: Workspace) -> Self {
42        Self { workspace }
43    }
44}
45
46#[async_trait]
47impl Tool for WriteFileTool {
48    fn name(&self) -> &str {
49        "write_file"
50    }
51
52    /// Writes the workspace on disk.
53    fn egress(&self, _args: &serde_json::Value) -> adk_core::egress::ToolEgress {
54        adk_core::egress::ToolEgress::None
55    }
56
57    fn description(&self) -> &str {
58        "Create a new file or overwrite an existing one with the given content. \
59         Parent directories are created automatically."
60    }
61
62    fn parameters_schema(&self) -> Option<Value> {
63        Some(json!({
64            "type": "object",
65            "properties": {
66                "path": { "type": "string", "description": "Path relative to the workspace root." },
67                "content": { "type": "string", "description": "The full file content to write." },
68                "expect_sha256": { "type": "string", "description": "Optional: the sha256 the file must have, or \"absent\" when it must not exist yet; the write is refused otherwise." }
69            },
70            "required": ["path", "content"]
71        }))
72    }
73
74    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
75        if !self.workspace.is_writable() {
76            return Err(DevToolError::ReadOnly("write_file").into());
77        }
78        let path = require_str(&args, "path")?;
79        let content = require_str(&args, "content")?;
80        let precondition = match args.get("expect_sha256").and_then(Value::as_str) {
81            Some(expect) => Precondition::from_expect(expect)?,
82            None => Precondition::Any,
83        };
84        let (resolved, target) = self.workspace.resolve_target(&path)?;
85        self.workspace.write_contained(&target, content.as_bytes(), precondition).await?;
86        // A freshly-written file is considered "read" (its content is known).
87        self.workspace
88            .record_digest(ctx.as_ref(), &resolved, &sha256_hex(content.as_bytes()))
89            .await;
90
91        Ok(json!({
92            "path": self.workspace.display(&resolved),
93            "bytes_written": content.len(),
94            "message": format!("Wrote {} bytes to {}", content.len(), self.workspace.display(&resolved)),
95        }))
96    }
97}