use std::sync::Arc;
use adk_core::{Result, Tool, ToolContext};
use async_trait::async_trait;
use serde_json::{Value, json};
use crate::error::DevToolError;
use crate::read_ledger::sha256_hex;
use crate::tools::read::require_str;
use crate::workspace::{Precondition, Workspace};
pub struct WriteFileTool {
workspace: Workspace,
}
impl WriteFileTool {
pub fn new(workspace: Workspace) -> Self {
Self { workspace }
}
}
#[async_trait]
impl Tool for WriteFileTool {
fn name(&self) -> &str {
"write_file"
}
fn egress(&self, _args: &serde_json::Value) -> adk_core::egress::ToolEgress {
adk_core::egress::ToolEgress::None
}
fn description(&self) -> &str {
"Create a new file or overwrite an existing one with the given content. \
Parent directories are created automatically."
}
fn parameters_schema(&self) -> Option<Value> {
Some(json!({
"type": "object",
"properties": {
"path": { "type": "string", "description": "Path relative to the workspace root." },
"content": { "type": "string", "description": "The full file content to write." },
"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." }
},
"required": ["path", "content"]
}))
}
async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
if !self.workspace.is_writable() {
return Err(DevToolError::ReadOnly("write_file").into());
}
let path = require_str(&args, "path")?;
let content = require_str(&args, "content")?;
let precondition = match args.get("expect_sha256").and_then(Value::as_str) {
Some(expect) => Precondition::from_expect(expect)?,
None => Precondition::Any,
};
let (resolved, target) = self.workspace.resolve_target(&path)?;
self.workspace.write_contained(&target, content.as_bytes(), precondition).await?;
self.workspace
.record_digest(ctx.as_ref(), &resolved, &sha256_hex(content.as_bytes()))
.await;
Ok(json!({
"path": self.workspace.display(&resolved),
"bytes_written": content.len(),
"message": format!("Wrote {} bytes to {}", content.len(), self.workspace.display(&resolved)),
}))
}
}