adk_devtools/tools/
write.rs1use 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
14pub struct WriteFileTool {
36 workspace: Workspace,
37}
38
39impl WriteFileTool {
40 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 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 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}