opencrabs 0.5.4

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Recommended: the 40MB prebuilt binary for macOS, Linux and Windows: https://github.com/adolfousier/opencrabs/releases
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
//! Web Search Tool (Unified)
//!
//! Single search entry point that fans out to DuckDuckGo, Exa, Brave, and
//! Serper in parallel, merges results, and returns the best combined set.
//! The agent calls one tool and never thinks about which engine answered.
//!
//! Engines:
//! - **DuckDuckGo** (always available, free, captcha-prone)
//! - **Exa** (free MCP endpoint or direct API with `EXA_API_KEY`)
//! - **Brave** (requires `BRAVE_API_KEY`, registered only when configured)
//! - **Serper** (Google SERP, requires configured key, #1731)
//!
//! DDG captcha detection (HTTP 202 + structural form heuristic) silently
//! drops DDG from the result pool instead of surfacing an error.

use super::brave_search::BraveSearchTool;
use super::error::{Result, ToolError};
use super::exa_search::ExaSearchTool;
use super::serper_search::SerperSearchTool;
use super::r#trait::{Tool, ToolCapability, ToolExecutionContext, ToolResult};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::Arc;

/// Unified web search tool. Fans out to DDG + Exa (+ Brave, + Serper when
/// configured) in parallel and merges results.
#[derive(Default)]
pub struct WebSearchTool {
    exa: Option<Arc<ExaSearchTool>>,
    brave: Option<Arc<BraveSearchTool>>,
    serper: Option<Arc<SerperSearchTool>>,
}

impl WebSearchTool {
    /// Create a unified search tool with optional engine references.
    /// When all are `None`, behaves as DDG-only (backward compat).
    pub fn new(
        exa: Option<Arc<ExaSearchTool>>,
        brave: Option<Arc<BraveSearchTool>>,
        serper: Option<Arc<SerperSearchTool>>,
    ) -> Self {
        Self { exa, brave, serper }
    }

    /// DuckDuckGo search (extracted for parallel fan-out).
    async fn search_ddg(&self, query: &str, max_results: usize) -> Result<ToolResult> {
        let url = format!(
            "https://lite.duckduckgo.com/lite/?q={}",
            urlencoding::encode(query)
        );

        let mut last_err = String::new();
        for (attempt, ua) in DDG_USER_AGENTS.iter().enumerate() {
            let client = reqwest::Client::builder()
                .timeout(std::time::Duration::from_secs(10))
                .user_agent(*ua)
                .build()
                .map_err(|e| ToolError::Execution(format!("Failed to create HTTP client: {e}")))?;

            match client.get(&url).send().await {
                // DDG bot-detection challenge: HTTP 202 is their
                // protocol-level "you're blocked" signal. Stable across
                // deploys. Short-circuit instead of burning UA rotations.
                Ok(response) if response.status().as_u16() == 202 => {
                    return Ok(ToolResult::error(
                        "DuckDuckGo returned a bot-detection challenge (HTTP 202).".to_string(),
                    ));
                }
                Ok(response) if response.status().is_success() => {
                    let html = response.text().await.map_err(|e| {
                        ToolError::Execution(format!("Failed to read response: {e}"))
                    })?;
                    let results = parse_lite_results(&html, max_results);
                    // Zero results + form present = challenge page, not a
                    // genuine empty result. Structural check, no reliance on
                    // internal JS filenames DDG can rename at any time.
                    if results.is_empty() && html.contains("<form") {
                        return Ok(ToolResult::error(
                            "DuckDuckGo returned a captcha/challenge page instead of results."
                                .to_string(),
                        ));
                    }
                    return Ok(ToolResult::success(format_results(query, &results)));
                }
                Ok(response) => {
                    last_err = format!("HTTP {}", response.status());
                    tracing::warn!(
                        "web_search: DuckDuckGo returned {} (UA {}/{}) — rotating User-Agent",
                        response.status(),
                        attempt + 1,
                        DDG_USER_AGENTS.len(),
                    );
                }
                Err(e) => {
                    last_err = e.to_string();
                    tracing::warn!(
                        "web_search: request failed (UA {}/{}): {e}",
                        attempt + 1,
                        DDG_USER_AGENTS.len(),
                    );
                }
            }

            // Brief backoff before the next UA (skipped after the last attempt).
            if attempt + 1 < DDG_USER_AGENTS.len() {
                tokio::time::sleep(std::time::Duration::from_millis(250)).await;
            }
        }

        Ok(ToolResult::error(format!(
            "DuckDuckGo search failed after {} attempts (last error: {last_err}).",
            DDG_USER_AGENTS.len(),
        )))
    }
}

#[derive(Debug, Deserialize, Serialize)]
struct SearchInput {
    /// Search query
    query: String,

    /// Maximum number of results to return
    #[serde(default = "default_max_results")]
    max_results: usize,
}

fn default_max_results() -> usize {
    5
}

// DuckDuckGo HTML search result
#[derive(Debug, Deserialize)]
pub(crate) struct SearchResult {
    pub(crate) title: String,
    pub(crate) url: String,
}

#[async_trait]
impl Tool for WebSearchTool {
    fn name(&self) -> &str {
        "web_search"
    }

    fn description(&self) -> &str {
        "Search the internet for real-time information. Fans out to \
         DuckDuckGo, Exa, Brave, and Serper (Google, when configured) in \
         parallel and returns merged, deduplicated results. \
         \n\nDEFAULT web-research tool — use this for any \"find me info \
         about X\" / \"what's the latest Y\" / \"check the docs for Z\" \
         request unless the user explicitly asks for browser interaction. \
         Always pick a search tool over `browser_navigate` for research. \
         \n\nFor GitHub content (issues, PRs, repos, code search) use the \
         `gh` CLI via `bash` instead — it returns structured JSON and is \
         authenticated."
    }

    fn input_schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Search query (e.g., 'latest Node.js LTS release', 'Rust async programming')"
                },
                "max_results": {
                    "type": "integer",
                    "description": "Maximum number of results to return (default: 5)",
                    "default": 5,
                    "minimum": 1,
                    "maximum": 10
                }
            },
            "required": ["query"]
        })
    }

    fn capabilities(&self) -> Vec<ToolCapability> {
        vec![ToolCapability::Network]
    }

    fn requires_approval(&self) -> bool {
        false // Web search is generally safe (read-only)
    }

    fn validate_input(&self, input: &Value) -> Result<()> {
        let input: SearchInput = serde_json::from_value(input.clone())
            .map_err(|e| ToolError::InvalidInput(format!("Invalid input: {}", e)))?;

        if input.query.trim().is_empty() {
            return Err(ToolError::InvalidInput("Query cannot be empty".to_string()));
        }

        if input.max_results == 0 || input.max_results > 10 {
            return Err(ToolError::InvalidInput(
                "max_results must be between 1 and 10".to_string(),
            ));
        }

        Ok(())
    }

    async fn execute(&self, input: Value, context: &ToolExecutionContext) -> Result<ToolResult> {
        let parsed: SearchInput = serde_json::from_value(input.clone())?;

        // No extra engines configured: DDG-only (backward compat with
        // tool_setup.rs registration before config is loaded).
        if self.exa.is_none() && self.brave.is_none() && self.serper.is_none() {
            return self.search_ddg(&parsed.query, parsed.max_results).await;
        }

        // Fan out to all engines in parallel.
        let ddg_query = parsed.query.clone();
        let ddg_max = parsed.max_results;
        let ddg_fut = self.search_ddg(&ddg_query, ddg_max);

        let exa_input = input.clone();
        let exa_fut = async {
            match &self.exa {
                Some(exa) => Some(exa.execute(exa_input, context).await),
                None => None,
            }
        };

        let brave_input = input.clone();
        let brave_fut = async {
            match &self.brave {
                Some(brave) => Some(brave.execute(brave_input, context).await),
                None => None,
            }
        };

        let serper_input = input.clone();
        let serper_fut = async {
            match &self.serper {
                Some(serper) => Some(serper.execute(serper_input, context).await),
                None => None,
            }
        };

        let (ddg_res, exa_res, brave_res, serper_res) =
            tokio::join!(ddg_fut, exa_fut, brave_fut, serper_fut);

        // Collect successful outputs. DDG errors (captcha, rate limit)
        // are silently dropped; the other engines fill the gap.
        let mut sections: Vec<String> = Vec::new();

        match ddg_res {
            Ok(ref r) if r.success => sections.push(r.output.clone()),
            Ok(r) => {
                tracing::debug!("web_search: DDG dropped: {}", r.output);
            }
            Err(e) => {
                tracing::debug!("web_search: DDG failed: {e}");
            }
        }

        if let Some(Ok(r)) = exa_res
            && r.success
        {
            sections.push(r.output);
        }

        if let Some(Ok(r)) = brave_res
            && r.success
        {
            sections.push(r.output);
        }

        if let Some(Ok(r)) = serper_res
            && r.success
        {
            sections.push(r.output);
        }

        if sections.is_empty() {
            return Ok(ToolResult::error(
                "All search engines failed or returned no results. \
                 Try rephrasing the query or using http_request against a search API."
                    .to_string(),
            ));
        }

        Ok(ToolResult::success(dedup_sections(sections)))
    }
}

/// Entry line of a rendered search result that carries its URL. Covers both
/// render formats in this module: Brave/Serper `   URL: https://...` and
/// DuckDuckGo `   🔗 https://...`.
fn entry_url(line: &str) -> Option<&str> {
    let trimmed = line.trim_start();
    let rest = trimmed
        .strip_prefix("URL:")
        .or_else(|| trimmed.strip_prefix("🔗"))?;
    let url = rest.trim();
    (url.starts_with("http://") || url.starts_with("https://")).then_some(url)
}

/// First line of a rendered result entry: `1. Title` / `10. Title`.
fn is_entry_start(line: &str) -> bool {
    let trimmed = line.trim_start();
    match trimmed.split_once(". ") {
        Some((num, _)) => !num.is_empty() && num.chars().all(|c| c.is_ascii_digit()),
        None => false,
    }
}

/// Canonical form for dup comparison: case-insensitive, trailing slash
///-insensitive. Intentionally not full URL canonicalization.
fn normalize_url(url: &str) -> String {
    url.trim_end_matches('/').to_lowercase()
}

/// Merge engine sections, dropping later result entries whose URL was already
/// returned by an earlier engine (#1731). Google, Brave, and DDG overlap hard
/// on popular queries, and the merged output used to repeat the same hit once
/// per engine. First occurrence wins, so engine priority order is preserved.
/// Entries without a recognizable URL line (unknown render format) are kept
/// verbatim, and a section reduced to header-only by dedup is dropped whole.
pub(crate) fn dedup_sections(sections: Vec<String>) -> String {
    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut merged: Vec<String> = Vec::new();

    for section in sections {
        // Was this section rendered in the numbered-entry format at all?
        // Sections in an unknown format (no `N.` lines) pass through
        // untouched; only entry-based sections can be reduced to
        // header-only by dedup.
        let entry_based = section.lines().any(is_entry_start);
        let mut out: Vec<String> = Vec::new();
        let mut entry_start: Option<usize> = None;
        let mut dropping = false;
        let mut mutated = false;

        for line in section.lines() {
            if is_entry_start(line) {
                dropping = false;
                entry_start = Some(out.len());
            }
            if !dropping
                && let Some(url) = entry_url(line)
                && !seen.insert(normalize_url(url))
            {
                // Duplicate: unwind this entry's already-pushed lines
                // (its title came before the URL line) and skip its tail.
                if let Some(start) = entry_start {
                    out.truncate(start);
                }
                dropping = true;
                mutated = true;
            }
            if !dropping {
                out.push(line.to_string());
            }
        }

        // Keep the section if an entry survived dedup, or if it never was
        // entry-based (unknown render format). A section reduced to
        // header-only (every entry was a duplicate) is dropped whole.
        if !entry_based || out.iter().any(|l| is_entry_start(l)) {
            // Untouched sections pass through byte-verbatim; only a
            // section that lost entries is rebuilt from surviving lines.
            merged.push(if mutated { out.join("\n") } else { section });
        }
    }

    merged.join("\n\n")
}

/// Rotated User-Agent pool for DuckDuckGo Lite (#525). DDG blocks repetitive UA
/// patterns from one IP, so trying a few realistic browser UAs recovers most
/// transient 403s.
pub(crate) const DDG_USER_AGENTS: &[&str] = &[
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.3 Safari/605.1.15",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:123.0) Gecko/20100101 Firefox/123.0",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
];

/// Format parsed search results into the tool's human-readable output.
pub(crate) fn format_results(query: &str, results: &[SearchResult]) -> String {
    let mut output = String::new();
    output.push_str(&format!("🔍 Search results for: \"{query}\"\n\n"));
    if results.is_empty() {
        output.push_str("ℹ️  No results found. Try:\n");
        output.push_str("  • Rephrasing your query\n");
        output.push_str("  • Using more specific keywords\n");
        output.push_str("  • Searching for a different topic\n");
    } else {
        for (i, result) in results.iter().enumerate() {
            output.push_str(&format!("{}. {}\n", i + 1, result.title));
            output.push_str(&format!("   🔗 {}\n\n", result.url));
        }
    }
    output
}

/// Parse DuckDuckGo Lite HTML response to extract search results
pub(crate) fn parse_lite_results(html: &str, max_results: usize) -> Vec<SearchResult> {
    let mut results = Vec::new();

    // Find result links in the HTML
    // DDG Lite uses <a> tags with class "result-link" for search results
    let link_regex =
        regex::Regex::new(r#"<a[^>]*class="result-link"[^>]*href="([^"]*)"[^>]*>([^<]*)</a>"#)
            .unwrap_or_else(|_| {
                regex::Regex::new(r#"<a[^>]*href="([^"]*)"[^>]*>([^<]*)</a>"#).unwrap()
            });

    for cap in link_regex.captures_iter(html) {
        if results.len() >= max_results {
            break;
        }

        let url = cap
            .get(1)
            .map(|m| m.as_str().to_string())
            .unwrap_or_default();
        let title = cap
            .get(2)
            .map(|m| m.as_str().to_string())
            .unwrap_or_default();

        // Skip non-http links and empty titles
        if url.starts_with("http") && !title.trim().is_empty() {
            results.push(SearchResult { title, url });
        }
    }

    // Fallback: if no results found with class="result-link", try generic link parsing
    if results.is_empty() {
        let generic_regex =
            regex::Regex::new(r#"<a[^>]*href="(https?://[^"]*)"[^>]*>([^<]{10,})</a>"#).unwrap();

        for cap in generic_regex.captures_iter(html) {
            if results.len() >= max_results {
                break;
            }

            let url = cap
                .get(1)
                .map(|m| m.as_str().to_string())
                .unwrap_or_default();
            let title = cap
                .get(2)
                .map(|m| m.as_str().to_string())
                .unwrap_or_default();

            // Skip duckduckgo own links
            if !url.contains("duckduckgo.com") && !title.trim().is_empty() {
                results.push(SearchResult { title, url });
            }
        }
    }

    results
}