-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsearch_tool.rs
More file actions
2221 lines (2072 loc) · 78.7 KB
/
Copy pathsearch_tool.rs
File metadata and controls
2221 lines (2072 loc) · 78.7 KB
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// web_search tool: no API key, no JS, no self-host.
//
// Primary → fallback chain (same security model as fetch — honors
// --no-network / fetch_allowlist, reuses html_to_text + egress helpers):
// 1. SearXNG public instances ranked from https://searx.space/data/instances.json
// that expose google+bing; queries pin engines=google,bing (JSON API when
// enabled, else HTML scrape of the simple theme)
// 2. DuckDuckGo Lite (https://lite.duckduckgo.com/lite/)
// 3. DuckDuckGo HTML (https://html.duckduckgo.com/html/)
// 4. Mojeek (https://www.mojeek.com/search)
//
// NO API KEY, NO JavaScript, NO new crate deps. SearXNG instance list is
// cached in-process (~1h). We try a few top-ranked instances serially
// (parallel spray trips rate limits). DDG wraps destinations in `uddg=`
// redirects which we decode by hand (no percent-encoding crate).
//
// This is best-effort, not an SLA: public instances rate-limit / captcha,
// and markup may drift. On block/HTTP failure / empty parse we try the
// next backend. Only if every backend fails do we surface an aggregated
// error; a successful empty SERP reports "no results".
use crate::config::Config;
use crate::fetch_tool::{egress_check, html_to_text};
use crate::tools::{smart_truncate, Outcome};
use regex::Regex;
use serde_json::json;
use serde_json::Value;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{LazyLock, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
const SEARX_SPACE_INSTANCES: &str = "https://searx.space/data/instances.json";
/// How many ranked public instances to try before falling through to DDG.
const SEARX_MAX_INSTANCES: usize = 4;
/// In-process TTL for the ranked instance list.
const SEARX_CACHE_TTL: Duration = Duration::from_secs(3600);
/// Bump when instance filters change so a long-lived process doesn't keep a
/// stale ranked list that ignored the new criteria.
const SEARX_CACHE_GEN: u32 = 2;
/// Engines pinned on every SearXNG query (highest-quality general web results).
const SEARX_ENGINES: &str = "google,bing";
/// Reject an engine whose searx.space-reported error_rate is at or above this.
const SEARX_ENGINE_MAX_ERROR_RATE: f64 = 80.0;
// ---- shared regexes (compiled once) ----
/// DDG Lite: `<a class="result-link" href="...">title</a>`
static DDG_LITE_LINK_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r#"<a\s+class="result-link"\s+href="([^"]+)"[^>]*>([\s\S]*?)</a>"#).unwrap()
});
/// DDG Lite: `<td class="result-snippet">...</td>`
static DDG_LITE_SNIP_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r#"class="result-snippet"[^>]*>([\s\S]*?)</td>"#).unwrap());
/// Loose fallback for any `<a href>` when structured classes drift.
static ANY_LINK_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r#"<a\s+[^>]*href="([^"]+)"[^>]*>([\s\S]*?)</a>"#).unwrap());
/// DDG HTML: `<a class="result__a" href="...">title</a>` (class order may vary).
static DDG_HTML_LINK_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r#"<a\s+[^>]*class="[^"]*result__a[^"]*"[^>]*href="([^"]+)"[^>]*>([\s\S]*?)</a>"#)
.unwrap()
});
/// Alternate attribute order: href before class.
static DDG_HTML_LINK_RE_ALT: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r#"<a\s+[^>]*href="([^"]+)"[^>]*class="[^"]*result__a[^"]*"[^>]*>([\s\S]*?)</a>"#)
.unwrap()
});
/// DDG HTML snippets.
static DDG_HTML_SNIP_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r#"class="[^"]*result__snippet[^"]*"[^>]*>([\s\S]*?)</(?:a|td|span|div)>"#).unwrap()
});
/// Mojeek: `<a class="title" title="url" href="url">Title</a>`
static MOJEEK_TITLE_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r#"<a\s+class="title"[^>]*href="([^"]+)"[^>]*>([\s\S]*?)</a>"#).unwrap()
});
/// Mojeek snippet: `<p class="s">...</p>` (paired by index with titles).
static MOJEEK_SNIP_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r#"<p\s+class="s">([\s\S]*?)</p>"#).unwrap());
/// SearXNG simple theme: one result card.
static SEARX_ARTICLE_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r#"(?is)<article[^>]*class="[^"]*\bresult\b[^"]*"[^>]*>(.*?)</article>"#).unwrap()
});
/// Title link inside a SearXNG result card (h3 > a).
static SEARX_TITLE_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r#"(?is)<h3[^>]*>\s*<a[^>]*href="([^"]+)"[^>]*>(.*?)</a>"#).unwrap()
});
/// Snippet paragraph inside a SearXNG result card.
static SEARX_CONTENT_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r#"(?is)<p[^>]*class="[^"]*\bcontent\b[^"]*"[^>]*>(.*?)</p>"#).unwrap()
});
/// Cached ranked instance URLs from searx.space: (generation, fetched_at, urls).
static SEARX_INSTANCE_CACHE: LazyLock<Mutex<Option<(u32, Instant, Vec<String>)>>> =
LazyLock::new(|| Mutex::new(None));
/// Percent-decode a query-string value (no `percent-encoding` crate dep).
/// Handles `%XX` hex escapes and `+`→space. Malformed `%` sequences are passed
/// through literally rather than panicking.
fn percent_decode(s: &str) -> String {
let bytes = s.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
if let (Some(h), Some(l)) = (hex(bytes[i + 1]), hex(bytes[i + 2])) {
out.push((h << 4) | l);
i += 3;
continue;
}
}
if bytes[i] == b'+' {
out.push(b' ');
} else {
out.push(bytes[i]);
}
i += 1;
}
String::from_utf8_lossy(&out).to_string()
}
fn hex(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
/// DDG wraps each result's destination in a redirect like
/// `//duckduckgo.com/l/?uddg=<encoded>&rut=...`. Extract and decode the real
/// URL. For direct hrefs (no `uddg=`), return the href unchanged (protocol-less
/// `//host/...` is upgraded to `https://`).
fn unwrap_ddg_url(href: &str) -> String {
let href = if let Some(rest) = href.strip_prefix("//") {
format!("https://{rest}")
} else {
href.to_string()
};
if let Some(idx) = href.find("uddg=") {
let after = &href[idx + "uddg=".len()..];
let end = after.find('&').unwrap_or(after.len());
return percent_decode(&after[..end]);
}
href
}
/// Strip tags from a snippet cell and tidy whitespace, reusing the shared
/// html_to_text helper so entities/whitespace are handled consistently with
/// the fetch tool's output.
fn cell_text(s: &str) -> String {
let t = html_to_text(s);
t.trim().to_string()
}
/// A single search hit.
#[derive(Clone, Debug)]
struct Hit {
title: String,
url: String,
snippet: String,
}
/// Which backend produced the hits (shown in the tool output header).
#[derive(Clone, Debug, PartialEq, Eq)]
enum Backend {
Exa,
Tavily,
Searx(String),
DdgLite,
DdgHtml,
Mojeek,
}
impl Backend {
fn label(&self) -> String {
match self {
Backend::Exa => "Exa API".into(),
Backend::Tavily => "Tavily API".into(),
Backend::Searx(host) => format!("SearXNG ({host})"),
Backend::DdgLite => "DuckDuckGo Lite".into(),
Backend::DdgHtml => "DuckDuckGo HTML".into(),
Backend::Mojeek => "Mojeek".into(),
}
}
}
/// Outcome of one backend attempt.
enum Attempt {
/// Parsed ≥1 hit — stop the chain.
Hits(Vec<Hit>),
/// Page looked like a real SERP but had zero results — stop the chain
/// (don't keep searching; the query genuinely has nothing).
Empty,
/// Blocked / HTTP error / markup drift — try the next backend.
Fail(String),
}
/// Shared captcha / anomaly heuristics used by DDG + SearXNG HTML.
fn looks_blocked(html: &str) -> bool {
let low = html.to_ascii_lowercase();
low.contains("captcha")
|| low.contains("unusual traffic")
|| low.contains("are you a robot")
|| low.contains("bots use duckduckgo")
|| low.contains("anomaly-modal")
|| low.contains("please complete the following challenge")
|| low.contains("making sure you're not a bot")
|| low.contains("checking your browser")
|| low.contains("checking if the site connection is secure")
|| low.contains("cf-browser-verification")
|| low.contains("browser verification required")
|| low.contains("just a moment...")
}
/// Map DDG-style `us-en` region to a SearXNG `language` code (`en`).
fn searx_language(region: &str) -> &str {
region
.rsplit_once('-')
.map(|(_, lang)| lang)
.filter(|s| !s.is_empty())
.unwrap_or("en")
}
fn instance_host(base: &str) -> String {
base.trim_end_matches('/')
.strip_prefix("https://")
.or_else(|| base.strip_prefix("http://"))
.unwrap_or(base)
.to_string()
}
/// Return the engine's reported error_rate if it looks usable, else `None`
/// (missing engine, or error_rate too high). An empty `{}` entry means OK (0%).
fn searx_engine_error_rate(engines: &Value, name: &str) -> Option<f64> {
let eng = engines.get(name)?;
// Presence as an object (including `{}`) means the instance lists the engine.
if !eng.is_object() {
return None;
}
let rate = eng
.get("error_rate")
.and_then(|v| v.as_f64())
.unwrap_or(0.0);
if rate >= SEARX_ENGINE_MAX_ERROR_RATE {
return None;
}
Some(rate)
}
/// Score a searx.space instance entry. Higher is better. `None` = skip.
/// Only instances that expose working `google` and `bing` engines qualify.
fn score_searx_instance(meta: &Value) -> Option<f64> {
let network_type = meta.get("network_type").and_then(|v| v.as_str());
if matches!(network_type, Some(t) if t != "normal") {
return None;
}
let http = meta.get("http")?;
if http.get("status_code").and_then(|v| v.as_u64()) != Some(200) {
return None;
}
if http.get("error").map(|e| !e.is_null()).unwrap_or(false) {
return None;
}
let engines = meta.get("engines")?;
let google_err = searx_engine_error_rate(engines, "google")?;
let bing_err = searx_engine_error_rate(engines, "bing")?;
let uptime = meta.get("uptime")?;
let day = uptime.get("uptimeDay")?.as_f64()?;
let week = uptime
.get("uptimeWeek")
.and_then(|v| v.as_f64())
.unwrap_or(day);
let search = meta.get("timing")?.get("search")?;
let success = search.get("success_percentage")?.as_f64()?;
if success < 50.0 {
return None;
}
let median = search
.get("all")
.and_then(|a| a.get("median"))
.and_then(|v| v.as_f64())
.unwrap_or(9.0);
// Prefer high uptime + search success + healthy google/bing, then low latency.
Some(
day * 2.0 + week + success * 3.0 - median * 5.0
+ (100.0 - google_err) * 0.5
+ (100.0 - bing_err) * 0.5,
)
}
/// Parse searx.space `instances.json` into ranked base URLs (https only).
fn rank_searx_instances(doc: &Value) -> Vec<String> {
let Some(map) = doc.get("instances").and_then(|v| v.as_object()) else {
return Vec::new();
};
let mut ranked: Vec<(f64, String)> = Vec::new();
for (url, meta) in map {
if !url.starts_with("https://") {
continue;
}
if let Some(score) = score_searx_instance(meta) {
ranked.push((score, url.trim_end_matches('/').to_string() + "/"));
}
}
ranked.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
ranked.into_iter().map(|(_, u)| u).collect()
}
/// Fetch + cache ranked public SearXNG instances from searx.space.
async fn load_searx_instances(cfg: &Config) -> Result<Vec<String>, String> {
if let Ok(guard) = SEARX_INSTANCE_CACHE.lock() {
if let Some((gen, at, urls)) = guard.as_ref() {
if *gen == SEARX_CACHE_GEN && at.elapsed() < SEARX_CACHE_TTL && !urls.is_empty() {
return Ok(urls.clone());
}
}
}
if let Some(err) = egress_check("web_search", SEARX_SPACE_INSTANCES, cfg) {
return Err(err);
}
let (status, body, _trunc) = fetch_html(
cfg,
SEARX_SPACE_INSTANCES,
// searx.space instances.json is ~1-2MB; the default fetch_max_bytes
// (256KB) truncates it mid-string → "JSON parse failed: EOF at column
// 262144". Floor this one fetch at 8MB so the instance list parses.
cfg.fetch_max_bytes.max(8 * 1024 * 1024),
)
.await?;
if !status.is_success() {
return Err(format!("searx.space returned HTTP {status}"));
}
let doc: Value =
serde_json::from_str(&body).map_err(|e| format!("searx.space JSON parse failed: {e}"))?;
let urls = rank_searx_instances(&doc);
if urls.is_empty() {
return Err(
"searx.space returned no usable online instances with google+bing engines".into(),
);
}
if let Ok(mut guard) = SEARX_INSTANCE_CACHE.lock() {
*guard = Some((SEARX_CACHE_GEN, Instant::now(), urls.clone()));
}
Ok(urls)
}
/// Parse SearXNG `format=json` body into hits.
fn parse_searx_json(body: &str, limit: usize) -> Result<Vec<Hit>, String> {
let doc: Value =
serde_json::from_str(body).map_err(|e| format!("SearXNG JSON parse failed: {e}"))?;
let Some(results) = doc.get("results").and_then(|v| v.as_array()) else {
return Err("SearXNG JSON missing results[]".into());
};
let mut hits = Vec::new();
for r in results {
let url = r
.get("url")
.and_then(|v| v.as_str())
.unwrap_or("")
.trim()
.to_string();
let title = r
.get("title")
.and_then(|v| v.as_str())
.unwrap_or("")
.trim()
.to_string();
let snippet = r
.get("content")
.and_then(|v| v.as_str())
.unwrap_or("")
.trim()
.to_string();
if url.starts_with("http") && !title.is_empty() {
hits.push(Hit {
title,
url,
snippet,
});
if hits.len() >= limit {
break;
}
}
}
Ok(hits)
}
/// Parse SearXNG simple-theme HTML SERP into hits.
fn parse_searx_html(html: &str, limit: usize) -> Vec<Hit> {
let mut hits: Vec<Hit> = Vec::new();
for art in SEARX_ARTICLE_RE.captures_iter(html) {
let block = art.get(1).map(|m| m.as_str()).unwrap_or("");
let Some(cap) = SEARX_TITLE_RE.captures(block) else {
continue;
};
let href = cap.get(1).map(|m| m.as_str()).unwrap_or("").to_string();
let title = cell_text(cap.get(2).map(|m| m.as_str()).unwrap_or(""));
if !href.starts_with("http") || title.is_empty() {
continue;
}
let snippet = SEARX_CONTENT_RE
.captures(block)
.map(|c| cell_text(c.get(1).map(|m| m.as_str()).unwrap_or("")))
.unwrap_or_default();
if hits.iter().any(|h| h.url == href) {
continue;
}
hits.push(Hit {
title,
url: href,
snippet,
});
if hits.len() >= limit {
break;
}
}
hits
}
fn classify_searx_response(
host: &str,
status: reqwest::StatusCode,
body: &str,
content_type: &str,
want_json: bool,
limit: usize,
) -> Attempt {
if status.as_u16() == 429 {
return Attempt::Fail(format!("SearXNG ({host}) rate-limited (HTTP 429)"));
}
if status.as_u16() == 403 {
return Attempt::Fail(format!(
"SearXNG ({host}) forbidden (HTTP 403; JSON often disabled on public instances)"
));
}
if !status.is_success() {
return Attempt::Fail(format!("SearXNG ({host}) returned HTTP {status}"));
}
if looks_blocked(body) {
return Attempt::Fail(format!("SearXNG ({host}) served a bot-check/captcha page"));
}
let ct = content_type.to_ascii_lowercase();
if want_json {
let looks_json = ct.contains("json") || body.trim_start().starts_with('{');
if !looks_json {
return Attempt::Fail(format!(
"SearXNG ({host}) did not return JSON (content-type {content_type:?})"
));
}
return match parse_searx_json(body, limit) {
Ok(hits) if hits.is_empty() => Attempt::Empty,
Ok(hits) => Attempt::Hits(hits),
Err(e) => Attempt::Fail(format!("SearXNG ({host}): {e}")),
};
}
let low = body.to_ascii_lowercase();
let has_markers = low.contains("class=\"result") || low.contains("article class=\"result");
if !has_markers && body.len() < 8 * 1024 {
return Attempt::Fail(format!(
"SearXNG ({host}) returned an unexpected page with no result markers"
));
}
let hits = parse_searx_html(body, limit);
if hits.is_empty() {
if has_markers {
Attempt::Empty
} else {
Attempt::Fail(format!(
"SearXNG ({host}) returned a page that parsed to zero results"
))
}
} else {
Attempt::Hits(hits)
}
}
/// Try ranked public SearXNG instances (JSON first, then HTML per host).
async fn try_searxng(
cfg: &Config,
query: &str,
count: usize,
region: &str,
byte_limit: usize,
failures: &mut Vec<String>,
) -> Option<(Backend, Attempt)> {
let instances = match load_searx_instances(cfg).await {
Ok(v) => v,
Err(e) => {
failures.push(format!("searx.space: {e}"));
return None;
}
};
let q = form_urlencode(query);
let lang = form_urlencode(searx_language(region));
let engines = form_urlencode(SEARX_ENGINES);
// Pin google+bing so we don't get low-quality default engine mixes.
let common = format!("q={q}&language={lang}&engines={engines}&categories=general&pageno=1");
for base in instances.into_iter().take(SEARX_MAX_INSTANCES) {
let host = instance_host(&base);
// JSON attempt (many public instances disable this → 403 → HTML).
let json_url = format!("{base}search?{common}&format=json");
if let Some(err) = egress_check("web_search", &json_url, cfg) {
failures.push(format!("SearXNG ({host}): skipped ({err})"));
continue;
}
match fetch_html_with_ct(cfg, &json_url, byte_limit).await {
Ok((status, body, ct, _trunc)) => {
match classify_searx_response(&host, status, &body, &ct, true, count) {
Attempt::Hits(h) => {
return Some((Backend::Searx(host), Attempt::Hits(h)));
}
Attempt::Empty => {
return Some((Backend::Searx(host), Attempt::Empty));
}
Attempt::Fail(reason) => {
// Fall through to HTML on the same host for JSON disable / drift.
failures.push(reason);
}
}
}
Err(e) => {
failures.push(format!("SearXNG ({host}) JSON: {e}"));
}
}
let html_url = format!("{base}search?{common}");
if let Some(err) = egress_check("web_search", &html_url, cfg) {
failures.push(format!("SearXNG ({host}) HTML: skipped ({err})"));
continue;
}
match fetch_html_with_ct(cfg, &html_url, byte_limit).await {
Ok((status, body, ct, _trunc)) => {
match classify_searx_response(&host, status, &body, &ct, false, count) {
Attempt::Hits(h) => {
return Some((Backend::Searx(host), Attempt::Hits(h)));
}
Attempt::Empty => {
return Some((Backend::Searx(host), Attempt::Empty));
}
Attempt::Fail(reason) => failures.push(reason),
}
}
Err(e) => failures.push(format!("SearXNG ({host}) HTML: {e}")),
}
}
None
}
/// Parse DDG Lite HTML into ordered hits. Returns up to `limit` results.
/// Defensive: if the structured `result-link`/`result-snippet` parse yields
/// nothing (markup drift / captcha), falls back to scraping any `<a href>`
/// whose href looks like a real external result.
fn parse_ddg_lite(html: &str, limit: usize) -> Vec<Hit> {
let titles_urls: Vec<(String, String)> = DDG_LITE_LINK_RE
.captures_iter(html)
.map(|c| {
let href = c.get(1).map(|m| m.as_str()).unwrap_or("");
let title = c.get(2).map(|m| m.as_str()).unwrap_or("");
(cell_text(title), unwrap_ddg_url(href))
})
.filter(|(t, u)| !t.is_empty() && !u.is_empty())
.collect();
let snippets: Vec<String> = DDG_LITE_SNIP_RE
.captures_iter(html)
.map(|c| cell_text(c.get(1).map(|m| m.as_str()).unwrap_or("")))
.collect();
if !titles_urls.is_empty() {
return titles_urls
.iter()
.take(limit)
.enumerate()
.map(|(i, (t, u))| Hit {
title: t.clone(),
url: u.clone(),
snippet: snippets.get(i).cloned().unwrap_or_default(),
})
.collect();
}
// Fallback: scrape external-looking <a href> links. Filters out anchors,
// javascript:, and DDG-internal nav links. This is looser but still useful
// when the structured classes drift.
let mut hits: Vec<Hit> = Vec::new();
for c in ANY_LINK_RE.captures_iter(html) {
let href = c.get(1).map(|m| m.as_str()).unwrap_or("");
let title = cell_text(c.get(2).map(|m| m.as_str()).unwrap_or(""));
if (href.starts_with("http://")
|| (href.starts_with("https://") && !href.contains("duckduckgo.com/l/")))
&& !title.is_empty()
&& !hits.iter().any(|h| h.url == href)
{
hits.push(Hit {
title,
url: href.to_string(),
snippet: String::new(),
});
if hits.len() >= limit {
break;
}
}
}
hits
}
/// Parse DDG HTML (`html.duckduckgo.com/html/`) results: `result__a` +
/// `result__snippet`. Same `uddg=` unwrap as Lite.
fn parse_ddg_html(html: &str, limit: usize) -> Vec<Hit> {
let mut titles_urls: Vec<(String, String)> = DDG_HTML_LINK_RE
.captures_iter(html)
.map(|c| {
let href = c.get(1).map(|m| m.as_str()).unwrap_or("");
let title = c.get(2).map(|m| m.as_str()).unwrap_or("");
(cell_text(title), unwrap_ddg_url(href))
})
.filter(|(t, u)| !t.is_empty() && !u.is_empty())
.collect();
if titles_urls.is_empty() {
titles_urls = DDG_HTML_LINK_RE_ALT
.captures_iter(html)
.map(|c| {
let href = c.get(1).map(|m| m.as_str()).unwrap_or("");
let title = c.get(2).map(|m| m.as_str()).unwrap_or("");
(cell_text(title), unwrap_ddg_url(href))
})
.filter(|(t, u)| !t.is_empty() && !u.is_empty())
.collect();
}
let snippets: Vec<String> = DDG_HTML_SNIP_RE
.captures_iter(html)
.map(|c| cell_text(c.get(1).map(|m| m.as_str()).unwrap_or("")))
.collect();
titles_urls
.iter()
.take(limit)
.enumerate()
.map(|(i, (t, u))| Hit {
title: t.clone(),
url: u.clone(),
snippet: snippets.get(i).cloned().unwrap_or_default(),
})
.collect()
}
/// Parse Mojeek SERP: `a.title` + paired `p.s` snippets. Hrefs are direct
/// (no redirect wrapper).
fn parse_mojeek(html: &str, limit: usize) -> Vec<Hit> {
let titles_urls: Vec<(String, String)> = MOJEEK_TITLE_RE
.captures_iter(html)
.map(|c| {
let href = c.get(1).map(|m| m.as_str()).unwrap_or("").to_string();
let title = cell_text(c.get(2).map(|m| m.as_str()).unwrap_or(""));
(title, href)
})
.filter(|(t, u)| !t.is_empty() && u.starts_with("http"))
.collect();
let snippets: Vec<String> = MOJEEK_SNIP_RE
.captures_iter(html)
.map(|c| cell_text(c.get(1).map(|m| m.as_str()).unwrap_or("")))
.collect();
titles_urls
.iter()
.take(limit)
.enumerate()
.map(|(i, (t, u))| Hit {
title: t.clone(),
url: u.clone(),
snippet: snippets.get(i).cloned().unwrap_or_default(),
})
.collect()
}
/// Classify a fetched body for a scrape backend into Hits / Empty / Fail.
fn classify_response(
backend: &Backend,
status: reqwest::StatusCode,
html: &str,
body_len: usize,
truncated: bool,
limit: usize,
) -> Attempt {
let trunc = if truncated { " [body truncated]" } else { "" };
let label = backend.label();
if !status.is_success() {
return Attempt::Fail(format!("{label} returned HTTP {status}{trunc}"));
}
if looks_blocked(html) {
return Attempt::Fail(format!(
"{label} served a captcha/anomaly page (likely rate-limited){trunc}"
));
}
let low = html.to_ascii_lowercase();
let has_markers = match backend {
// API providers never flow through classify_response (they return parsed
// hits directly); mark as "has markers" so they can't trip the no-markers
// fail path if ever reached defensively.
Backend::Exa | Backend::Tavily => true,
Backend::DdgLite => low.contains("result-link") || low.contains("result-snippet"),
Backend::DdgHtml => {
low.contains("result__a")
|| low.contains("result__snippet")
|| low.contains("web-result")
}
Backend::Mojeek => low.contains("class=\"title\"") || low.contains("class=\"s\""),
Backend::Searx(_) => {
low.contains("class=\"result") || low.contains("article class=\"result")
}
};
// Small page with no result markers → block / markup drift, not "no hits".
if !has_markers && body_len < 8 * 1024 {
return Attempt::Fail(format!(
"{label} returned an unexpected page with no result markers (markup drift or a block){trunc}"
));
}
let hits = match backend {
Backend::Exa | Backend::Tavily => Vec::new(),
Backend::DdgLite => parse_ddg_lite(html, limit),
Backend::DdgHtml => parse_ddg_html(html, limit),
Backend::Mojeek => parse_mojeek(html, limit),
Backend::Searx(_) => parse_searx_html(html, limit),
};
if hits.is_empty() {
// Markers present (or large page) but nothing parsed: treat as empty
// SERP when markers exist; otherwise as a soft fail so the chain continues.
if has_markers {
Attempt::Empty
} else {
Attempt::Fail(format!(
"{label} returned a page that parsed to zero results{trunc}"
))
}
} else {
Attempt::Hits(hits)
}
}
/// GET `url`, stream up to `byte_limit` bytes, return (status, body, truncated).
async fn fetch_html(
cfg: &Config,
url: &str,
byte_limit: usize,
) -> Result<(reqwest::StatusCode, String, bool), String> {
let (status, body, _ct, truncated) = fetch_html_with_ct(cfg, url, byte_limit).await?;
Ok((status, body, truncated))
}
async fn fetch_html_with_ct(
cfg: &Config,
url: &str,
byte_limit: usize,
) -> Result<(reqwest::StatusCode, String, String, bool), String> {
let parsed = reqwest::Url::parse(url).map_err(|e| format!("invalid URL: {e}"))?;
let resp = crate::fetch_tool::send_resolved(parsed, cfg).await?;
let status = resp.status();
let ct = resp
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_string();
use futures_util::StreamExt;
let mut collected = Vec::with_capacity(byte_limit.min(64 * 1024));
let mut truncated = false;
let mut stream = resp.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|e| format!("failed to read body: {e}"))?;
let room = byte_limit.saturating_sub(collected.len());
if chunk.len() <= room {
collected.extend_from_slice(&chunk);
} else {
collected.extend_from_slice(&chunk[..room]);
truncated = true;
break;
}
}
Ok((
status,
String::from_utf8_lossy(&collected).into_owned(),
ct,
truncated,
))
}
fn render_hits(query: &str, backend: &Backend, hits: &[Hit], note: Option<&str>) -> Outcome {
let mut header = format!(
"Search: {query} ({}, {} hit(s)",
backend.label(),
hits.len()
);
if let Some(n) = note {
header.push_str(&format!(" · {n}"));
}
header.push_str(")\n\n");
let mut text = header;
for (i, h) in hits.iter().enumerate() {
text.push_str(&format!(
"{}. {}\n {}\n {}\n\n",
i + 1,
h.title,
h.url,
h.snippet
));
}
const OUT_CAP: usize = 24_576;
if text.len() > OUT_CAP {
text = smart_truncate(&text, OUT_CAP);
}
Outcome::ok(text)
}
// ============================================================================
// Paid API providers (Exa + Tavily) with load balancing + usage tracking.
//
// When EXA_API_KEY and/or TAVILY_API_KEY are set, web_search prefers them
// (structured snippets, higher quality than scraping). With both keys set,
// requests round-robin between the two. Cumulative monthly usage persists to
// ~/.config/catalyst-code/search-usage.json so a restarted session won't blow
// past the free-tier quota (default 1000/mo each; override via
// EXA_MONTHLY_LIMIT / TAVILY_MONTHLY_LIMIT).
//
// On a 429 / quota-exceeded response the provider enters a cooldown (parsed
// from `retry-after`, default 60s) and the OTHER provider is tried. Only if
// every API provider is unavailable / exhausted / failing do we fall through
// to the no-key scrape chain (SearXNG -> DDG -> Mojeek) below -- so web_search
// ALWAYS has a path to results.
//
// Egress: API endpoints go through the same `egress_check` as scrape URLs, so
// `--no-network` + empty allowlist denies them too (consistent). Add the API
// hosts to `fetch_allowlist` to opt them in under a locked-down config.
// ============================================================================
/// A paid API search provider. Keys resolve from env vars; `ALL` order is the
/// deterministic round-robin priority.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ApiProvider {
Exa,
Tavily,
}
impl ApiProvider {
const ALL: [ApiProvider; 2] = [ApiProvider::Exa, ApiProvider::Tavily];
fn env_key(&self) -> &'static str {
match self {
ApiProvider::Exa => "EXA_API_KEY",
ApiProvider::Tavily => "TAVILY_API_KEY",
}
}
fn endpoint(&self) -> &'static str {
match self {
ApiProvider::Exa => "https://api.exa.ai/search",
ApiProvider::Tavily => "https://api.tavily.com/search",
}
}
/// Monthly request/credit budget. Override via env; default = free tier.
fn monthly_limit(&self) -> u64 {
let env = match self {
ApiProvider::Exa => "EXA_MONTHLY_LIMIT",
ApiProvider::Tavily => "TAVILY_MONTHLY_LIMIT",
};
std::env::var(env)
.ok()
.and_then(|s| s.trim().parse::<u64>().ok())
.filter(|&n| n > 0)
.unwrap_or(1000)
}
/// Resolved API key (non-empty). A key set via `/search-key` (persisted in
/// `cfg.search_keys`) wins over the env var, so slash-command keys override.
fn key(&self, cfg: &Config) -> Option<String> {
let name = match self {
ApiProvider::Exa => "exa",
ApiProvider::Tavily => "tavily",
};
if let Some(k) = cfg.search_keys.get(name) {
if !k.is_empty() {
return Some(k.clone());
}
}
std::env::var(self.env_key())
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
fn backend(self) -> Backend {
match self {
ApiProvider::Exa => Backend::Exa,
ApiProvider::Tavily => Backend::Tavily,
}
}
}
/// Persisted monthly usage for one provider (resets when the calendar month
/// rolls over so quotas are month-bound, not lifetime).
#[derive(Clone, Debug, Default)]
struct MonthlyUsage {
/// "YYYY-MM" -- when this differs from the current month, count resets to 0.
month: String,
count: u64,
}
/// In-process usage + cooldown state (loaded lazily from disk on first use).
#[derive(Default)]
struct UsageState {
exa: MonthlyUsage,
tavily: MonthlyUsage,
exa_cooldown_until: Option<Instant>,
tavily_cooldown_until: Option<Instant>,
loaded: bool,
}
static USAGE: LazyLock<Mutex<UsageState>> = LazyLock::new(|| Mutex::new(UsageState::default()));
/// Round-robin cursor: incremented once per search; the starting provider is
/// `cursor % available.len()`, so two available providers strictly alternate.
static ROUND_ROBIN: AtomicU64 = AtomicU64::new(0);
/// Current calendar month as "YYYY-MM" (no chrono dep -- Howard Hinnant's
/// civil-from-days algorithm applied to the Unix epoch second).
fn current_month() -> String {
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
let days = secs.div_euclid(86400);
let z = days + 719468;
let era = if z >= 0 { z } else { z - 146096 } / 146097;
let doe = z - era * 146097;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let m = mp + if mp < 10 { 3 } else { -9 };
let year = if m <= 2 { y + 1 } else { y };
format!("{year:04}-{m:02}")
}
fn usage_file_path() -> Option<PathBuf> {
crate::config::home_dir().map(|h| h.join(".config/catalyst-code/search-usage.json"))
}
/// Lazily load persisted monthly counts into the in-process state (once).
/// A stored month that doesn't match the current month resets the count to 0.
fn load_usage(state: &mut UsageState) {
if state.loaded {
return;
}
state.loaded = true;
let Some(path) = usage_file_path() else {
return;
};
let Ok(content) = std::fs::read_to_string(&path) else {
return;
};
let Ok(doc) = serde_json::from_str::<Value>(&content) else {
return;
};
let month = current_month();
state.exa = read_provider_usage(&doc, "exa", &month);
state.tavily = read_provider_usage(&doc, "tavily", &month);
}
fn read_provider_usage(doc: &Value, name: &str, current: &str) -> MonthlyUsage {
let Some(p) = doc.get(name) else {
return MonthlyUsage::default();
};
let month = p
.get("month")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let count = p.get("count").and_then(|v| v.as_u64()).unwrap_or(0);
if month == current {
MonthlyUsage { month, count }
} else {
// New calendar month -> quota resets.
MonthlyUsage {
month: current.to_string(),
count: 0,
}
}
}