coderlib 0.1.0

A Rust library for AI-powered code assistance and agentic system
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! HTTP content fetching tool with format conversion

use async_trait::async_trait;
use reqwest::{Client, header::HeaderMap};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Duration;

use crate::integration::HostIntegration;
use crate::tools::{Tool, ToolError, ToolResponse, Permission};

/// HTTP content fetching tool
pub struct FetchTool {
    client: Client,
}

/// Parameters for the fetch tool
#[derive(Debug, Deserialize)]
struct FetchParams {
    /// URL to fetch
    url: String,
    /// Response format: "text", "markdown", "json", "html" (default: "text")
    format: Option<String>,
    /// Request timeout in seconds (default: 30, max: 120)
    timeout: Option<u64>,
    /// Custom headers to include in the request
    headers: Option<HashMap<String, String>>,
    /// Whether to follow redirects (default: true)
    follow_redirects: Option<bool>,
    /// Maximum response size in bytes (default: 10MB)
    max_size: Option<usize>,
}

/// Fetch operation metadata
#[derive(Debug, Serialize)]
struct FetchMetadata {
    /// Final URL after redirects
    final_url: String,
    /// HTTP status code
    status_code: u16,
    /// Response headers
    response_headers: HashMap<String, String>,
    /// Content type
    content_type: String,
    /// Content length in bytes
    content_length: usize,
    /// Response time in milliseconds
    response_time_ms: u64,
    /// Whether content was converted
    converted: bool,
    /// Original format detected
    original_format: String,
    /// Target format requested
    target_format: String,
}

impl FetchTool {
    /// Create a new fetch tool
    pub fn new() -> Result<Self, ToolError> {
        let client = Client::builder()
            .user_agent("coderlib/1.0")
            .timeout(Duration::from_secs(30))
            .build()
            .map_err(|e| ToolError::ExecutionFailed(format!("Failed to create HTTP client: {}", e)))?;
        
        Ok(Self { client })
    }
    
    /// Fetch content from URL
    async fn fetch_content(&self, params: &FetchParams) -> Result<(String, FetchMetadata), ToolError> {
        let start_time = std::time::Instant::now();
        
        // Validate URL
        let url = reqwest::Url::parse(&params.url)
            .map_err(|e| ToolError::InvalidParameters(format!("Invalid URL: {}", e)))?;
        
        // Build client with custom settings
        let mut client_builder = Client::builder()
            .user_agent("coderlib/1.0");
        
        // Set timeout
        let timeout = params.timeout.unwrap_or(30).min(120);
        client_builder = client_builder.timeout(Duration::from_secs(timeout));
        
        // Set redirect policy
        if !params.follow_redirects.unwrap_or(true) {
            client_builder = client_builder.redirect(reqwest::redirect::Policy::none());
        }
        
        let client = client_builder.build()
            .map_err(|e| ToolError::ExecutionFailed(format!("Failed to create HTTP client: {}", e)))?;
        
        // Build request
        let mut request = client.get(url.clone());
        
        // Add custom headers
        if let Some(headers) = &params.headers {
            let mut header_map = HeaderMap::new();
            for (key, value) in headers {
                let header_name: reqwest::header::HeaderName = key.parse()
                    .map_err(|e| ToolError::InvalidParameters(format!("Invalid header name '{}': {}", key, e)))?;
                let header_value: reqwest::header::HeaderValue = value.parse()
                    .map_err(|e| ToolError::InvalidParameters(format!("Invalid header value '{}': {}", value, e)))?;
                header_map.insert(header_name, header_value);
            }
            request = request.headers(header_map);
        }
        
        // Send request
        let response = request.send().await
            .map_err(|e| ToolError::ExecutionFailed(format!("Failed to fetch URL: {}", e)))?;
        
        let response_time = start_time.elapsed();
        let status_code = response.status().as_u16();
        let final_url = response.url().to_string();
        
        // Check status code
        if !response.status().is_success() {
            return Err(ToolError::ExecutionFailed(format!(
                "Request failed with status code: {} ({})", 
                status_code, response.status().canonical_reason().unwrap_or("Unknown")
            )));
        }
        
        // Extract response headers
        let mut response_headers = HashMap::new();
        for (name, value) in response.headers() {
            if let Ok(value_str) = value.to_str() {
                response_headers.insert(name.to_string(), value_str.to_string());
            }
        }
        
        // Get content type
        let content_type = response.headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok())
            .unwrap_or("text/plain")
            .to_string();
        
        // Check content length
        let max_size = params.max_size.unwrap_or(10 * 1024 * 1024); // 10MB default
        if let Some(content_length) = response.content_length() {
            if content_length as usize > max_size {
                return Err(ToolError::ExecutionFailed(format!(
                    "Response too large: {} bytes (max: {} bytes)", 
                    content_length, max_size
                )));
            }
        }
        
        // Read response body
        let bytes = response.bytes().await
            .map_err(|e| ToolError::ExecutionFailed(format!("Failed to read response body: {}", e)))?;
        
        // Check actual size
        if bytes.len() > max_size {
            return Err(ToolError::ExecutionFailed(format!(
                "Response too large: {} bytes (max: {} bytes)", 
                bytes.len(), max_size
            )));
        }
        
        // Convert to string
        let content = String::from_utf8_lossy(&bytes).to_string();
        
        // Detect original format
        let original_format = self.detect_format(&content_type, &content);
        let target_format = params.format.as_deref().unwrap_or("text");
        
        // Convert format if needed
        let (converted_content, converted) = self.convert_format(&content, &original_format, target_format)?;
        
        let metadata = FetchMetadata {
            final_url,
            status_code,
            response_headers,
            content_type,
            content_length: bytes.len(),
            response_time_ms: response_time.as_millis() as u64,
            converted,
            original_format,
            target_format: target_format.to_string(),
        };
        
        Ok((converted_content, metadata))
    }
    
    /// Detect content format from content type and content
    fn detect_format(&self, content_type: &str, content: &str) -> String {
        if content_type.contains("application/json") {
            "json".to_string()
        } else if content_type.contains("text/html") {
            "html".to_string()
        } else if content_type.contains("text/markdown") || content_type.contains("text/x-markdown") {
            "markdown".to_string()
        } else if content.trim_start().starts_with("<!DOCTYPE html") || content.trim_start().starts_with("<html") {
            "html".to_string()
        } else if content.trim_start().starts_with('{') || content.trim_start().starts_with('[') {
            "json".to_string()
        } else {
            "text".to_string()
        }
    }
    
    /// Convert content format
    fn convert_format(&self, content: &str, from_format: &str, to_format: &str) -> Result<(String, bool), ToolError> {
        if from_format == to_format {
            return Ok((content.to_string(), false));
        }
        
        match (from_format, to_format) {
            ("html", "markdown") => {
                self.html_to_markdown(content).map(|s| (s, true))
            }
            ("html", "text") => {
                self.html_to_text(content).map(|s| (s, true))
            }
            ("json", "text") => {
                self.json_to_text(content).map(|s| (s, true))
            }
            ("markdown", "text") => {
                self.markdown_to_text(content).map(|s| (s, true))
            }
            _ => {
                // No conversion available, return as-is
                Ok((content.to_string(), false))
            }
        }
    }
    
    /// Convert HTML to Markdown
    fn html_to_markdown(&self, html: &str) -> Result<String, ToolError> {
        // Simple HTML to Markdown conversion
        // In a real implementation, you'd use a proper HTML parser like scraper
        let mut markdown = html.to_string();
        
        // Basic conversions
        markdown = markdown.replace("<br>", "\n");
        markdown = markdown.replace("<br/>", "\n");
        markdown = markdown.replace("<br />", "\n");
        markdown = markdown.replace("<p>", "\n\n");
        markdown = markdown.replace("</p>", "");
        markdown = markdown.replace("<h1>", "# ");
        markdown = markdown.replace("</h1>", "\n");
        markdown = markdown.replace("<h2>", "## ");
        markdown = markdown.replace("</h2>", "\n");
        markdown = markdown.replace("<h3>", "### ");
        markdown = markdown.replace("</h3>", "\n");
        
        // Remove other HTML tags (simple approach)
        let re = regex::Regex::new(r"<[^>]*>").unwrap();
        markdown = re.replace_all(&markdown, "").to_string();
        
        // Clean up extra whitespace
        let re = regex::Regex::new(r"\n\s*\n\s*\n").unwrap();
        markdown = re.replace_all(&markdown, "\n\n").to_string();
        
        Ok(markdown.trim().to_string())
    }
    
    /// Convert HTML to plain text
    fn html_to_text(&self, html: &str) -> Result<String, ToolError> {
        // Remove HTML tags and decode entities
        let re = regex::Regex::new(r"<[^>]*>").unwrap();
        let text = re.replace_all(html, "").to_string();
        
        // Basic HTML entity decoding
        let text = text.replace("&amp;", "&");
        let text = text.replace("&lt;", "<");
        let text = text.replace("&gt;", ">");
        let text = text.replace("&quot;", "\"");
        let text = text.replace("&#39;", "'");
        let text = text.replace("&nbsp;", " ");
        
        // Clean up whitespace
        let re = regex::Regex::new(r"\s+").unwrap();
        let text = re.replace_all(&text, " ").to_string();
        
        Ok(text.trim().to_string())
    }
    
    /// Convert JSON to formatted text
    fn json_to_text(&self, json: &str) -> Result<String, ToolError> {
        match serde_json::from_str::<serde_json::Value>(json) {
            Ok(value) => Ok(serde_json::to_string_pretty(&value)
                .unwrap_or_else(|_| json.to_string())),
            Err(_) => Ok(json.to_string()), // Return as-is if not valid JSON
        }
    }
    
    /// Convert Markdown to plain text
    fn markdown_to_text(&self, markdown: &str) -> Result<String, ToolError> {
        // Simple Markdown to text conversion
        let mut text = markdown.to_string();
        
        // Remove Markdown syntax
        let re = regex::Regex::new(r"^#{1,6}\s+").unwrap();
        text = re.replace_all(&text, "").to_string();
        
        let re = regex::Regex::new(r"\*\*([^*]+)\*\*").unwrap();
        text = re.replace_all(&text, "$1").to_string();
        
        let re = regex::Regex::new(r"\*([^*]+)\*").unwrap();
        text = re.replace_all(&text, "$1").to_string();
        
        let re = regex::Regex::new(r"`([^`]+)`").unwrap();
        text = re.replace_all(&text, "$1").to_string();
        
        let re = regex::Regex::new(r"\[([^\]]+)\]\([^)]+\)").unwrap();
        text = re.replace_all(&text, "$1").to_string();
        
        Ok(text)
    }
    
    /// Format the fetch response
    fn format_response(&self, content: &str, metadata: &FetchMetadata) -> String {
        let mut response = String::new();
        
        response.push_str(&format!("Successfully fetched content from: {}\n\n", metadata.final_url));
        response.push_str(&format!("Status: {} {}\n", metadata.status_code, 
            if metadata.status_code == 200 { "OK" } else { "Success" }));
        response.push_str(&format!("Content-Type: {}\n", metadata.content_type));
        response.push_str(&format!("Content-Length: {} bytes\n", metadata.content_length));
        response.push_str(&format!("Response Time: {}ms\n", metadata.response_time_ms));
        
        if metadata.converted {
            response.push_str(&format!("Format: {} → {}\n", metadata.original_format, metadata.target_format));
        }
        
        response.push_str("\n--- Content ---\n");
        response.push_str(content);
        
        response
    }
}

impl Default for FetchTool {
    fn default() -> Self {
        Self::new().unwrap_or_else(|_| Self {
            client: Client::new(),
        })
    }
}

#[async_trait]
impl Tool for FetchTool {
    async fn execute(
        &self,
        parameters: serde_json::Value,
        _host: &dyn HostIntegration,
    ) -> Result<ToolResponse, ToolError> {
        let params: FetchParams = serde_json::from_value(parameters)
            .map_err(|e| ToolError::InvalidParameters(format!("Invalid parameters: {}", e)))?;

        // Validate URL
        if params.url.trim().is_empty() {
            return Err(ToolError::InvalidParameters("url is required".to_string()));
        }

        // Validate format
        let valid_formats = ["text", "markdown", "json", "html"];
        if let Some(format) = &params.format {
            if !valid_formats.contains(&format.as_str()) {
                return Err(ToolError::InvalidParameters(format!(
                    "Invalid format '{}'. Supported formats: {}",
                    format, valid_formats.join(", ")
                )));
            }
        }

        // Fetch content
        let (content, metadata) = self.fetch_content(&params).await?;

        let response_content = self.format_response(&content, &metadata);
        let metadata_json = serde_json::to_value(&metadata)
            .unwrap_or(serde_json::Value::Null);

        Ok(ToolResponse {
            content: response_content,
            success: true,
            metadata: metadata_json,
            affected_files: Vec::new(), // No files affected by fetch
        })
    }

    fn name(&self) -> &str {
        "fetch"
    }

    fn description(&self) -> &str {
        "Fetch content from URLs with format conversion. Supports converting HTML to Markdown/text, JSON formatting, and more."
    }

    fn requires_permission(&self) -> Permission {
        Permission::NetworkAccess // Requires network access
    }

    fn parameter_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "url": {
                    "type": "string",
                    "description": "URL to fetch content from",
                    "format": "uri"
                },
                "format": {
                    "type": "string",
                    "description": "Response format: text, markdown, json, or html (default: text)",
                    "enum": ["text", "markdown", "json", "html"],
                    "default": "text"
                },
                "timeout": {
                    "type": "integer",
                    "description": "Request timeout in seconds (default: 30, max: 120)",
                    "default": 30,
                    "minimum": 1,
                    "maximum": 120
                },
                "headers": {
                    "type": "object",
                    "description": "Custom headers to include in the request",
                    "additionalProperties": {
                        "type": "string"
                    }
                },
                "follow_redirects": {
                    "type": "boolean",
                    "description": "Whether to follow redirects (default: true)",
                    "default": true
                },
                "max_size": {
                    "type": "integer",
                    "description": "Maximum response size in bytes (default: 10MB)",
                    "default": 10485760,
                    "minimum": 1024,
                    "maximum": 104857600
                }
            },
            "required": ["url"]
        })
    }

    fn clone_box(&self) -> Box<dyn Tool> {
        Box::new(Self {
            client: self.client.clone(),
        })
    }
}

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

    #[tokio::test]
    async fn test_fetch_tool_creation() {
        let tool = FetchTool::new().unwrap();
        assert_eq!(tool.name(), "fetch");
        assert!(!tool.description().is_empty());
    }

    #[test]
    fn test_format_detection() {
        let tool = FetchTool::new().unwrap();

        assert_eq!(tool.detect_format("application/json", "{}"), "json");
        assert_eq!(tool.detect_format("text/html", "<html></html>"), "html");
        assert_eq!(tool.detect_format("text/plain", "hello"), "text");
        assert_eq!(tool.detect_format("text/plain", "<!DOCTYPE html>"), "html");
        assert_eq!(tool.detect_format("text/plain", "{\"key\": \"value\"}"), "json");
    }

    #[test]
    fn test_html_to_text() {
        let tool = FetchTool::new().unwrap();
        let html = "<h1>Title</h1><p>Hello <strong>world</strong>!</p>";
        let text = tool.html_to_text(html).unwrap();
        assert!(text.contains("Title"));
        assert!(text.contains("Hello world!"));
        assert!(!text.contains("<"));
    }

    #[test]
    fn test_json_formatting() {
        let tool = FetchTool::new().unwrap();
        let json = r#"{"name":"test","value":123}"#;
        let formatted = tool.json_to_text(json).unwrap();
        assert!(formatted.contains("\"name\": \"test\""));
        assert!(formatted.len() > json.len()); // Should be pretty-printed
    }
}