返回 CodeWhale
fim.rs
根目录 / crates / engine / src / tools / fim.rs
1 //! FIM (Fill-in-the-Middle) edit tool.
2 //!
3 //! Reads a file, finds `prefix_anchor` and `suffix_anchor`, calls the active
4 //! route's `/beta/completions` FIM endpoint, and writes the generated middle
5 //! content back into the file. The URL is built from the session's own base URL
6 //! (`crates/engine/src/client.rs:3484`), so this works on any ChatCompletions
7 //! provider — it is not DeepSeek-specific.
8
9 use async_trait::async_trait;
10 use serde_json::{Value, json};
11 use thiserror::Error;
12
13 use crate::client::CodewhaleClient;
14
15 use super::spec::{
16 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
17 optional_u64, required_str,
18 };
19
20 /// Result of a FIM edit operation
21 #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
22 pub struct FimEditResult {
23 pub success: bool,
24 pub path: String,
25 pub generated_text: String,
26 pub prefix_end: usize,
27 pub suffix_start: usize,
28 pub message: String,
29 }
30
31 /// Tool for performing Fill-in-the-Middle edits via the active route's FIM API.
32 /// (`CodewhaleClient` is the historical name of the shared provider client; it is
33 /// not a DeepSeek-only type.)
34 pub struct FimEditTool {
35 pub client: Option<CodewhaleClient>,
36 pub model: String,
37 }
38
39 impl FimEditTool {
40 #[must_use]
41 pub fn new(client: Option<CodewhaleClient>, model: String) -> Self {
42 Self { client, model }
43 }
44 }
45
46 // === Errors ===
47
48 #[derive(Debug, Error)]
49 enum FimError {
50 #[error("Prefix anchor not found in file: '{0}'")]
51 PrefixNotFound(String),
52 #[error("Suffix anchor not found after prefix anchor: '{0}'")]
53 SuffixNotFound(String),
54 #[error("Prefix and suffix anchors overlap (suffix starts at {0}, prefix ends at {1})")]
55 AnchorsOverlap(usize, usize),
56 #[error("FIM API call failed: {0}")]
57 ApiFailed(String),
58 }
59
60 #[async_trait]
61 impl ToolSpec for FimEditTool {
62 fn name(&self) -> &'static str {
63 "fim_edit"
64 }
65
66 fn description(&self) -> &'static str {
67 "Edit a file using Fill-in-the-Middle (FIM) completion. Provide a file path, \
68 prefix_anchor (text that appears before the section to replace), and \
69 suffix_anchor (text that appears after the section to replace). The tool \
70 calls the active route's fill-in-the-middle completion endpoint to \
71 generate replacement content."
72 }
73
74 fn input_schema(&self) -> Value {
75 json!({
76 "type": "object",
77 "properties": {
78 "path": {
79 "type": "string",
80 "description": "Path to the file to edit (relative to workspace)"
81 },
82 "prefix_anchor": {
83 "type": "string",
84 "description": "Text anchor marking the end of the prefix. Everything up to and including this anchor is kept as-is before the generated middle."
85 },
86 "suffix_anchor": {
87 "type": "string",
88 "description": "Text anchor marking the start of the suffix. Everything from this anchor onward is kept as-is after the generated middle."
89 },
90 "max_tokens": {
91 "type": "integer",
92 "description": "Maximum tokens to generate (default: 1024)"
93 }
94 },
95 "required": ["path", "prefix_anchor", "suffix_anchor"]
96 })
97 }
98
99 fn capabilities(&self) -> Vec<ToolCapability> {
100 vec![
101 ToolCapability::WritesFiles,
102 ToolCapability::RequiresApproval,
103 ]
104 }
105
106 fn approval_requirement(&self) -> ApprovalRequirement {
107 ApprovalRequirement::Suggest
108 }
109
110 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
111 let path = required_str(&input, "path")?;
112 let prefix_anchor = required_str(&input, "prefix_anchor")?;
113 let suffix_anchor = required_str(&input, "suffix_anchor")?;
114 let max_tokens = optional_u64(&input, "max_tokens", 1024)?;
115
116 let plan =
117 crate::tools::file::resolve_read_open_plan(context, path, "fim_edit", false, false)
118 .await?;
119 let resolved = plan.file_path.clone();
120 let (content_bytes, _fd_path) = crate::tools::file::open_and_read_verified_bytes(
121 plan.clone(),
122 None,
123 false,
124 "Failed to read",
125 )
126 .await?
127 .ok_or_else(|| {
128 ToolError::execution_failed(format!(
129 "Failed to read {}: file not found",
130 resolved.display()
131 ))
132 })?;
133 let content = String::from_utf8(content_bytes).map_err(|e| {
134 ToolError::execution_failed(format!("Failed to read {}: {}", resolved.display(), e))
135 })?;
136
137 // 2. Find prefix anchor
138 let prefix_pos = content.find(prefix_anchor).ok_or_else(|| {
139 ToolError::execution_failed(
140 FimError::PrefixNotFound(prefix_anchor.to_string()).to_string(),
141 )
142 })?;
143 let prefix_end = prefix_pos + prefix_anchor.len();
144
145 // 3. Find suffix anchor (after prefix anchor)
146 let suffix_pos = content[prefix_end..].find(suffix_anchor).ok_or_else(|| {
147 ToolError::execution_failed(
148 FimError::SuffixNotFound(suffix_anchor.to_string()).to_string(),
149 )
150 })?;
151 let suffix_start = prefix_end + suffix_pos;
152
153 // 4. Validate anchors don't overlap
154 if suffix_start < prefix_end {
155 return Err(ToolError::execution_failed(
156 FimError::AnchorsOverlap(suffix_start, prefix_end).to_string(),
157 ));
158 }
159
160 // 5. Extract prefix and suffix for the FIM API
161 let fim_prompt = content[..prefix_end].to_string();
162 let fim_suffix = content[suffix_start..].to_string();
163
164 // 6. Call FIM API
165 let generated_text = match self.client.as_ref() {
166 Some(client) => client
167 .fim_completion(&self.model, &fim_prompt, &fim_suffix, max_tokens as u32)
168 .await
169 .map_err(|e| {
170 ToolError::execution_failed(FimError::ApiFailed(e.to_string()).to_string())
171 })?,
172 None => {
173 return Err(ToolError::execution_failed(
174 "FIM API client not available".to_string(),
175 ));
176 }
177 };
178
179 let (current_bytes, _fd_path) =
180 crate::tools::file::open_and_read_verified_bytes(plan, None, true, "Failed to re-read")
181 .await?
182 .ok_or_else(|| {
183 ToolError::execution_failed(format!(
184 "Failed to re-read {}: file not found",
185 resolved.display()
186 ))
187 })?;
188 let current = String::from_utf8(current_bytes).map_err(|e| {
189 ToolError::execution_failed(format!("Failed to re-read {}: {}", resolved.display(), e))
190 })?;
191 if current != content {
192 return Err(ToolError::execution_failed(format!(
193 "Refusing fim_edit for {path}: the file changed while the FIM completion was running. Nothing was written. Recovery: read the file again and retry."
194 )));
195 }
196
197 // 7. Build the new content and write it back
198 let generated_len = generated_text.len();
199 let new_content = format!("{fim_prompt}{generated_text}{fim_suffix}");
200 super::syntax_check::guard_edit(&resolved, path, Some(&content), &new_content)?;
201 // Deliberately not rustfmt-normalized (#6205): this result reports
202 // `prefix_end`/`suffix_start` as byte offsets into the written file,
203 // and reformatting would move them. The syntax gate applies; the
204 // formatting normalization does not.
205 codewhale_util::utils::write_atomic_workspace(&resolved, new_content.as_bytes()).map_err(
206 |e| {
207 ToolError::execution_failed(format!(
208 "Failed to write {}: {}",
209 resolved.display(),
210 e
211 ))
212 },
213 )?;
214 context.note_file_read(&resolved);
215
216 let result = FimEditResult {
217 success: true,
218 path: path.to_string(),
219 generated_text,
220 prefix_end,
221 suffix_start,
222 message: format!(
223 "FIM edit applied to `{path}`. Generated {generated_len} chars between prefix_anchor end (byte {prefix_end}) and suffix_anchor start (byte {suffix_start}).",
224 ),
225 };
226
227 ToolResult::json(&result).map_err(|e| ToolError::execution_failed(e.to_string()))
228 }
229 }
230
231 #[cfg(test)]
232 mod tests {
233 use super::*;
234
235 #[test]
236 fn fim_edit_is_write_capable_but_not_read_only() {
237 let tool = FimEditTool::new(None, "fim-model".to_string());
238 let capabilities = tool.capabilities();
239
240 assert!(capabilities.contains(&ToolCapability::WritesFiles));
241 assert!(!capabilities.contains(&ToolCapability::ReadOnly));
242 assert!(!tool.is_read_only());
243 }
244
245 #[tokio::test]
246 async fn fim_edit_refuses_read_only_root_and_outside_hardlink() {
247 let workspace = tempfile::tempdir().expect("workspace");
248 let ro_root = tempfile::tempdir().expect("read-only root");
249 let ro_file = ro_root.path().join("sample.rs");
250 std::fs::write(&ro_file, "fn a() {}\nfn b() {}\n").expect("write ro");
251 let ro_canon = ro_root.path().canonicalize().expect("canon ro");
252 let ctx = ToolContext::new(workspace.path()).with_read_only_roots(vec![ro_canon]);
253 let tool = FimEditTool::new(None, "fim-model".to_string());
254
255 let ro_err = tool
256 .execute(
257 json!({
258 "path": ro_file.to_string_lossy(),
259 "prefix_anchor": "fn a()",
260 "suffix_anchor": "fn b()",
261 }),
262 &ctx,
263 )
264 .await
265 .expect_err("fim_edit must never read from read_only_roots");
266 assert!(matches!(ro_err, ToolError::PathEscape { .. }), "{ro_err:?}");
267
268 #[cfg(unix)]
269 {
270 let outside = tempfile::tempdir().expect("outside");
271 let original = outside.path().join("orig.rs");
272 let linked = outside.path().join("alias.rs");
273 std::fs::write(&original, "fn a() {}\nfn b() {}\n").expect("write orig");
274 std::fs::hard_link(&original, &linked).expect("hardlink");
275 let trusted_ctx = ToolContext::new(workspace.path()).with_trust_mode(true);
276 let link_err = tool
277 .execute(
278 json!({
279 "path": linked.to_string_lossy(),
280 "prefix_anchor": "fn a()",
281 "suffix_anchor": "fn b()",
282 }),
283 &trusted_ctx,
284 )
285 .await
286 .expect_err("outside hardlink must be refused by verified-handle reader");
287 assert!(
288 matches!(link_err, ToolError::PermissionDenied { .. }),
289 "{link_err:?}"
290 );
291 }
292 }
293 }
294
294 lines RUST