hippox-drivers 0.3.3

🦛All indivisible atomic driver units in Hippox.
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
use crate::DriverCallback;
use crate::DriverContext;
use crate::{
    DriverCategory,
    types::{Driver, DriverParameter},
};
use crate::{ensure_dir, file_exists, read_file_content, validate_path, write_file_content};
use anyhow::Result;
use serde_json::{Value, json};
use std::collections::HashMap;

#[derive(Debug)]
pub struct HtmlReadDriver;

#[async_trait::async_trait]
impl Driver for HtmlReadDriver {
    fn name(&self) -> &str {
        "html_read"
    }

    fn description(&self) -> &str {
        "Read and parse HTML file content"
    }

    fn usage_hint(&self) -> &str {
        "Use this skill when the user wants to read an HTML file, extract text content, or parse HTML structure"
    }

    fn parameters(&self) -> Vec<DriverParameter> {
        vec![
            DriverParameter {
                name: "path".to_string(),
                param_type: "string".to_string(),
                description: "Path to the HTML file".to_string(),
                required: true,
                default: None,
                example: Some(Value::String("index.html".to_string())),
                enum_values: None,
            },
            DriverParameter {
                name: "extract_text".to_string(),
                param_type: "boolean".to_string(),
                description: "Extract only text content (strip HTML tags)".to_string(),
                required: false,
                default: Some(Value::Bool(false)),
                example: Some(Value::Bool(true)),
                enum_values: None,
            },
            DriverParameter {
                name: "selector".to_string(),
                param_type: "string".to_string(),
                description: "CSS selector to extract specific elements".to_string(),
                required: false,
                default: None,
                example: Some(Value::String("div.content".to_string())),
                enum_values: None,
            },
        ]
    }

    fn example_call(&self) -> Value {
        json!({
            "action": "html_read",
            "parameters": {
                "path": "index.html"
            }
        })
    }

    fn example_output(&self) -> String {
        "<html><body><h1>Title</h1></body></html>".to_string()
    }

    fn category(&self) -> DriverCategory {
        DriverCategory::Document
    }
    async fn execute(
        &self,
        parameters: &HashMap<String, Value>,
        callback: Option<&dyn DriverCallback>,
        context: Option<&DriverContext>,
    ) -> Result<String> {
        let path = parameters
            .get("path")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("Missing 'path' parameter"))?;
        let extract_text = parameters
            .get("extract_text")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let selector = parameters.get("selector").and_then(|v| v.as_str());

        let validated_path = validate_path(path, None)?;
        if !file_exists(&validated_path.to_string_lossy()) {
            anyhow::bail!("HTML file not found: {}", path);
        }

        let content = read_file_content(&validated_path.to_string_lossy())?;

        if extract_text || selector.is_some() {
            use scraper::{Html, Selector};

            let document = Html::parse_document(&content);

            if let Some(sel_str) = selector {
                let selector = Selector::parse(sel_str)
                    .map_err(|e| anyhow::anyhow!("Invalid CSS selector: {}", e))?;

                let elements: Vec<String> = document
                    .select(&selector)
                    .map(|el| el.text().collect::<String>())
                    .collect();

                if elements.is_empty() {
                    Ok(format!("No elements found matching selector: {}", sel_str))
                } else {
                    let mut output = String::new();
                    for (i, text) in elements.iter().enumerate() {
                        output.push_str(&format!("Element {}: {}\n", i + 1, text));
                    }
                    output.push_str(&format!("\nTotal elements: {}", elements.len()));
                    Ok(output)
                }
            } else if extract_text {
                let text = document
                    .root_element()
                    .text()
                    .collect::<Vec<&str>>()
                    .join(" ");
                Ok(text)
            } else {
                Ok(content)
            }
        } else {
            Ok(content)
        }
    }

    fn validate(&self, parameters: &HashMap<String, Value>) -> Result<()> {
        parameters
            .get("path")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("Missing required parameter: path"))?;
        Ok(())
    }
}

#[derive(Debug)]
pub struct HtmlWriteDriver;

#[async_trait::async_trait]
impl Driver for HtmlWriteDriver {
    fn name(&self) -> &str {
        "html_write"
    }

    fn description(&self) -> &str {
        "Write HTML content to a file"
    }

    fn usage_hint(&self) -> &str {
        "Use this skill when the user wants to create or save an HTML file"
    }

    fn parameters(&self) -> Vec<DriverParameter> {
        vec![
            DriverParameter {
                name: "path".to_string(),
                param_type: "string".to_string(),
                description: "Path to save the HTML file".to_string(),
                required: true,
                default: None,
                example: Some(Value::String("output.html".to_string())),
                enum_values: None,
            },
            DriverParameter {
                name: "content".to_string(),
                param_type: "string".to_string(),
                description: "HTML content to write".to_string(),
                required: true,
                default: None,
                example: Some(Value::String("<html><body>Hello</body></html>".to_string())),
                enum_values: None,
            },
            DriverParameter {
                name: "minify".to_string(),
                param_type: "boolean".to_string(),
                description: "Minify HTML (remove extra whitespace)".to_string(),
                required: false,
                default: Some(Value::Bool(false)),
                example: Some(Value::Bool(true)),
                enum_values: None,
            },
        ]
    }

    fn example_call(&self) -> Value {
        json!({
            "action": "html_write",
            "parameters": {
                "path": "output.html",
                "content": "<html><body>Hello</body></html>"
            }
        })
    }

    fn example_output(&self) -> String {
        "HTML written to: output.html".to_string()
    }

    fn category(&self) -> DriverCategory {
        DriverCategory::Document
    }
    async fn execute(
        &self,
        parameters: &HashMap<String, Value>,
        callback: Option<&dyn DriverCallback>,
        context: Option<&DriverContext>,
    ) -> Result<String> {
        let path = parameters
            .get("path")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("Missing 'path' parameter"))?;
        let content = parameters
            .get("content")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("Missing 'content' parameter"))?;
        let minify = parameters
            .get("minify")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let validated_path = validate_path(path, None)?;
        if let Some(parent) = validated_path.parent() {
            ensure_dir(&parent.to_string_lossy())?;
        }
        let final_content = if minify {
            minify_html(content)
        } else {
            content.to_string()
        };
        write_file_content(&validated_path.to_string_lossy(), &final_content, false)?;
        Ok(format!("HTML written to: {}", path))
    }

    fn validate(&self, parameters: &HashMap<String, Value>) -> Result<()> {
        parameters
            .get("path")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("Missing required parameter: path"))?;
        parameters
            .get("content")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("Missing required parameter: content"))?;
        Ok(())
    }
}

#[derive(Debug)]
pub struct HtmlValidateDriver;

#[async_trait::async_trait]
impl Driver for HtmlValidateDriver {
    fn name(&self) -> &str {
        "html_validate"
    }

    fn description(&self) -> &str {
        "Validate HTML syntax and structure"
    }

    fn usage_hint(&self) -> &str {
        "Use this skill when the user wants to check if an HTML file has valid syntax"
    }

    fn parameters(&self) -> Vec<DriverParameter> {
        vec![DriverParameter {
            name: "path".to_string(),
            param_type: "string".to_string(),
            description: "Path to the HTML file to validate".to_string(),
            required: true,
            default: None,
            example: Some(Value::String("index.html".to_string())),
            enum_values: None,
        }]
    }

    fn example_call(&self) -> Value {
        json!({
            "action": "html_validate",
            "parameters": {
                "path": "index.html"
            }
        })
    }

    fn example_output(&self) -> String {
        "HTML is valid".to_string()
    }

    fn category(&self) -> DriverCategory {
        DriverCategory::Document
    }
    async fn execute(
        &self,
        parameters: &HashMap<String, Value>,
        callback: Option<&dyn DriverCallback>,
        context: Option<&DriverContext>,
    ) -> Result<String> {
        let path = parameters
            .get("path")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("Missing 'path' parameter"))?;
        let validated_path = validate_path(path, None)?;
        if !file_exists(&validated_path.to_string_lossy()) {
            anyhow::bail!("HTML file not found: {}", path);
        }
        let content = read_file_content(&validated_path.to_string_lossy())?;
        use scraper::Html;
        let document = Html::parse_document(&content);
        let has_html = document
            .select(&scraper::Selector::parse("html").unwrap())
            .next()
            .is_some();
        let has_body = document
            .select(&scraper::Selector::parse("body").unwrap())
            .next()
            .is_some();
        let has_head = document
            .select(&scraper::Selector::parse("head").unwrap())
            .next()
            .is_some();
        let mut warnings = Vec::new();
        if !has_html {
            warnings.push("Missing <html> tag");
        }
        if !has_body {
            warnings.push("Missing <body> tag");
        }
        if !has_head {
            warnings.push("Missing <head> tag");
        }
        let mut output = String::from("HTML parsed successfully\n");
        output.push_str(&format!("  Title: {}\n", get_title(&document)));
        if warnings.is_empty() {
            output.push_str("  Structure: Complete\n");
        } else {
            output.push_str("  Warnings:\n");
            for warning in warnings {
                output.push_str(&format!("    - {}\n", warning));
            }
        }
        Ok(output)
    }

    fn validate(&self, parameters: &HashMap<String, Value>) -> Result<()> {
        parameters
            .get("path")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("Missing required parameter: path"))?;
        Ok(())
    }
}

fn minify_html(html: &str) -> String {
    let mut result = String::new();
    let mut in_tag = false;
    let mut in_quote = false;
    let mut quote_char = '\0';
    let mut prev_char = '\0';
    for c in html.chars() {
        if c == '"' || c == '\'' {
            if !in_quote {
                in_quote = true;
                quote_char = c;
            } else if c == quote_char && prev_char != '\\' {
                in_quote = false;
            }
        }
        if c == '<' && !in_quote {
            in_tag = true;
            if !result.is_empty() && result.ends_with(' ') {
                result.pop();
            }
            result.push(c);
        } else if c == '>' && in_tag {
            in_tag = false;
            result.push(c);
            if !result.ends_with('\n') {
                result.push('\n');
            }
        } else if in_tag || in_quote {
            result.push(c);
        } else if !c.is_whitespace() {
            result.push(c);
        } else if !result.is_empty() && !result.ends_with(' ') && !result.ends_with('\n') {
            result.push(' ');
        }
        prev_char = c;
    }
    result
}

fn get_title(document: &scraper::Html) -> String {
    if let Ok(selector) = scraper::Selector::parse("title") {
        if let Some(title_elem) = document.select(&selector).next() {
            return title_elem.text().collect::<String>();
        }
    }
    "No title found".to_string()
}