car-inference 0.26.0

Local model inference for CAR — Candle backend with Qwen3 models
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
//! Web search capability — the `search` tool, fulfilled natively.
//!
//! CAR ships a `search` ToolSchema (car-ir builtins) that agents can declare,
//! but until now nothing implemented it. This module backs it from two sources,
//! resolved automatically (see [`resolve_provider`]):
//!
//! - **Parslee** — when a Parslee session is present (`PARSLEE_ACCESS_TOKEN`).
//!   Calls Parslee's hosted search (`POST {base}/api/v1/orgs/{org}/search`),
//!   which is Tavily under the hood with org/billing wrapping. No user key
//!   needed; Parslee users get search through their account.
//! - **Tavily (bring-your-own-key)** — when `TAVILY_API_KEY` is set. Calls
//!   `POST https://api.tavily.com/search` directly.
//!
//! Both return the same [`WebSearchResponse`] shape (mirrors Parslee's
//! `WebSearchResult`: title/url/snippet/score/published_date). The HTTP calls
//! are the only impure part; the JSON→struct mapping is pure and unit-tested.

use serde::{Deserialize, Serialize};

/// Tavily's hard cap on results per query (search_depth=basic).
const MAX_RESULTS_CAP: u32 = 20;
const DEFAULT_MAX_RESULTS: u32 = 5;
const TAVILY_ENDPOINT: &str = "https://api.tavily.com/search";
const TAVILY_API_KEY_ENV: &str = "TAVILY_API_KEY";
const PARSLEE_API_BASE_ENV: &str = "PARSLEE_API_BASE";
const PARSLEE_DEFAULT_BASE: &str = "https://api.parslee.ai";
const HTTP_TIMEOUT_SECS: u64 = 20;

/// One web-search hit. Shape mirrors Parslee's `WebSearchResult` so the two
/// sources are interchangeable to callers.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct WebSearchResult {
    pub title: String,
    pub url: String,
    /// The result excerpt (Tavily calls this `content`; Parslee `snippet`).
    pub snippet: String,
    /// Relevance score in [0,1] when the provider reports it.
    #[serde(default)]
    pub score: f64,
    /// Publication date as the provider reports it (ISO-ish string), if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub published_date: Option<String>,
}

/// A web-search response: the echoed query, the results, and which backend
/// served it (`"tavily"` or `"parslee"`).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct WebSearchResponse {
    pub query: String,
    pub results: Vec<WebSearchResult>,
    pub source: String,
}

/// Parameters for the `search` capability (matches the `search` ToolSchema).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchRequest {
    pub query: String,
    /// 1..=20; defaults to 5 when omitted.
    #[serde(default)]
    pub max_results: Option<u32>,
}

#[derive(Debug, thiserror::Error)]
pub enum SearchError {
    #[error("web search HTTP error: {0}")]
    Http(String),
    #[error("web search parse error: {0}")]
    Parse(String),
}

/// Which backend serves a search, resolved from the environment.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SearchProvider {
    /// Parslee hosted search (bearer token; no user key needed).
    Parslee { base: String, token: String },
    /// Tavily direct, with the user's own key.
    Tavily { api_key: String },
    /// Keyless fallback: DuckDuckGo's no-JS HTML endpoint, scraped over plain
    /// HTTP. Zero-config (no account, no key) so search always works; lower
    /// quality + more fragile than the keyed backends. (car-releases#59 asked
    /// for a no-key `browser_run` fallback; this is the same goal via a plain
    /// HTTP fetch — no Chromium — which is lighter and lives in this layer.)
    DuckDuckGo,
}

/// Pick the search backend: Parslee session first (no key needed for the
/// signed-in user), else a bring-your-own Tavily key, else the keyless
/// DuckDuckGo fallback so search works with zero configuration.
pub async fn resolve_provider() -> SearchProvider {
    // Mint a proactively-refreshed bearer (#318) — the sibling chat path was
    // already fixed in #313 but the search path still read the raw token and
    // 401'd on a lapsed session. `access_token_refreshing` is env-first, so
    // the `PARSLEE_ACCESS_TOKEN` override still wins and is never refreshed.
    if let Some(token) = car_auth::access_token_refreshing()
        .await
        .filter(|t| !t.is_empty())
    {
        let base = std::env::var(PARSLEE_API_BASE_ENV)
            .ok()
            .filter(|b| !b.is_empty())
            .or_else(|| car_secrets::resolve_env_or_keychain(PARSLEE_API_BASE_ENV))
            .unwrap_or_else(|| PARSLEE_DEFAULT_BASE.to_string());
        return SearchProvider::Parslee { base, token };
    }
    if let Some(api_key) =
        car_secrets::resolve_env_or_keychain(TAVILY_API_KEY_ENV).filter(|k| !k.is_empty())
    {
        return SearchProvider::Tavily { api_key };
    }
    SearchProvider::DuckDuckGo
}

fn clamp_max(max_results: Option<u32>) -> u32 {
    max_results.unwrap_or(DEFAULT_MAX_RESULTS).clamp(1, MAX_RESULTS_CAP)
}

fn http_client() -> Result<reqwest::Client, SearchError> {
    reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(HTTP_TIMEOUT_SECS))
        .build()
        .map_err(|e| SearchError::Http(e.to_string()))
}

/// Run a web search, auto-resolving the backend. The entry point the `search`
/// capability calls.
pub async fn web_search(
    query: &str,
    max_results: Option<u32>,
) -> Result<WebSearchResponse, SearchError> {
    let max = clamp_max(max_results);
    match resolve_provider().await {
        SearchProvider::Parslee { base, token } => parslee_search(query, max, &base, &token).await,
        SearchProvider::Tavily { api_key } => tavily_search(query, max, &api_key).await,
        SearchProvider::DuckDuckGo => ddg_search(query, max).await,
    }
}

/// Tavily direct (BYO key). `POST https://api.tavily.com/search`.
pub async fn tavily_search(
    query: &str,
    max_results: u32,
    api_key: &str,
) -> Result<WebSearchResponse, SearchError> {
    let body = serde_json::json!({
        "api_key": api_key,
        "query": query,
        "max_results": max_results,
        "search_depth": "basic",
        "include_answer": false,
        "include_raw_content": false,
        "include_images": false,
    });
    let resp = http_client()?
        .post(TAVILY_ENDPOINT)
        .json(&body)
        .send()
        .await
        .map_err(|e| SearchError::Http(format!("tavily: {e}")))?;
    if !resp.status().is_success() {
        return Err(SearchError::Http(format!("tavily: HTTP {}", resp.status())));
    }
    let json: serde_json::Value = resp
        .json()
        .await
        .map_err(|e| SearchError::Parse(format!("tavily: {e}")))?;
    Ok(parse_tavily(query, &json))
}

/// Parslee hosted search. Resolves the org for the bearer, then
/// `POST {base}/api/v1/orgs/{org}/search`.
pub async fn parslee_search(
    query: &str,
    max_results: u32,
    base: &str,
    token: &str,
) -> Result<WebSearchResponse, SearchError> {
    let client = http_client()?;
    let base = base.trim_end_matches('/');
    let org_id = parslee_org_id(&client, base, token).await?;
    let url = format!("{base}/api/v1/orgs/{org_id}/search");
    let body = serde_json::json!({ "query": query, "maxResults": max_results });
    let resp = client
        .post(&url)
        .bearer_auth(token)
        .json(&body)
        .send()
        .await
        .map_err(|e| SearchError::Http(format!("parslee search: {e}")))?;
    if !resp.status().is_success() {
        return Err(SearchError::Http(format!(
            "parslee search: HTTP {}",
            resp.status()
        )));
    }
    let json: serde_json::Value = resp
        .json()
        .await
        .map_err(|e| SearchError::Parse(format!("parslee search: {e}")))?;
    Ok(parse_parslee(query, &json))
}

/// Resolve the Parslee org id for a bearer via `/api/v1/organizations/me`
/// (mirrors the inference path in `remote.rs`).
async fn parslee_org_id(
    client: &reqwest::Client,
    base: &str,
    token: &str,
) -> Result<String, SearchError> {
    let resp = client
        .get(format!("{base}/api/v1/organizations/me"))
        .bearer_auth(token)
        .send()
        .await
        .map_err(|e| SearchError::Http(format!("parslee org lookup: {e}")))?;
    if !resp.status().is_success() {
        return Err(SearchError::Http(format!(
            "parslee org lookup: HTTP {}",
            resp.status()
        )));
    }
    let json: serde_json::Value = resp
        .json()
        .await
        .map_err(|e| SearchError::Parse(format!("parslee org: {e}")))?;
    json.get("organizationId")
        .or_else(|| json.get("OrganizationId"))
        .and_then(|v| v.as_str())
        .map(String::from)
        .ok_or_else(|| {
            SearchError::Parse(
                "parslee org response has no organizationId (finish onboarding)".to_string(),
            )
        })
}

/// Pure: map a Tavily `/search` JSON body to [`WebSearchResponse`]. Tavily's
/// `content` becomes our `snippet`; results without a url are dropped.
fn parse_tavily(query: &str, json: &serde_json::Value) -> WebSearchResponse {
    let results = json
        .get("results")
        .and_then(|r| r.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|r| {
                    let url = r.get("url").and_then(|v| v.as_str())?.to_string();
                    if url.is_empty() {
                        return None;
                    }
                    Some(WebSearchResult {
                        title: r.get("title").and_then(|v| v.as_str()).unwrap_or("").to_string(),
                        url,
                        snippet: r
                            .get("content")
                            .and_then(|v| v.as_str())
                            .unwrap_or("")
                            .to_string(),
                        score: r.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0),
                        published_date: r
                            .get("published_date")
                            .and_then(|v| v.as_str())
                            .map(String::from),
                    })
                })
                .collect()
        })
        .unwrap_or_default();
    WebSearchResponse {
        query: query.to_string(),
        results,
        source: "tavily".to_string(),
    }
}

/// Pure: map Parslee's `/search` JSON body to [`WebSearchResponse`]. Parslee
/// already returns `snippet`/`publishedDate`; results without a url are dropped.
fn parse_parslee(query: &str, json: &serde_json::Value) -> WebSearchResponse {
    let results = json
        .get("results")
        .and_then(|r| r.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|r| {
                    let url = r.get("url").and_then(|v| v.as_str())?.to_string();
                    if url.is_empty() {
                        return None;
                    }
                    Some(WebSearchResult {
                        title: r.get("title").and_then(|v| v.as_str()).unwrap_or("").to_string(),
                        url,
                        snippet: r
                            .get("snippet")
                            .and_then(|v| v.as_str())
                            .unwrap_or("")
                            .to_string(),
                        score: r.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0),
                        published_date: r
                            .get("publishedDate")
                            .and_then(|v| v.as_str())
                            .map(String::from),
                    })
                })
                .collect()
        })
        .unwrap_or_default();
    WebSearchResponse {
        query: query.to_string(),
        results,
        source: "parslee".to_string(),
    }
}

const DDG_HTML_ENDPOINT: &str = "https://html.duckduckgo.com/html/";
const USER_AGENT: &str = "Mozilla/5.0 (compatible; CAR/1.0; +https://parslee.ai)";

/// Keyless search via DuckDuckGo's no-JS HTML endpoint, scraped over plain
/// HTTP. The zero-config fallback (no key, no account). Best-effort: the SERP
/// markup can change and there's no relevance score.
pub async fn ddg_search(query: &str, max_results: u32) -> Result<WebSearchResponse, SearchError> {
    let resp = http_client()?
        .get(DDG_HTML_ENDPOINT)
        .query(&[("q", query)])
        .header(reqwest::header::USER_AGENT, USER_AGENT)
        .send()
        .await
        .map_err(|e| SearchError::Http(format!("duckduckgo: {e}")))?;
    if !resp.status().is_success() {
        return Err(SearchError::Http(format!(
            "duckduckgo: HTTP {}",
            resp.status()
        )));
    }
    let html = resp
        .text()
        .await
        .map_err(|e| SearchError::Parse(format!("duckduckgo: {e}")))?;
    Ok(parse_ddg(query, &html, max_results))
}

/// Pure: parse a DuckDuckGo HTML SERP into results. Result links are DDG
/// redirects (`//duckduckgo.com/l/?uddg=<real-url>`); we unwrap the real url.
fn parse_ddg(query: &str, html: &str, max_results: u32) -> WebSearchResponse {
    use scraper::{Html, Selector};
    let doc = Html::parse_document(html);
    let result_sel = Selector::parse("div.result, div.web-result").unwrap();
    let a_sel = Selector::parse("a.result__a").unwrap();
    let snippet_sel = Selector::parse("a.result__snippet, .result__snippet").unwrap();
    let mut results = Vec::new();
    for el in doc.select(&result_sel) {
        if results.len() >= max_results as usize {
            break;
        }
        let Some(a) = el.select(&a_sel).next() else {
            continue;
        };
        let url = ddg_unwrap_href(a.value().attr("href").unwrap_or(""));
        if url.is_empty() {
            continue;
        }
        let title = a.text().collect::<String>().split_whitespace().collect::<Vec<_>>().join(" ");
        let snippet = el
            .select(&snippet_sel)
            .next()
            .map(|s| s.text().collect::<String>().split_whitespace().collect::<Vec<_>>().join(" "))
            .unwrap_or_default();
        results.push(WebSearchResult {
            title,
            url,
            snippet,
            score: 0.0,
            published_date: None,
        });
    }
    WebSearchResponse {
        query: query.to_string(),
        results,
        source: "duckduckgo".to_string(),
    }
}

/// Unwrap a DuckDuckGo result href to the real destination url. Direct urls
/// pass through; `//duckduckgo.com/l/?uddg=<encoded>` carries the target in
/// the (percent-decoded) `uddg` query param.
fn ddg_unwrap_href(href: &str) -> String {
    if href.starts_with("http://") || href.starts_with("https://") {
        return href.to_string();
    }
    let abs = if let Some(rest) = href.strip_prefix("//") {
        format!("https://{rest}")
    } else {
        return String::new();
    };
    reqwest::Url::parse(&abs)
        .ok()
        .and_then(|u| {
            u.query_pairs()
                .find(|(k, _)| k == "uddg")
                .map(|(_, v)| v.into_owned())
        })
        .unwrap_or_default()
}

/// A fetched web page: final url, status, content type, extracted title + text.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct WebFetchResponse {
    pub url: String,
    pub status: u16,
    pub content_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    pub text: String,
}

/// Parameters for the `web_fetch` capability.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FetchRequest {
    pub url: String,
}

/// Fetch a URL and extract readable text. Keyless (plain HTTP GET). HTML is
/// reduced to title + visible text (scripts/styles dropped); non-HTML bodies
/// are returned verbatim. Best-effort extraction — good enough for an LLM to
/// read, not a full readability engine.
pub async fn web_fetch(url: &str) -> Result<WebFetchResponse, SearchError> {
    let resp = http_client()?
        .get(url)
        .header(reqwest::header::USER_AGENT, USER_AGENT)
        .send()
        .await
        .map_err(|e| SearchError::Http(format!("fetch: {e}")))?;
    let status = resp.status().as_u16();
    let final_url = resp.url().to_string();
    let content_type = resp
        .headers()
        .get(reqwest::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("")
        .to_string();
    let body = resp
        .text()
        .await
        .map_err(|e| SearchError::Parse(format!("fetch body: {e}")))?;
    let (title, text) = if content_type.contains("html") || looks_like_html(&body) {
        (extract_title(&body), html_to_text(&body))
    } else {
        (None, body)
    };
    Ok(WebFetchResponse {
        url: final_url,
        status,
        content_type,
        title,
        text,
    })
}

fn looks_like_html(body: &str) -> bool {
    let head = body.get(..512).unwrap_or(body).to_ascii_lowercase();
    head.contains("<!doctype html") || head.contains("<html") || head.contains("<body")
}

/// Pure: extract the `<title>` text from HTML, if any.
fn extract_title(html: &str) -> Option<String> {
    use scraper::{Html, Selector};
    let doc = Html::parse_document(html);
    let sel = Selector::parse("title").ok()?;
    doc.select(&sel)
        .next()
        .map(|t| t.text().collect::<String>().split_whitespace().collect::<Vec<_>>().join(" "))
        .filter(|s| !s.is_empty())
}

/// Pure: reduce HTML to readable text. Collects text from content-bearing
/// elements (so `<script>`/`<style>` are excluded), falling back to body text
/// for div-only pages.
fn html_to_text(html: &str) -> String {
    use scraper::{Html, Selector};
    let doc = Html::parse_document(html);
    let content = Selector::parse(
        "p, li, h1, h2, h3, h4, h5, h6, blockquote, td, th, caption, figcaption, dd, dt, pre",
    )
    .unwrap();
    let parts: Vec<String> = doc
        .select(&content)
        .filter_map(|el| {
            let t = el.text().collect::<String>().split_whitespace().collect::<Vec<_>>().join(" ");
            (!t.is_empty()).then_some(t)
        })
        .collect();
    let joined = parts.join("\n");
    if !joined.is_empty() {
        // Content extraction excludes <script>/<style>; prefer it whenever it
        // found anything.
        return joined;
    }
    // Fallback only for pages with no semantic content elements at all (rare,
    // div-only markup). Best-effort — may include some non-content text.
    Selector::parse("body")
        .ok()
        .and_then(|b| doc.select(&b).next())
        .map(|b| b.text().collect::<String>().split_whitespace().collect::<Vec<_>>().join(" "))
        .unwrap_or(joined)
}

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

    #[test]
    fn clamp_max_results() {
        assert_eq!(clamp_max(None), DEFAULT_MAX_RESULTS);
        assert_eq!(clamp_max(Some(0)), 1);
        assert_eq!(clamp_max(Some(7)), 7);
        assert_eq!(clamp_max(Some(999)), MAX_RESULTS_CAP);
    }

    #[test]
    fn parses_tavily_shape_content_to_snippet() {
        let json = serde_json::json!({
            "query": "rust async",
            "results": [
                { "title": "Async Rust", "url": "https://ex.com/a", "content": "tokio…",
                  "score": 0.92, "published_date": "2026-01-02" },
                { "title": "no url dropped", "url": "", "content": "x" }
            ],
            "response_time": 1.2
        });
        let r = parse_tavily("rust async", &json);
        assert_eq!(r.source, "tavily");
        assert_eq!(r.results.len(), 1, "empty-url result dropped");
        assert_eq!(r.results[0].url, "https://ex.com/a");
        assert_eq!(r.results[0].snippet, "tokio…", "content → snippet");
        assert_eq!(r.results[0].published_date.as_deref(), Some("2026-01-02"));
        assert!((r.results[0].score - 0.92).abs() < 1e-9);
    }

    #[test]
    fn parses_parslee_shape() {
        let json = serde_json::json!({
            "query": "q",
            "results": [
                { "title": "T", "url": "https://ex.com/p", "snippet": "snip",
                  "score": 0.5, "publishedDate": "2026-06-13T00:00:00" }
            ],
            "source": "Tavily"
        });
        let r = parse_parslee("q", &json);
        assert_eq!(r.source, "parslee");
        assert_eq!(r.results.len(), 1);
        assert_eq!(r.results[0].snippet, "snip");
        assert_eq!(
            r.results[0].published_date.as_deref(),
            Some("2026-06-13T00:00:00")
        );
    }

    #[test]
    fn missing_results_is_empty_not_error() {
        let r = parse_tavily("q", &serde_json::json!({}));
        assert!(r.results.is_empty());
    }

    #[test]
    fn resolver_floors_at_duckduckgo() {
        // With no Parslee token and no Tavily key, search still works via the
        // keyless DDG fallback (zero-config). We can't guarantee the env is
        // clean here, but the fallback variant must be reachable.
        // (Just assert the type is constructible / matchable.)
        let p = SearchProvider::DuckDuckGo;
        assert!(matches!(p, SearchProvider::DuckDuckGo));
    }

    #[test]
    fn ddg_unwrap_redirect_and_direct() {
        // DDG redirect → real url (percent-decoded uddg param).
        let real = ddg_unwrap_href(
            "//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2Fa%3Fx%3D1&rut=abc",
        );
        assert_eq!(real, "https://example.com/a?x=1");
        // Direct url passes through.
        assert_eq!(ddg_unwrap_href("https://ex.com/b"), "https://ex.com/b");
        // Junk → empty (dropped by the caller).
        assert_eq!(ddg_unwrap_href("/about"), "");
    }

    #[test]
    fn parse_ddg_extracts_results() {
        let html = r#"
        <div class="result web-result">
          <a class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fr.com%2F1">First &amp; Best</a>
          <a class="result__snippet">A snippet here.</a>
        </div>
        <div class="result">
          <a class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fr.com%2F2">Second</a>
        </div>"#;
        let r = parse_ddg("q", html, 10);
        assert_eq!(r.source, "duckduckgo");
        assert_eq!(r.results.len(), 2);
        assert_eq!(r.results[0].url, "https://r.com/1");
        assert_eq!(r.results[0].title, "First & Best");
        assert_eq!(r.results[0].snippet, "A snippet here.");
        assert_eq!(r.results[1].url, "https://r.com/2");
        // max_results caps.
        assert_eq!(parse_ddg("q", html, 1).results.len(), 1);
    }

    #[test]
    fn html_to_text_drops_script_keeps_content() {
        let html = r#"<html><head><title> Hi — Page </title><style>.x{}</style></head>
            <body><script>var leak='SECRET';</script>
            <h1>Heading</h1><p>Para one.</p><p>Para two.</p></body></html>"#;
        assert_eq!(extract_title(html).as_deref(), Some("Hi — Page"));
        let text = html_to_text(html);
        assert!(text.contains("Heading"));
        assert!(text.contains("Para one."));
        assert!(text.contains("Para two."));
        assert!(!text.contains("SECRET"), "script text must be excluded: {text}");
    }

    #[test]
    fn looks_like_html_detects() {
        assert!(looks_like_html("<!DOCTYPE html><html>…"));
        assert!(looks_like_html("<html lang=en>"));
        assert!(!looks_like_html("{\"json\": true}"));
    }

    // --- Parslee search HTTP path (wiremock). Exercises the real
    // org-lookup → search request/parse chain, including the 401 surface
    // that #318 was about (a lapsed token). ---

    #[tokio::test]
    async fn parslee_search_resolves_org_then_returns_results() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/organizations/me"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "organizationId": "org_test"
                })),
            )
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/api/v1/orgs/org_test/search"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "results": [
                    { "title": "T", "url": "https://example.com", "snippet": "S", "score": 0.9 }
                ]
            })))
            .mount(&server)
            .await;

        let resp = parslee_search("q", 5, &server.uri(), "bearer-xyz")
            .await
            .expect("search should succeed");
        assert_eq!(resp.source, "parslee");
        assert_eq!(resp.results.len(), 1);
        assert_eq!(resp.results[0].url, "https://example.com");
    }

    #[tokio::test]
    async fn parslee_search_surfaces_401_on_org_lookup() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/api/v1/organizations/me"))
            .respond_with(ResponseTemplate::new(401))
            .mount(&server)
            .await;

        let err = parslee_search("q", 5, &server.uri(), "stale-token")
            .await
            .expect_err("a 401 org lookup must surface as an error");
        match err {
            SearchError::Http(m) => assert!(m.contains("HTTP 401"), "got: {m}"),
            other => panic!("expected Http(401), got {other:?}"),
        }
    }
}