distri-filesystem 0.3.7

Filesystem and artifact tools for Distri agents
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
use crate::ArtifactWrapper;
use anyhow::Result;
use distri_types::{filesystem::FileSystemOps, Tool, ToolContext};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::sync::Arc;

// Base path metadata configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArtifactBasePath {
    pub base_path: String,
}

impl ArtifactBasePath {
    /// Extract base_path from ToolContext metadata with fallback to computed path
    pub fn from_context(context: &ToolContext) -> Option<String> {
        let base_path: Option<&str> = context
            .metadata
            .as_ref()
            .and_then(|m| m.get("artifact_base_path"))
            .and_then(|m| m.as_str());
        if let Some(v) = base_path {
            tracing::info!("✅ Using artifact_base_path from metadata: {}", v);
            Some(v.to_string())
        } else {
            // If not injected from parent, you can use your task namespace
            let artifact_base_path =
                crate::ArtifactWrapper::task_namespace(&context.thread_id, &context.task_id);
            tracing::info!(
                "No metadata provided, using computed path: {}",
                artifact_base_path
            );
            Some(artifact_base_path)
        }
    }
}

// Artifact-specific parameter types
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ListArtifactsParams {
    pub namespace: Option<String>, // thread_id or custom namespace
    pub limit: Option<usize>,
    #[serde(default)]
    pub include_preview: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ReadArtifactParams {
    pub filename: String,
    pub start_line: Option<u64>,
    pub end_line: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SearchArtifactsParams {
    pub pattern: String, // Search pattern to find within artifact content
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DeleteArtifactParams {
    pub filename: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SaveArtifactParams {
    pub filename: String,
    pub content: String,
}

// Artifact response types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArtifactListEntry {
    pub artifact_id: String,
    pub path: String,
    pub size: u64,
    pub preview: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArtifactListResponse {
    pub artifacts: Vec<ArtifactListEntry>,
    pub total: usize,
}

/// List available artifacts
#[derive(Debug)]
pub struct ListArtifactsTool {
    filesystem: Arc<dyn FileSystemOps>,
}

impl ListArtifactsTool {
    pub fn new(filesystem: Arc<dyn FileSystemOps>) -> Self {
        Self { filesystem }
    }
}

#[async_trait::async_trait]
impl Tool for ListArtifactsTool {
    fn get_name(&self) -> String {
        "list_artifacts".to_string()
    }

    fn get_description(&self) -> String {
        "List all available artifacts in the current task".to_string()
    }

    fn get_parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "namespace": {
                    "type": "string",
                    "description": "Optional namespace override (thread_id or custom namespace)"
                },
                "limit": {
                    "type": "integer",
                    "description": "Optional maximum number of artifacts to return"
                },
                "include_preview": {
                    "type": "boolean",
                    "description": "When true, include short content previews for each artifact",
                    "default": false
                }
            }
        })
    }

    async fn execute(
        &self,
        _tool_call: distri_types::ToolCall,
        context: Arc<ToolContext>,
    ) -> Result<Vec<distri_types::Part>, anyhow::Error> {
        // Use ArtifactNamespace to get thread and task paths
        let namespace = distri_types::ArtifactNamespace::new(
            context.thread_id.clone(),
            Some(context.task_id.clone()),
        );

        // Check thread level first, then task level
        let thread_path = namespace.thread_path();
        let paths_to_check = if let Some(task_path) = namespace.task_path() {
            vec![thread_path, task_path]
        } else {
            vec![thread_path]
        };

        tracing::info!(
            "🔍 ListArtifactsTool: thread_id={}, task_id={}, checking paths: {:?}",
            context.thread_id,
            context.task_id,
            paths_to_check
        );

        // Check all paths and merge results
        let mut all_artifacts = Vec::new();
        let mut seen_filenames = std::collections::HashSet::new();

        for path in paths_to_check {
            if let Ok(wrapper) = ArtifactWrapper::new(self.filesystem.clone(), path.clone()).await {
                if let Ok(entries) = wrapper.list_artifacts().await {
                    for entry in entries {
                        if !seen_filenames.contains(&entry.name) {
                            seen_filenames.insert(entry.name.clone());
                            all_artifacts.push(entry);
                        }
                    }
                }
            }
        }

        tracing::info!(
            "✅ ListArtifactsTool: Found {} artifacts",
            all_artifacts.len()
        );
        Ok(vec![distri_types::Part::Data(serde_json::to_value(
            all_artifacts,
        )?)])
    }
}

/// Read specific artifact content
#[derive(Debug)]
pub struct ReadArtifactTool {
    filesystem: Arc<dyn FileSystemOps>,
}

impl ReadArtifactTool {
    pub fn new(filesystem: Arc<dyn FileSystemOps>) -> Self {
        Self { filesystem }
    }
}

#[async_trait::async_trait]
impl Tool for ReadArtifactTool {
    fn get_name(&self) -> String {
        "read_artifact".to_string()
    }

    fn get_description(&self) -> String {
        "Read the content of a specific artifact by filename (including extension)".to_string()
    }

    fn get_parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "filename": {
                    "type": "string",
                    "description": "Filename of the artifact to read, including extension"
                },
                "start_line": {
                    "type": "integer",
                    "description": "Optional starting line (1-based)",
                    "minimum": 1
                },
                "end_line": {
                    "type": "integer",
                    "description": "Optional ending line (inclusive, 1-based)",
                    "minimum": 1
                }
            },
            "required": ["filename"]
        })
    }

    async fn execute(
        &self,
        tool_call: distri_types::ToolCall,
        context: Arc<ToolContext>,
    ) -> Result<Vec<distri_types::Part>, anyhow::Error> {
        let params: ReadArtifactParams = serde_json::from_value(tool_call.input)?;

        // Use ArtifactNamespace to get thread and task paths
        let namespace = distri_types::ArtifactNamespace::new(
            context.thread_id.clone(),
            Some(context.task_id.clone()),
        );

        // Check thread level first, then task level
        let thread_path = namespace.thread_path();
        let paths_to_check = if let Some(task_path) = namespace.task_path() {
            vec![thread_path, task_path]
        } else {
            vec![thread_path]
        };

        tracing::info!(
            "🔍 ReadArtifactTool: thread_id={}, task_id={}, filename={}, checking paths: {:?}",
            context.thread_id,
            context.task_id,
            params.filename,
            paths_to_check
        );

        // Try each path until we find the artifact
        let mut last_error = None;
        for path in paths_to_check {
            if let Ok(wrapper) = ArtifactWrapper::new(self.filesystem.clone(), path.clone()).await {
                match wrapper
                    .read_artifact(&params.filename, params.start_line, params.end_line)
                    .await
                {
                    Ok(result) => {
                        tracing::info!("✅ ReadArtifactTool: Found artifact at path: {}", path);
                        return Ok(vec![distri_types::Part::Data(serde_json::to_value(
                            result,
                        )?)]);
                    }
                    Err(e) => {
                        last_error = Some(e);
                        continue;
                    }
                }
            }
        }

        // If we get here, artifact wasn't found in any path
        Err(last_error.unwrap_or_else(|| {
            anyhow::anyhow!(
                "Artifact '{}' not found in any namespace path",
                params.filename
            )
        }))
    }
}

/// Search within artifact contents
#[derive(Debug)]
pub struct SearchArtifactsTool {
    filesystem: Arc<dyn FileSystemOps>,
}

impl SearchArtifactsTool {
    pub fn new(filesystem: Arc<dyn FileSystemOps>) -> Self {
        Self { filesystem }
    }
}

#[async_trait::async_trait]
impl Tool for SearchArtifactsTool {
    fn get_name(&self) -> String {
        "search_artifacts".to_string()
    }

    fn get_description(&self) -> String {
        "Search for text patterns within all available artifacts".to_string()
    }

    fn get_parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "pattern": {
                    "type": "string",
                    "description": "Search pattern to find within artifact content"
                }
            },
            "required": ["pattern"]
        })
    }

    async fn execute(
        &self,
        tool_call: distri_types::ToolCall,
        context: Arc<ToolContext>,
    ) -> Result<Vec<distri_types::Part>, anyhow::Error> {
        let params: SearchArtifactsParams = serde_json::from_value(tool_call.input)?;
        let base_path = ArtifactBasePath::from_context(&context)
            .ok_or(anyhow::anyhow!("artifact_base_path is empty in metadata"))?;
        let wrapper = ArtifactWrapper::new(self.filesystem.clone(), base_path).await?;
        let result = wrapper.search_artifacts(&params.pattern).await?;
        Ok(vec![distri_types::Part::Data(serde_json::to_value(
            result,
        )?)])
    }
}

/// Delete specific artifact
#[derive(Debug)]
pub struct DeleteArtifactTool {
    filesystem: Arc<dyn FileSystemOps>,
}

impl DeleteArtifactTool {
    pub fn new(filesystem: Arc<dyn FileSystemOps>) -> Self {
        Self { filesystem }
    }
}

#[async_trait::async_trait]
impl Tool for DeleteArtifactTool {
    fn get_name(&self) -> String {
        "delete_artifact".to_string()
    }

    fn get_description(&self) -> String {
        "Delete a specific artifact by ID".to_string()
    }

    fn get_parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "filename": {
                    "type": "string",
                    "description": "Filename of the artifact to delete"
                }
            },
            "required": ["filename"]
        })
    }

    async fn execute(
        &self,
        tool_call: distri_types::ToolCall,
        context: Arc<ToolContext>,
    ) -> Result<Vec<distri_types::Part>, anyhow::Error> {
        let params: DeleteArtifactParams = serde_json::from_value(tool_call.input)?;
        let base_path = ArtifactBasePath::from_context(&context)
            .ok_or(anyhow::anyhow!("artifact_base_path is empty in metadata"))?;
        let wrapper = ArtifactWrapper::new(self.filesystem.clone(), base_path).await?;
        wrapper.cleanup_task_folder().await?;
        Ok(vec![distri_types::Part::Data(
            serde_json::json!({"success": true, "filename": params.filename}),
        )])
    }
}

/// Save content as artifact
#[derive(Debug)]
pub struct SaveArtifactTool {
    filesystem: Arc<dyn FileSystemOps>,
}

impl SaveArtifactTool {
    pub fn new(filesystem: Arc<dyn FileSystemOps>) -> Self {
        Self { filesystem }
    }
}

#[async_trait::async_trait]
impl Tool for SaveArtifactTool {
    fn get_name(&self) -> String {
        "save_artifact".to_string()
    }

    fn get_description(&self) -> String {
        "Save content as an artifact with specified filename".to_string()
    }

    fn get_parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "filename": {
                    "type": "string",
                    "description": "Filename (including extension) to save the artifact as"
                },
                "content": {
                    "type": "string",
                    "description": "Content to store in the artifact"
                }
            },
            "required": ["filename", "content"]
        })
    }

    async fn execute(
        &self,
        tool_call: distri_types::ToolCall,
        context: Arc<ToolContext>,
    ) -> Result<Vec<distri_types::Part>, anyhow::Error> {
        let params: SaveArtifactParams = serde_json::from_value(tool_call.input)?;
        let base_path = ArtifactBasePath::from_context(&context)
            .ok_or(anyhow::anyhow!("artifact_base_path is empty in metadata"))?;
        tracing::info!(
            "🔍 SaveArtifactTool: thread_id={}, task_id={}, base_path={}",
            context.thread_id,
            context.task_id,
            base_path
        );
        let wrapper = ArtifactWrapper::new(self.filesystem.clone(), base_path).await?;

        tracing::info!(
            "💾 SaveArtifactTool: Saving filename={}, content_len={}",
            params.filename,
            params.content.len()
        );

        wrapper
            .save_artifact(&params.filename, &params.content)
            .await?;
        tracing::info!("✅ SaveArtifactTool: Successfully saved artifact");
        Ok(vec![distri_types::Part::Data(serde_json::json!({
            "success": true,
            "filename": params.filename
        }))])
    }
}

/// Factory function to create all artifact tools
pub fn create_artifact_tools(filesystem: Arc<dyn FileSystemOps>) -> Vec<Arc<dyn Tool>> {
    vec![
        Arc::new(ListArtifactsTool::new(filesystem.clone())) as Arc<dyn Tool>,
        Arc::new(ReadArtifactTool::new(filesystem.clone())) as Arc<dyn Tool>,
        Arc::new(SearchArtifactsTool::new(filesystem.clone())) as Arc<dyn Tool>,
        Arc::new(DeleteArtifactTool::new(filesystem.clone())) as Arc<dyn Tool>,
        Arc::new(SaveArtifactTool::new(filesystem)) as Arc<dyn Tool>,
    ]
}