serdes-ai-tools 0.2.5

Tool system for serdes-ai 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
//! File search tool using vector similarity search.
//!
//! This module provides a configurable file search tool that uses
//! embeddings for semantic search over files.

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;

use crate::{
    definition::ToolDefinition,
    errors::ToolError,
    return_types::{ToolResult, ToolReturn},
    schema::SchemaBuilder,
    tool::Tool,
    RunContext,
};

/// Configuration for the file search tool.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileSearchConfig {
    /// Maximum number of results to return.
    pub max_results: usize,
    /// Minimum similarity score (0.0 to 1.0).
    pub min_score: f64,
    /// File extensions to search.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub file_extensions: Vec<String>,
    /// Directories to search.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub search_paths: Vec<String>,
    /// Whether to include file content in results.
    pub include_content: bool,
    /// Maximum content snippet length.
    pub max_content_length: usize,
}

impl Default for FileSearchConfig {
    fn default() -> Self {
        Self {
            max_results: 10,
            min_score: 0.5,
            file_extensions: Vec::new(),
            search_paths: Vec::new(),
            include_content: true,
            max_content_length: 500,
        }
    }
}

impl FileSearchConfig {
    /// Create a new config with defaults.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set max results.
    #[must_use]
    pub fn max_results(mut self, max: usize) -> Self {
        self.max_results = max;
        self
    }

    /// Set minimum similarity score.
    #[must_use]
    pub fn min_score(mut self, score: f64) -> Self {
        self.min_score = score.clamp(0.0, 1.0);
        self
    }

    /// Set file extensions to search.
    #[must_use]
    pub fn file_extensions(mut self, exts: Vec<String>) -> Self {
        self.file_extensions = exts;
        self
    }

    /// Add a file extension.
    #[must_use]
    pub fn add_extension(mut self, ext: impl Into<String>) -> Self {
        self.file_extensions.push(ext.into());
        self
    }

    /// Set search paths.
    #[must_use]
    pub fn search_paths(mut self, paths: Vec<String>) -> Self {
        self.search_paths = paths;
        self
    }

    /// Add a search path.
    #[must_use]
    pub fn add_path(mut self, path: impl Into<String>) -> Self {
        self.search_paths.push(path.into());
        self
    }

    /// Set whether to include content.
    #[must_use]
    pub fn include_content(mut self, include: bool) -> Self {
        self.include_content = include;
        self
    }

    /// Set max content length.
    #[must_use]
    pub fn max_content_length(mut self, length: usize) -> Self {
        self.max_content_length = length;
        self
    }
}

/// A file search result.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileSearchResult {
    /// File path.
    pub path: String,
    /// File name.
    pub filename: String,
    /// Similarity score.
    pub score: f64,
    /// Content snippet.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    /// Line number where match was found.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line_number: Option<usize>,
}

/// File search tool.
///
/// This tool allows agents to search files using semantic similarity.
/// It requires integration with an embedding model and vector store.
///
/// # Example
///
/// ```ignore
/// use serdes_ai_tools::builtin::{FileSearchTool, FileSearchConfig};
///
/// let tool = FileSearchTool::with_config(
///     FileSearchConfig::new()
///         .max_results(5)
///         .add_extension("rs")
///         .add_extension("py")
/// );
/// ```
pub struct FileSearchTool {
    config: FileSearchConfig,
}

impl FileSearchTool {
    /// Create a new file search tool with default config.
    #[must_use]
    pub fn new() -> Self {
        Self {
            config: FileSearchConfig::default(),
        }
    }

    /// Create with a specific config.
    #[must_use]
    pub fn with_config(config: FileSearchConfig) -> Self {
        Self { config }
    }

    /// Get the tool schema.
    fn schema() -> JsonValue {
        SchemaBuilder::new()
            .string("query", "The search query", true)
            .string_array(
                "file_extensions",
                "File extensions to filter by (e.g., ['rs', 'py'])",
                false,
            )
            .integer_constrained(
                "max_results",
                "Maximum number of results to return",
                false,
                Some(1),
                Some(50),
            )
            .build()
            .expect("SchemaBuilder JSON serialization failed")
    }

    /// Perform the search (stub - integrate with vector store).
    async fn search(
        &self,
        query: &str,
        _extensions: &[String],
        max_results: usize,
    ) -> Vec<FileSearchResult> {
        // This is a stub implementation.
        // In a real implementation, you would:
        // 1. Generate an embedding for the query
        // 2. Search a vector store (e.g., Qdrant, Pinecone, etc.)
        // 3. Filter by file extensions if provided
        // 4. Return the top results with content snippets

        vec![FileSearchResult {
            path: "/example/path/file.rs".to_string(),
            filename: "file.rs".to_string(),
            score: 0.95,
            content: Some(format!(
                "This is a placeholder. Integrate with a vector store to get real results. \
                 Query: '{}', Max results: {}",
                query, max_results
            )),
            line_number: Some(1),
        }]
    }
}

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

#[async_trait]
impl<Deps: Send + Sync> Tool<Deps> for FileSearchTool {
    fn definition(&self) -> ToolDefinition {
        ToolDefinition::new("file_search", "Search files using semantic similarity")
            .with_parameters(Self::schema())
    }

    async fn call(&self, _ctx: &RunContext<Deps>, args: JsonValue) -> ToolResult {
        let query = args.get("query").and_then(|v| v.as_str()).ok_or_else(|| {
            ToolError::validation_error(
                "file_search",
                Some("query".to_string()),
                "Missing 'query' field",
            )
        })?;

        if query.trim().is_empty() {
            return Err(ToolError::validation_error(
                "file_search",
                Some("query".to_string()),
                "Query cannot be empty",
            ));
        }

        let extensions: Vec<String> = args
            .get("file_extensions")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str())
                    .map(String::from)
                    .collect()
            })
            .unwrap_or_else(|| self.config.file_extensions.clone());

        let max_results = args
            .get("max_results")
            .and_then(|v| v.as_u64())
            .map(|n| n as usize)
            .unwrap_or(self.config.max_results)
            .min(50);

        let results = self.search(query, &extensions, max_results).await;

        // Filter by min score
        let filtered: Vec<_> = results
            .into_iter()
            .filter(|r| r.score >= self.config.min_score)
            .collect();

        let output = serde_json::json!({
            "query": query,
            "results": filtered,
            "total": filtered.len()
        });

        Ok(ToolReturn::json(output))
    }

    fn max_retries(&self) -> Option<u32> {
        Some(2)
    }
}

impl std::fmt::Debug for FileSearchTool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FileSearchTool")
            .field("config", &self.config)
            .finish()
    }
}

/// Trait for file search providers.
#[allow(async_fn_in_trait)]
pub trait FileSearchProvider: Send + Sync {
    /// Search files.
    async fn search(
        &self,
        query: &str,
        config: &FileSearchConfig,
    ) -> Result<Vec<FileSearchResult>, ToolError>;
}

/// File indexer for building search indices.
#[allow(async_fn_in_trait)]
pub trait FileIndexer: Send + Sync {
    /// Index files at the given paths.
    async fn index_files(&self, paths: &[String]) -> Result<usize, ToolError>;

    /// Re-index a single file.
    async fn reindex_file(&self, path: &str) -> Result<(), ToolError>;

    /// Remove a file from the index.
    async fn remove_file(&self, path: &str) -> Result<(), ToolError>;
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_file_search_config() {
        let config = FileSearchConfig::new()
            .max_results(5)
            .min_score(0.7)
            .add_extension("rs")
            .add_path("/src");

        assert_eq!(config.max_results, 5);
        assert_eq!(config.min_score, 0.7);
        assert_eq!(config.file_extensions, vec!["rs"]);
        assert_eq!(config.search_paths, vec!["/src"]);
    }

    #[test]
    fn test_min_score_clamping() {
        let config = FileSearchConfig::new().min_score(1.5);
        assert_eq!(config.min_score, 1.0);

        let config2 = FileSearchConfig::new().min_score(-0.5);
        assert_eq!(config2.min_score, 0.0);
    }

    #[test]
    fn test_file_search_tool_definition() {
        let tool = FileSearchTool::new();
        let def = <FileSearchTool as Tool<()>>::definition(&tool);
        assert_eq!(def.name, "file_search");
        let required = def
            .parameters()
            .get("required")
            .and_then(|value| value.as_array())
            .unwrap();
        assert!(required.iter().any(|value| value.as_str() == Some("query")));
    }

    #[tokio::test]
    async fn test_file_search_tool_call() {
        let tool = FileSearchTool::new();
        let ctx = RunContext::minimal("test");

        let result = tool
            .call(&ctx, serde_json::json!({"query": "find user auth"}))
            .await
            .unwrap();

        assert!(!result.is_error());
        let json = result.as_json().unwrap();
        assert_eq!(json["query"], "find user auth");
    }

    #[tokio::test]
    async fn test_file_search_missing_query() {
        let tool = FileSearchTool::new();
        let ctx = RunContext::minimal("test");

        let result = tool.call(&ctx, serde_json::json!({})).await;
        assert!(matches!(result, Err(ToolError::ValidationFailed { .. })));
    }

    #[tokio::test]
    async fn test_file_search_empty_query() {
        let tool = FileSearchTool::new();
        let ctx = RunContext::minimal("test");

        let result = tool.call(&ctx, serde_json::json!({"query": "  "})).await;
        assert!(matches!(result, Err(ToolError::ValidationFailed { .. })));
    }

    #[tokio::test]
    async fn test_file_search_with_extensions() {
        let tool = FileSearchTool::new();
        let ctx = RunContext::minimal("test");

        let result = tool
            .call(
                &ctx,
                serde_json::json!({
                    "query": "test",
                    "file_extensions": ["rs", "py"]
                }),
            )
            .await
            .unwrap();

        assert!(!result.is_error());
    }

    #[test]
    fn test_file_search_result() {
        let result = FileSearchResult {
            path: "/test/file.rs".to_string(),
            filename: "file.rs".to_string(),
            score: 0.95,
            content: Some("fn main() {}".to_string()),
            line_number: Some(1),
        };

        let json = serde_json::to_value(&result).unwrap();
        assert_eq!(json["filename"], "file.rs");
        assert_eq!(json["score"], 0.95);
    }
}