argentor-builtins 1.4.7

50+ built-in skills (web search, crypto, file ops, security, data processing) for Argentor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use argentor_core::{ArgentorError, ArgentorResult, ToolCall, ToolResult};
use argentor_security::{Capability, PermissionSet};
use argentor_skills::skill::{Skill, SkillDescriptor};
use async_trait::async_trait;
use std::path::Path;
use tracing::info;

const MAX_WRITE_SIZE: usize = 10 * 1024 * 1024; // 10MB

/// File writing skill. Writes content to files with path validation.
pub struct FileWriteSkill {
    descriptor: SkillDescriptor,
}

impl FileWriteSkill {
    /// Create a new file write skill.
    pub fn new() -> Self {
        Self {
            descriptor: SkillDescriptor {
                name: "file_write".to_string(),
                description: "Write content to a file. Path must be within allowed directories."
                    .to_string(),
                parameters_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "Absolute path to the file to write"
                        },
                        "content": {
                            "type": "string",
                            "description": "Content to write to the file"
                        },
                        "append": {
                            "type": "boolean",
                            "description": "Append to file instead of overwriting (default: false)"
                        },
                        "create_dirs": {
                            "type": "boolean",
                            "description": "Create parent directories if they don't exist (default: false)"
                        }
                    },
                    "required": ["path", "content"]
                }),
                required_capabilities: vec![Capability::FileWrite {
                    allowed_paths: vec![], // Configured at runtime
                }],
                requires_approval: false,
            },
        }
    }
}

impl Default for FileWriteSkill {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Skill for FileWriteSkill {
    fn descriptor(&self) -> &SkillDescriptor {
        &self.descriptor
    }

    fn validate_arguments(
        &self,
        call: &ToolCall,
        permissions: &PermissionSet,
    ) -> ArgentorResult<()> {
        let path_str = call.arguments["path"].as_str().unwrap_or_default();
        if path_str.is_empty() {
            return Ok(()); // Empty path will be caught in execute()
        }

        let path = Path::new(path_str);

        // For writes the file may not exist yet, so canonicalize the parent directory.
        let canonical = if path.exists() {
            match path.canonicalize() {
                Ok(p) => p,
                Err(_) => return Ok(()), // Let execute() handle the error
            }
        } else if let Some(parent) = path.parent() {
            if parent.exists() {
                match parent.canonicalize() {
                    Ok(p) => p.join(path.file_name().unwrap_or_default()),
                    Err(_) => return Ok(()),
                }
            } else {
                // Parent doesn't exist either — use the path as-is for the check.
                // This may happen with create_dirs=true.
                path.to_path_buf()
            }
        } else {
            return Ok(());
        };

        if !permissions.check_file_write_path(&canonical) {
            return Err(ArgentorError::Security(format!(
                "file write not permitted for path '{}'",
                canonical.display()
            )));
        }

        Ok(())
    }

    async fn execute(&self, call: ToolCall) -> ArgentorResult<ToolResult> {
        let path_str = call.arguments["path"].as_str().unwrap_or_default();

        if path_str.is_empty() {
            return Ok(ToolResult::error(&call.id, "Empty path"));
        }

        let content = call.arguments["content"].as_str().unwrap_or_default();
        let append = call.arguments["append"].as_bool().unwrap_or(false);
        let create_dirs = call.arguments["create_dirs"].as_bool().unwrap_or(false);

        // Size check
        if content.len() > MAX_WRITE_SIZE {
            return Ok(ToolResult::error(
                &call.id,
                format!(
                    "Content too large: {} bytes (max: {} bytes)",
                    content.len(),
                    MAX_WRITE_SIZE
                ),
            ));
        }

        let path = Path::new(path_str);

        // Must be absolute
        if !path.is_absolute() {
            return Ok(ToolResult::error(
                &call.id,
                format!("Path must be absolute: '{path_str}'"),
            ));
        }

        // Block writing to sensitive locations
        let blocked_patterns = [
            "/etc/",
            "/usr/",
            "/bin/",
            "/sbin/",
            "/boot/",
            "/proc/",
            "/sys/",
            ".ssh/",
            ".env",
            ".bashrc",
            ".zshrc",
            ".profile",
            ".gitconfig",
            "credentials",
            "id_rsa",
            "id_ed25519",
        ];

        let path_lower = path_str.to_lowercase();
        for pattern in &blocked_patterns {
            if path_lower.contains(pattern) {
                return Ok(ToolResult::error(
                    &call.id,
                    format!("Access denied: '{path_str}' matches blocked pattern"),
                ));
            }
        }

        // Block writing executable files
        let blocked_extensions = [".sh", ".bash", ".exe", ".bat", ".cmd", ".ps1"];
        if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
            let ext_lower = format!(".{}", ext.to_lowercase());
            if blocked_extensions.contains(&ext_lower.as_str()) {
                return Ok(ToolResult::error(
                    &call.id,
                    format!("Access denied: writing executable files ({ext_lower}) is not allowed"),
                ));
            }
        }

        // Create parent directories if requested
        if create_dirs {
            if let Some(parent) = path.parent() {
                if let Err(e) = tokio::fs::create_dir_all(parent).await {
                    return Ok(ToolResult::error(
                        &call.id,
                        format!("Failed to create directories for '{path_str}': {e}"),
                    ));
                }
            }
        }

        // Write or append
        let result = if append {
            use tokio::io::AsyncWriteExt;
            let mut file = match tokio::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(path)
                .await
            {
                Ok(f) => f,
                Err(e) => {
                    return Ok(ToolResult::error(
                        &call.id,
                        format!("Failed to open '{path_str}' for append: {e}"),
                    ));
                }
            };
            file.write_all(content.as_bytes()).await
        } else {
            tokio::fs::write(path, content).await
        };

        match result {
            Ok(()) => {
                info!(path = %path_str, size = content.len(), append = append, "File written");
                let response = serde_json::json!({
                    "path": path_str,
                    "bytes_written": content.len(),
                    "append": append,
                });
                Ok(ToolResult::success(&call.id, response.to_string()))
            }
            Err(e) => Ok(ToolResult::error(
                &call.id,
                format!("Failed to write '{path_str}': {e}"),
            )),
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_file_write_and_read_back() {
        let skill = FileWriteSkill::new();
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("test.txt");
        let path_str = file_path.to_str().unwrap();

        let call = ToolCall {
            id: "test_1".to_string(),
            name: "file_write".to_string(),
            arguments: serde_json::json!({
                "path": path_str,
                "content": "Hello, Argentor!"
            }),
        };
        let result = skill.execute(call).await.unwrap();
        assert!(!result.is_error, "Result: {}", result.content);

        let content = tokio::fs::read_to_string(&file_path).await.unwrap();
        assert_eq!(content, "Hello, Argentor!");
    }

    #[tokio::test]
    async fn test_file_write_append() {
        let skill = FileWriteSkill::new();
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("append.txt");
        let path_str = file_path.to_str().unwrap();

        // Write initial content
        let call1 = ToolCall {
            id: "test_2a".to_string(),
            name: "file_write".to_string(),
            arguments: serde_json::json!({
                "path": path_str,
                "content": "Line 1\n"
            }),
        };
        skill.execute(call1).await.unwrap();

        // Append more
        let call2 = ToolCall {
            id: "test_2b".to_string(),
            name: "file_write".to_string(),
            arguments: serde_json::json!({
                "path": path_str,
                "content": "Line 2\n",
                "append": true
            }),
        };
        let result = skill.execute(call2).await.unwrap();
        assert!(!result.is_error);

        let content = tokio::fs::read_to_string(&file_path).await.unwrap();
        assert_eq!(content, "Line 1\nLine 2\n");
    }

    #[tokio::test]
    async fn test_file_write_create_dirs() {
        let skill = FileWriteSkill::new();
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("a/b/c/deep.txt");
        let path_str = file_path.to_str().unwrap();

        let call = ToolCall {
            id: "test_3".to_string(),
            name: "file_write".to_string(),
            arguments: serde_json::json!({
                "path": path_str,
                "content": "deep file",
                "create_dirs": true
            }),
        };
        let result = skill.execute(call).await.unwrap();
        assert!(!result.is_error, "Result: {}", result.content);

        let content = tokio::fs::read_to_string(&file_path).await.unwrap();
        assert_eq!(content, "deep file");
    }

    #[tokio::test]
    async fn test_file_write_blocked_path() {
        let skill = FileWriteSkill::new();
        let call = ToolCall {
            id: "test_4".to_string(),
            name: "file_write".to_string(),
            arguments: serde_json::json!({
                "path": "/etc/passwd",
                "content": "malicious"
            }),
        };
        let result = skill.execute(call).await.unwrap();
        assert!(result.is_error);
        assert!(result.content.contains("blocked"));
    }

    #[tokio::test]
    async fn test_file_write_blocks_executables() {
        let skill = FileWriteSkill::new();
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("evil.sh");
        let path_str = file_path.to_str().unwrap();

        let call = ToolCall {
            id: "test_5".to_string(),
            name: "file_write".to_string(),
            arguments: serde_json::json!({
                "path": path_str,
                "content": "#!/bin/bash\nrm -rf /"
            }),
        };
        let result = skill.execute(call).await.unwrap();
        assert!(result.is_error);
        assert!(result.content.contains("executable"));
    }

    #[tokio::test]
    async fn test_file_write_empty_path() {
        let skill = FileWriteSkill::new();
        let call = ToolCall {
            id: "test_6".to_string(),
            name: "file_write".to_string(),
            arguments: serde_json::json!({"path": "", "content": "x"}),
        };
        let result = skill.execute(call).await.unwrap();
        assert!(result.is_error);
    }

    #[tokio::test]
    async fn test_file_write_relative_path_rejected() {
        let skill = FileWriteSkill::new();
        let call = ToolCall {
            id: "test_7".to_string(),
            name: "file_write".to_string(),
            arguments: serde_json::json!({
                "path": "relative/path.txt",
                "content": "x"
            }),
        };
        let result = skill.execute(call).await.unwrap();
        assert!(result.is_error);
        assert!(result.content.contains("absolute"));
    }

    #[tokio::test]
    async fn test_file_write_blocks_ssh_key() {
        let skill = FileWriteSkill::new();
        let call = ToolCall {
            id: "test_8".to_string(),
            name: "file_write".to_string(),
            arguments: serde_json::json!({
                "path": "/home/user/.ssh/id_rsa",
                "content": "fake key"
            }),
        };
        let result = skill.execute(call).await.unwrap();
        assert!(result.is_error);
    }

    #[test]
    fn test_validate_arguments_denies_disallowed_path() {
        let skill = FileWriteSkill::new();
        let mut perms = PermissionSet::new();
        perms.grant(Capability::FileWrite {
            allowed_paths: vec!["/allowed".to_string()],
        });

        let call = ToolCall {
            id: "test_va_1".to_string(),
            name: "file_write".to_string(),
            arguments: serde_json::json!({"path": "/tmp/some_file.txt", "content": "x"}),
        };
        let result = skill.validate_arguments(&call, &perms);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_arguments_allows_permitted_path() {
        let skill = FileWriteSkill::new();
        let mut perms = PermissionSet::new();
        perms.grant(Capability::FileWrite {
            allowed_paths: vec!["/tmp".to_string()],
        });

        let call = ToolCall {
            id: "test_va_2".to_string(),
            name: "file_write".to_string(),
            arguments: serde_json::json!({"path": "/tmp/some_file.txt", "content": "x"}),
        };
        let result = skill.validate_arguments(&call, &perms);
        assert!(result.is_ok());
    }
}