Skip to main content

tea_coding_tools/
write.rs

1use std::str::FromStr;
2
3use futures_util::stream;
4use serde_json::json;
5use tea_control::CancellationScope;
6use tea_protocol::ToolIdempotency;
7use tea_tools::{
8    BoxToolExecutionStream, ToolConcurrency, ToolEffect, ToolExecutionEvent,
9    ToolExecutionSemantics, ToolExecutor, ToolName, ToolRetrySafety, ToolSpec, ToolSpecError,
10    ToolTimeout, ToolVersion, ValidatedToolInvocation,
11};
12
13use crate::edit_diff::code_change;
14use crate::file::{atomic_write, atomic_write_if_unchanged, read_utf8};
15use crate::output::{failure, success};
16use crate::read::string_argument;
17use crate::{FileToolError, FileToolErrorCode, WorkspaceRoot};
18
19/// Workspace-confined atomic UTF-8 file writer.
20#[derive(Debug, Clone)]
21pub struct WriteTool {
22    workspace: WorkspaceRoot,
23}
24
25impl WriteTool {
26    /// Creates a writer bound to one validated workspace capability.
27    #[must_use]
28    pub const fn new(workspace: WorkspaceRoot) -> Self {
29        Self { workspace }
30    }
31
32    /// Builds the portable `write` tool contract.
33    ///
34    /// # Errors
35    ///
36    /// Returns an error only if the static contract violates tool bounds.
37    pub fn spec() -> Result<ToolSpec, ToolSpecError> {
38        ToolSpec::new(
39            ToolName::from_str("write").map_err(|_| ToolSpecError::InvalidDescription)?,
40            ToolVersion::from_str("1.0.0").map_err(|_| ToolSpecError::InvalidDescription)?,
41            "Atomically create or replace one workspace UTF-8 text file.",
42            json!({
43                "type":"object",
44                "properties":{
45                    "path":{"type":"string","minLength":1,"maxLength":4096},
46                    "content":{"type":"string","maxLength":crate::MAX_WRITE_BYTES}
47                },
48                "required":["path","content"],
49                "additionalProperties":false
50            }),
51            json!({
52                "type":"object",
53                "properties":{
54                    "path":{"type":"string"},
55                    "writtenBytes":{"type":"integer","minimum":0},
56                    "created":{"type":"boolean"}
57                },
58                "required":["path","writtenBytes","created"],
59                "additionalProperties":false
60            }),
61            [ToolEffect::FsWrite],
62            ToolExecutionSemantics::new(
63                ToolIdempotency::Idempotent,
64                ToolRetrySafety::ExplicitOnly,
65                ToolConcurrency::Serial,
66                ToolTimeout::from_millis(30_000)?,
67            )?,
68        )?
69        .with_prompt_hint("Use write for complete UTF-8 file content and workspace-relative paths.")
70    }
71
72    fn run(
73        &self,
74        invocation: &ValidatedToolInvocation,
75    ) -> Result<ToolExecutionEvent, FileToolError> {
76        let path = string_argument(invocation, "path")?;
77        let content = string_argument(invocation, "content")?;
78        if content.len() > crate::MAX_WRITE_BYTES {
79            return Err(FileToolError::new(FileToolErrorCode::TooLarge));
80        }
81        let target = self.workspace.resolve_mutation(path)?;
82        let created = !target.target_existed_at_resolution();
83        let existing_text = if created {
84            None
85        } else {
86            let existing = self.workspace.resolve_existing(path)?;
87            match read_utf8(&self.workspace, &existing, crate::MAX_WRITE_BYTES) {
88                Ok(source) => Some((existing, source)),
89                Err(error)
90                    if matches!(
91                        error.code(),
92                        FileToolErrorCode::BinaryFile
93                            | FileToolErrorCode::InvalidUtf8
94                            | FileToolErrorCode::TooLarge
95                    ) =>
96                {
97                    None
98                }
99                Err(error) => return Err(error),
100            }
101        };
102        let change = match existing_text.as_ref() {
103            Some((existing, source)) => Some(code_change(
104                existing.display_path(),
105                source,
106                content,
107                tea_protocol::CodeChangeKind::Update,
108            )?),
109            None if created => Some(code_change(
110                target.display_path(),
111                "",
112                content,
113                tea_protocol::CodeChangeKind::Create,
114            )?),
115            None => None,
116        };
117        if let Some((existing, source)) = existing_text.as_ref() {
118            atomic_write_if_unchanged(
119                &self.workspace,
120                existing,
121                &target,
122                source,
123                content.as_bytes(),
124            )?;
125        } else {
126            atomic_write(&self.workspace, &target, content.as_bytes())?;
127        }
128        let event = success(
129            format!("wrote {} bytes to {}", content.len(), target.display_path()),
130            json!({
131                "path":target.display_path(),
132                "writtenBytes":content.len(),
133                "created":created
134            }),
135        );
136        let ToolExecutionEvent::Finished(result) = event else {
137            return Err(FileToolError::new(FileToolErrorCode::Internal));
138        };
139        let result = match change {
140            Some(change) => {
141                result.with_presentation(tea_protocol::ToolPresentation::CodeChange(change))
142            }
143            None => result,
144        };
145        Ok(ToolExecutionEvent::Finished(result))
146    }
147
148    fn preview_change(
149        &self,
150        invocation: &ValidatedToolInvocation,
151    ) -> Result<tea_protocol::CodeChange, FileToolError> {
152        let path = string_argument(invocation, "path")?;
153        let content = string_argument(invocation, "content")?;
154        if content.len() > crate::MAX_WRITE_BYTES {
155            return Err(FileToolError::new(FileToolErrorCode::TooLarge));
156        }
157        let target = self.workspace.resolve_mutation(path)?;
158        if !target.target_existed_at_resolution() {
159            return code_change(
160                target.display_path(),
161                "",
162                content,
163                tea_protocol::CodeChangeKind::Create,
164            );
165        }
166        let existing = self.workspace.resolve_existing(path)?;
167        let source = read_utf8(&self.workspace, &existing, crate::MAX_WRITE_BYTES)?;
168        code_change(
169            existing.display_path(),
170            &source,
171            content,
172            tea_protocol::CodeChangeKind::Update,
173        )
174    }
175}
176
177impl ToolExecutor for WriteTool {
178    fn preview(
179        &self,
180        invocation: &ValidatedToolInvocation,
181    ) -> Option<tea_protocol::ToolPresentation> {
182        self.preview_change(invocation)
183            .ok()
184            .map(tea_protocol::ToolPresentation::CodeChange)
185    }
186
187    fn execute(
188        &self,
189        invocation: ValidatedToolInvocation,
190        cancellation: CancellationScope,
191    ) -> BoxToolExecutionStream {
192        let executor = self.clone();
193        Box::pin(stream::once(async move {
194            if cancellation.is_cancelled() {
195                ToolExecutionEvent::Failed(tea_tools::ToolExecutionFailure::cancelled())
196            } else {
197                executor.run(&invocation).unwrap_or_else(failure)
198            }
199        }))
200    }
201}