mermaid-cli 0.18.0

Open-source AI pair programmer with agentic capabilities. Local-first with Ollama, native tool calling, and beautiful TUI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
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
//! Web tools: `web_search` and `web_fetch`.
//!
//! Each tool holds a pluggable backend (`web_client::SearchProvider` /
//! `FetchProvider`) selected from `[web]` config: `web_fetch` defaults to a
//! native in-process fetch (no key), `web_search` to Ollama Cloud or a
//! self-hosted SearXNG. This tool layer owns cancellation plumbing, the SSRF
//! guard, and multi-query fan-out; the backend owns the transport.

use std::sync::Arc;

use async_trait::async_trait;

use crate::app::{FetchBackend, SearchBackend, WebConfig};
use crate::domain::{ToolDefinition, ToolMetadata, ToolOutcome, ToolRunMetadata};

use super::super::ctx::{ExecContext, ProgressEvent};
use super::ToolExecutor;
use super::web_client::{
    FetchProvider, ManagedSearxngBackend, NativeFetchClient, OllamaWebClient, SearchProvider,
    SearxngClient, WebFetchResult, format_results,
};

/// Build the `web_fetch` tool for the configured backend. `native` always
/// yields a tool; `ollama` yields one only when `OLLAMA_API_KEY` resolves
/// (otherwise the tool would 401 on every call, so we don't register it).
pub fn web_fetch_tool(web: &WebConfig) -> Option<WebFetchTool> {
    match web.fetch_backend {
        FetchBackend::Native => Some(WebFetchTool::native()),
        FetchBackend::Ollama => {
            crate::utils::resolve_provider_key("ollama", "OLLAMA_API_KEY", None)
                .map(WebFetchTool::ollama)
        },
    }
}

/// Build the `web_search` tool for the configured backend. `auto` (the default)
/// and `searxng` always yield a tool; `ollama` yields one only when
/// `OLLAMA_API_KEY` resolves.
pub fn web_search_tool(web: &WebConfig) -> Option<WebSearchTool> {
    match web.search_backend {
        // Zero-config default: Ollama Cloud when a key is present, otherwise an
        // auto-managed local SearXNG (started lazily on the first search).
        SearchBackend::Auto => Some(
            crate::utils::resolve_provider_key("ollama", "OLLAMA_API_KEY", None)
                .map(WebSearchTool::ollama)
                .unwrap_or_else(WebSearchTool::managed_searxng),
        ),
        SearchBackend::Ollama => {
            crate::utils::resolve_provider_key("ollama", "OLLAMA_API_KEY", None)
                .map(WebSearchTool::ollama)
        },
        SearchBackend::Searxng => Some(WebSearchTool::searxng(web.searxng_url.clone())),
    }
}

/// `web_search` — query the configured search backend. Accepts a single
/// `{query, max_results}` OR a list of `{queries: [{query, max_results}]}` for
/// parallel fan-out.
pub struct WebSearchTool {
    backend: Arc<dyn SearchProvider>,
}

impl WebSearchTool {
    /// Search via Ollama Cloud (bearer `OLLAMA_API_KEY`).
    pub fn ollama(api_key: String) -> Self {
        Self {
            backend: Arc::new(OllamaWebClient::new(api_key)),
        }
    }

    /// Search via a self-hosted SearXNG instance at `base_url`.
    pub fn searxng(base_url: String) -> Self {
        Self {
            backend: Arc::new(SearxngClient::new(base_url)),
        }
    }

    /// Search via an auto-managed local SearXNG container (zero-config default).
    pub fn managed_searxng() -> Self {
        Self {
            backend: Arc::new(ManagedSearxngBackend),
        }
    }
}

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

    fn schema(&self) -> ToolDefinition {
        ToolDefinition {
            name: "web_search".to_string(),
            description:
                "Search the web. Takes either a single `query` + `max_results`, or an array of `queries` for parallel fan-out."
                    .to_string(),
            input_schema: serde_json::json!({
                "type": "object",
                "properties": {
                    "query": { "type": "string" },
                    "max_results": { "type": "integer", "minimum": 1, "maximum": 10, "default": 5 },
                    "queries": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "query": { "type": "string" },
                                "max_results": { "type": "integer", "minimum": 1, "maximum": 10 }
                            },
                            "required": ["query"]
                        }
                    }
                }
            }),
        }
    }

    async fn execute(&self, args: serde_json::Value, ctx: ExecContext) -> ToolOutcome {
        let queries = match parse_queries(&args) {
            Ok(q) => q,
            Err(e) => return ToolOutcome::error(e, 0.0),
        };
        if queries.is_empty() {
            return ToolOutcome::error("web_search requires at least one query", 0.0);
        }
        if let Some(blocked) = super::policy_gate::gate_external(
            &ctx,
            "web_search",
            crate::runtime::ToolCategory::Web,
            format!("web_search ({} queries)", queries.len()),
            &args,
        )
        .await
        {
            return blocked;
        }

        let start = std::time::Instant::now();
        let mut combined = String::new();
        let mut result_count = 0usize;
        let mut sources = Vec::new();
        let mut errors: Vec<String> = Vec::new();
        for (idx, (query, count)) in queries.iter().enumerate() {
            let _ = ctx
                .progress
                .send(ProgressEvent::Status(format!(
                    "searching {}/{}: {}",
                    idx + 1,
                    queries.len(),
                    query
                )))
                .await;

            let search = self.backend.search(query, *count);
            let result = tokio::select! {
                biased;
                _ = ctx.token.cancelled() => return ToolOutcome::cancelled(),
                result = search => result,
            };
            // A single query returning nothing or erroring does NOT abort the
            // batch — record it and carry on so the other queries' results
            // survive (a partial answer beats none).
            let section = match result {
                Ok(results) => {
                    result_count += results.len();
                    sources.extend(results.iter().map(|result| result.url.clone()));
                    if results.is_empty() {
                        "[SEARCH_RESULTS]\n(no results found)\n[/SEARCH_RESULTS]\n".to_string()
                    } else {
                        format_results(&results)
                    }
                },
                Err(e) => {
                    errors.push(format!("{query}: {e}"));
                    format!("(search failed: {e})\n")
                },
            };
            if queries.len() > 1 {
                combined.push_str(&format!("=== query: {query} ===\n{section}\n\n"));
            } else {
                combined = section;
            }
        }

        // Only a total failure — every query hit a backend error — is a tool
        // error. An empty-but-reachable search, or a partial success, returns
        // normally so the model sees what did come back.
        if errors.len() == queries.len() {
            return ToolOutcome::error(
                format!("web_search failed: {}", errors.join("; ")),
                start.elapsed().as_secs_f64(),
            );
        }

        // Cap the aggregate output. Per-result content is already truncated to
        // WEB_CONTENT_MAX_CHARS, but many results across many queries can still
        // bloat context (and memory) past what any single result's cap bounds (#28).
        let combined = crate::utils::truncate_middle(
            &combined,
            crate::constants::WEB_SEARCH_AGGREGATE_MAX_CHARS,
        );

        let duration_secs = start.elapsed().as_secs_f64();
        let requested_count = queries.iter().map(|(_, count)| *count).sum();
        let query_texts = queries.iter().map(|(query, _)| query.clone()).collect();
        ToolOutcome::success(
            combined,
            format!(
                "{} {} returned",
                result_count,
                if result_count == 1 {
                    "result"
                } else {
                    "results"
                }
            ),
            duration_secs,
        )
        .with_metadata(ToolRunMetadata {
            detail: ToolMetadata::WebSearch {
                queries: query_texts,
                requested_count,
                result_count,
                sources,
            },
            result_count: Some(result_count),
            ..ToolRunMetadata::default()
        })
    }
}

/// `web_fetch` — retrieve a URL's readable content as markdown. Single URL,
/// single response. Native by default (fetches + converts in-process, no key);
/// can be backed by Ollama Cloud instead.
pub struct WebFetchTool {
    backend: Arc<dyn FetchProvider>,
}

impl WebFetchTool {
    /// Fetch the URL in-process and convert its HTML to markdown (no API key).
    pub fn native() -> Self {
        Self {
            backend: Arc::new(NativeFetchClient::new()),
        }
    }

    /// Fetch via Ollama Cloud's server-side `/api/web_fetch`.
    pub fn ollama(api_key: String) -> Self {
        Self {
            backend: Arc::new(OllamaWebClient::new(api_key)),
        }
    }
}

#[async_trait]
impl ToolExecutor for WebFetchTool {
    fn name(&self) -> &'static str {
        "web_fetch"
    }

    fn schema(&self) -> ToolDefinition {
        ToolDefinition {
            name: "web_fetch".to_string(),
            description: "Retrieve a single URL's main content as markdown. Optional 'pattern' \
                          finds matches in the page instead of returning the whole body: plain \
                          case-insensitive substring matching, applied per line (a pattern \
                          containing a newline never matches), returning each match with \
                          surrounding context lines."
                .to_string(),
            input_schema: serde_json::json!({
                "type": "object",
                "properties": {
                    "url": { "type": "string" },
                    "pattern": {
                        "type": "string",
                        "description": "Case-insensitive substring to find in the page (not a regex)"
                    },
                    "context_lines": {
                        "type": "integer",
                        "description": "Context lines around each match (default 2, max 10)"
                    }
                },
                "required": ["url"]
            }),
        }
    }

    async fn execute(&self, args: serde_json::Value, ctx: ExecContext) -> ToolOutcome {
        let Some(url) = args.get("url").and_then(|v| v.as_str()) else {
            return ToolOutcome::error("web_fetch requires 'url' (string)", 0.0);
        };
        let pattern = args
            .get("pattern")
            .and_then(|v| v.as_str())
            .map(str::trim)
            .filter(|p| !p.is_empty());
        let context_lines = args
            .get("context_lines")
            .and_then(|v| v.as_u64())
            .unwrap_or(2)
            .min(10) as usize;
        if let Err(reason) = validate_fetch_url(url) {
            return ToolOutcome::error(format!("web_fetch: {reason}"), 0.0);
        }
        if let Some(blocked) = super::policy_gate::gate_external(
            &ctx,
            "web_fetch",
            crate::runtime::ToolCategory::Web,
            format!("web_fetch {}", url),
            &args,
        )
        .await
        {
            return blocked;
        }
        let start = std::time::Instant::now();
        let fetch = self.backend.fetch(url);

        tokio::select! {
            biased;
            _ = ctx.token.cancelled() => ToolOutcome::cancelled(),
            result = fetch => match result {
                Ok(page) => {
                    let output = format_fetch(url, &page, pattern, context_lines);
                    let duration_secs = start.elapsed().as_secs_f64();
                    let line_count = output.lines().count();
                    let byte_count = output.len();
                    let title = if page.title.is_empty() {
                        None
                    } else {
                        Some(page.title)
                    };
                    ToolOutcome::success(
                        output,
                        format!("{} {} fetched", line_count, if line_count == 1 { "line" } else { "lines" }),
                        duration_secs,
                    )
                    .with_metadata(ToolRunMetadata {
                        detail: ToolMetadata::WebFetch {
                            url: url.to_string(),
                            title,
                            line_count,
                            byte_count,
                        },
                        line_count: Some(line_count),
                        byte_count: Some(byte_count),
                        ..ToolRunMetadata::default()
                    })
                },
                Err(e) => ToolOutcome::error(
                    format!("web_fetch({}): {}", url, e),
                    start.elapsed().as_secs_f64(),
                ),
            },
        }
    }
}

/// Cap on a single `web_fetch` body (#F46). The raw fetch is bounded only by the
/// 16 MB HTTP body limit, so without this one URL could dump megabytes into model
/// context. A full page warrants more room than a `web_search` snippet
/// (`WEB_CONTENT_MAX_CHARS`), so this mirrors web_search's per-call aggregate
/// budget. Applied as a byte cap; truncation is char-boundary safe.
const WEB_FETCH_MAX_CHARS: usize = crate::constants::WEB_SEARCH_AGGREGATE_MAX_CHARS;

/// Truncate a fetched page body to `WEB_FETCH_MAX_CHARS` bytes, char-boundary
/// safe, appending a marker — consistent with how `web_search` bounds the
/// content it returns (#F46). Borrows when no truncation is needed.
fn cap_fetch_content(content: &str) -> std::borrow::Cow<'_, str> {
    if content.len() <= WEB_FETCH_MAX_CHARS {
        return std::borrow::Cow::Borrowed(content);
    }
    let cut = content.floor_char_boundary(WEB_FETCH_MAX_CHARS);
    std::borrow::Cow::Owned(format!("{}\n\n...[content truncated]", &content[..cut]))
}

/// Cap on find-in-page match BLOCKS per call (merged context windows).
/// Matched lines beyond the included blocks are summarized as a
/// `(+N more matches)` tail so the model knows the page has more.
const MAX_PATTERN_MATCHES: usize = 20;

fn format_fetch(
    url: &str,
    page: &WebFetchResult,
    pattern: Option<&str>,
    ctx_lines: usize,
) -> String {
    let title = if page.title.is_empty() {
        "(no title)"
    } else {
        page.title.as_str()
    };
    // Find-in-page runs on the FULL readable markdown, then the report goes
    // through the cap — capping first would hide matches in the tail.
    if let Some(pattern) = pattern {
        let body = match extract_matches(&page.content, pattern, ctx_lines, MAX_PATTERN_MATCHES) {
            Some(report) => report,
            // No match: say so, then the capped head as usual so the model
            // keeps its orientation on the page.
            None => format!(
                "No matches for \"{}\".\n\n{}",
                pattern,
                cap_fetch_content(&page.content)
            ),
        };
        let report = format!("# {}\n\nURL: {}\n\n{}", title, url, body);
        return cap_fetch_content(&report).into_owned();
    }
    let content = cap_fetch_content(&page.content);
    format!("# {}\n\nURL: {}\n\n{}", title, url, content)
}

/// Find-in-page core: plain case-insensitive SUBSTRING match per line (not a
/// regex — model-supplied metacharacters must mean themselves), each match
/// reported as a `L<n>:`-prefixed context block. Overlapping or adjacent
/// windows merge into one block; blocks are separated by `---` lines and
/// capped at `max_blocks`, with a `(+N more matches)` tail counting the
/// matched lines that didn't fit. Returns `None` when nothing matches.
fn extract_matches(
    content: &str,
    pattern: &str,
    context_lines: usize,
    max_blocks: usize,
) -> Option<String> {
    let needle = pattern.to_lowercase();
    let lines: Vec<&str> = content.lines().collect();
    let matched: Vec<usize> = lines
        .iter()
        .enumerate()
        .filter(|(_, l)| l.to_lowercase().contains(&needle))
        .map(|(i, _)| i)
        .collect();
    if matched.is_empty() {
        return None;
    }

    // Merge each match's [i-ctx, i+ctx] window with overlapping/adjacent
    // neighbors; count how many matched lines the included blocks cover.
    let mut blocks: Vec<(usize, usize)> = Vec::new();
    for &i in &matched {
        let start = i.saturating_sub(context_lines);
        let end = (i + context_lines).min(lines.len() - 1);
        match blocks.last_mut() {
            Some((_, last_end)) if start <= *last_end + 1 => *last_end = (*last_end).max(end),
            _ => blocks.push((start, end)),
        }
    }
    let included = &blocks[..blocks.len().min(max_blocks)];
    let cutoff = included.last().map(|&(_, end)| end).unwrap_or(0);
    let dropped = matched.iter().filter(|&&i| i > cutoff).count();

    let mut out = format!(
        "{} match{} for \"{}\":\n",
        matched.len(),
        if matched.len() == 1 { "" } else { "es" },
        pattern
    );
    for (bi, &(start, end)) in included.iter().enumerate() {
        if bi > 0 {
            out.push_str("---\n");
        }
        for (offset, line) in lines[start..=end].iter().enumerate() {
            // 1-based line numbers, matching how editors and grep report.
            out.push_str(&format!("L{}: {}\n", start + offset + 1, line));
        }
    }
    if dropped > 0 {
        out.push_str(&format!(
            "(+{dropped} more match{})\n",
            if dropped == 1 { "" } else { "es" }
        ));
    }
    Some(out)
}

fn parse_queries(args: &serde_json::Value) -> Result<Vec<(String, usize)>, String> {
    if let Some(arr) = args.get("queries").and_then(|v| v.as_array()) {
        if arr.len() > crate::constants::MAX_BATCH_TOOL_ITEMS {
            return Err(format!(
                "web_search: too many queries ({}); cap is {} per call — split the request",
                arr.len(),
                crate::constants::MAX_BATCH_TOOL_ITEMS
            ));
        }
        let mut out = Vec::with_capacity(arr.len());
        for v in arr {
            let Some(obj) = v.as_object() else {
                return Err(
                    "web_search: 'queries' must be an array of {query, max_results}".to_string(),
                );
            };
            let Some(query) = obj.get("query").and_then(|x| x.as_str()) else {
                return Err("web_search: each query entry needs 'query' (string)".to_string());
            };
            let count = obj
                .get("max_results")
                .or_else(|| obj.get("result_count"))
                .and_then(|x| x.as_u64())
                .unwrap_or(5)
                .clamp(1, 10) as usize;
            out.push((query.to_string(), count));
        }
        return Ok(out);
    }
    if let Some(query) = args.get("query").and_then(|v| v.as_str()) {
        let count = args
            .get("max_results")
            .or_else(|| args.get("result_count"))
            .and_then(|v| v.as_u64())
            .unwrap_or(5)
            .clamp(1, 10) as usize;
        return Ok(vec![(query.to_string(), count)]);
    }
    Err("web_search requires 'query' (string) or 'queries' (array)".to_string())
}

/// Reject obviously-unsafe fetch URLs before the backend runs: only
/// `http`/`https`, and no loopback / link-local / private / metadata hosts.
/// For the native backend this is the primary SSRF boundary (the request
/// leaves from this process, so `web_client::guard_resolved_ips` also checks
/// the resolved addresses); for the Ollama backend it's defense-in-depth ahead
/// of Ollama's own server-side fetch. Guards against model-supplied URLs.
/// Reject anything that isn't a plain `http(s)` URL. A `file:`, `javascript:`,
/// `data:`, or otherwise exotic scheme has no business reaching an HTTP fetch or
/// an OS browser launcher. Returns the parsed URL so callers can inspect the
/// host without re-parsing. Note: this deliberately does NOT block loopback —
/// `open_url` legitimately opens a just-started local dev server.
pub(crate) fn require_http_scheme(url: &str) -> Result<reqwest::Url, String> {
    let parsed = reqwest::Url::parse(url).map_err(|e| format!("invalid URL: {e}"))?;
    match parsed.scheme() {
        "http" | "https" => Ok(parsed),
        other => Err(format!(
            "unsupported URL scheme '{other}' (only http/https allowed)"
        )),
    }
}

fn validate_fetch_url(url: &str) -> Result<(), String> {
    let parsed = require_http_scheme(url)?;
    let host = parsed
        .host_str()
        .ok_or_else(|| "URL has no host".to_string())?;
    if is_blocked_host(host) {
        return Err(format!("refusing to fetch internal/loopback host '{host}'"));
    }
    Ok(())
}

/// Cloud-metadata DNS hostnames that resolve (inside the relevant cloud) to a
/// link-local metadata IP — `169.254.169.254` and friends — but are LEXICALLY
/// public, so the IP-only `classify_host` waves them through as
/// [`crate::utils::HostClass::Public`]. We block them by name as well. Matched
/// after lowercasing + trimming any surrounding `[]` and trailing FQDN dot.
const METADATA_HOSTNAMES: &[&str] = &[
    "metadata.google.internal",   // GCP (canonical)
    "metadata.goog",              // GCP (alternate)
    "metadata",                   // GCP/Azure short name (http://metadata/ responds)
    "instance-data",              // AWS (cloud-init alias)
    "instance-data.ec2.internal", // AWS
];

/// F57: client-side SSRF denylist for `web_fetch`.
///
/// For the NATIVE backend the request originates from this process, so this
/// lexical check plus `web_client::guard_resolved_ips` (which classifies the
/// resolved addresses) is the authoritative boundary — modulo the
/// DNS-rebinding TOCTOU that no pre-connect check can fully close.
///
/// For the OLLAMA backend the URL is POSTed to Ollama's server-side
/// `/api/web_fetch` and the in-process client only ever connects to
/// `ollama.com`; there the authoritative boundary is server-side (Ollama) and
/// this check is defense-in-depth so a model can't trivially aim the server at
/// an obvious internal target.
///
/// Either way we reject:
/// - every non-public IP form via the shared `classify_host` (loopback,
///   RFC-1918/ULA, link-local incl. `169.254.169.254`, CGNAT, unspecified
///   `0.0.0.0`/`::`, plus the IPv4-mapped-IPv6 / ULA / link-local-IPv6 / `[::1]`
///   forms a hand-rolled IPv4 check would miss); and
/// - the well-known cloud-metadata HOSTNAMES (`metadata.google.internal`, …)
///   that are lexically public but front a metadata service.
fn is_blocked_host(host: &str) -> bool {
    let normalized = host
        .trim_start_matches('[')
        .trim_end_matches(']')
        .trim_end_matches('.')
        .to_ascii_lowercase();
    if METADATA_HOSTNAMES.contains(&normalized.as_str()) {
        return true;
    }
    crate::utils::classify_host(host).is_internal()
}

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

    #[test]
    fn require_http_scheme_accepts_http_rejects_exotic() {
        // http/https pass — including loopback, since `open_url` legitimately
        // opens a just-started local dev server (so this must NOT block localhost).
        for good in [
            "http://example.com",
            "https://example.com/path?a=1&b=2",
            "http://localhost:3000",
            "http://127.0.0.1:8080",
        ] {
            assert!(require_http_scheme(good).is_ok(), "{good} should pass");
        }
        // Non-http(s) schemes and unparseable input are rejected.
        for bad in [
            "file:///etc/passwd",
            "javascript:alert(1)",
            "data:text/html,<script>",
            "ftp://example.com",
            "not a url",
        ] {
            assert!(
                require_http_scheme(bad).is_err(),
                "{bad} should be rejected"
            );
        }
    }

    #[test]
    fn validate_fetch_url_blocks_unsafe_targets() {
        // #9: scheme + internal-host guards.
        for bad in [
            "file:///etc/passwd",
            "ftp://example.com/x",
            "http://localhost/admin",
            "http://127.0.0.1:8080",
            "http://169.254.169.254/latest/meta-data/",
            "http://10.0.0.5/",
            "http://192.168.1.1/",
            "http://[::1]/",
            // #27/#80: IPv6/CGNAT bypasses the old IPv4-centric blocklist missed.
            "http://[::ffff:169.254.169.254]/latest/meta-data/",
            "http://[fc00::1]/",
            "http://[fe80::1]/",
            "http://100.100.100.200/",
            // F57: cloud-metadata hostnames are lexically public (IP-only
            // classify_host waves them through) but front a metadata service.
            "http://metadata.google.internal/computeMetadata/v1/",
            "http://metadata.goog/",
            "http://metadata/",
            "http://instance-data/latest/meta-data/",
            "https://METADATA.GOOGLE.INTERNAL./",
            "not a url",
        ] {
            assert!(
                validate_fetch_url(bad).is_err(),
                "expected reject for {bad:?}",
            );
        }
        for good in [
            "https://example.com",
            "http://example.com/page?x=1",
            "https://docs.rs/serde",
        ] {
            assert!(
                validate_fetch_url(good).is_ok(),
                "expected accept for {good:?}",
            );
        }
    }

    #[test]
    fn is_blocked_host_covers_metadata_names_and_ip_forms() {
        // F57: cloud-metadata HOSTNAMES (lexically public, IP-only
        // classify_host misses them) are blocked, case/dot-insensitively.
        for h in [
            "metadata.google.internal",
            "metadata.google.internal.", // trailing FQDN dot
            "Metadata.Google.Internal",  // case-insensitive
            "metadata.goog",
            "metadata",
            "instance-data",
            "instance-data.ec2.internal",
        ] {
            assert!(is_blocked_host(h), "metadata host {h:?} must be blocked");
        }
        // Non-public IP forms still go through classify_host (incl. the ones
        // the task lists as examples that must already be covered).
        for h in ["0.0.0.0", "::1", "169.254.169.254", "127.0.0.1"] {
            assert!(is_blocked_host(h), "internal IP {h:?} must be blocked");
        }
        // Legitimate public hosts are NOT blocked — including a real `.goog`
        // domain that merely is not the metadata alias.
        for h in ["example.com", "docs.rs", "abc.goog", "8.8.8.8"] {
            assert!(!is_blocked_host(h), "public host {h:?} must be allowed");
        }
    }

    #[test]
    fn format_fetch_caps_long_content() {
        // F46: a huge page body must be truncated with a marker, not dumped whole.
        let big = "z".repeat(WEB_FETCH_MAX_CHARS * 2);
        let page = WebFetchResult {
            title: "T".to_string(),
            content: big,
        };
        let out = format_fetch("https://example.com", &page, None, 2);
        assert!(
            out.len() < WEB_FETCH_MAX_CHARS + 256,
            "content must be capped, got {} bytes",
            out.len()
        );
        assert!(out.contains("truncated"), "expected truncation marker");

        // A short page is emitted intact, with no marker.
        let small = WebFetchResult {
            title: "T".to_string(),
            content: "hello world".to_string(),
        };
        let out = format_fetch("https://example.com", &small, None, 2);
        assert!(out.contains("hello world"));
        assert!(!out.contains("truncated"));
    }

    #[test]
    fn extract_matches_finds_case_insensitive_with_context() {
        let content = "line one\nline two\nTARGET here\nline four\nline five";
        let out = extract_matches(content, "target", 1, 20).unwrap();
        assert!(out.starts_with("1 match for \"target\":"));
        assert!(out.contains("L2: line two"));
        assert!(out.contains("L3: TARGET here"));
        assert!(out.contains("L4: line four"));
        assert!(!out.contains("L1:"), "context clipped to 1 line: {out}");
        assert!(!out.contains("L5:"));
    }

    #[test]
    fn extract_matches_merges_overlapping_windows() {
        // Matches on adjacent lines must merge into ONE block (no separator).
        let content = "a\nhit one\nhit two\nb\nc\nd\ne\nf\ng\nhit three\nz";
        let out = extract_matches(content, "hit", 1, 20).unwrap();
        assert!(out.starts_with("3 matches"));
        assert_eq!(out.matches("---").count(), 1, "two blocks: {out}");
        // No duplicated lines from the merged windows.
        assert_eq!(out.matches("hit one").count(), 1);
    }

    #[test]
    fn extract_matches_caps_blocks_and_reports_tail() {
        // 25 matches spaced far apart -> 25 blocks, capped at 20 + tail note.
        let content = (0..25)
            .map(|i| format!("match {i}\nx\nx\nx\nx\nx"))
            .collect::<Vec<_>>()
            .join("\n");
        let out = extract_matches(&content, "match", 0, 20).unwrap();
        assert!(out.starts_with("25 matches"));
        assert_eq!(out.matches("---").count(), 19, "20 blocks: {out}");
        assert!(out.contains("(+5 more matches)"), "tail note: {out}");
    }

    #[test]
    fn extract_matches_none_and_multibyte() {
        assert!(extract_matches("nothing here", "absent", 2, 20).is_none());
        // Multibyte content must not panic and must match case-insensitively.
        let content = "voil\u{e0} un r\u{e9}sultat\nplain line";
        let out = extract_matches(content, "R\u{c9}SULTAT", 0, 20).unwrap();
        assert!(out.contains("L1: voil\u{e0} un r\u{e9}sultat"));
        // Context 0 keeps only the matching line.
        assert!(!out.contains("plain line"));
    }

    #[test]
    fn format_fetch_pattern_paths() {
        let page = WebFetchResult {
            title: "T".to_string(),
            content: "alpha\nbeta\ngamma".to_string(),
        };
        // Match -> report replaces the body.
        let out = format_fetch("https://example.com", &page, Some("beta"), 1);
        assert!(out.contains("1 match for \"beta\""));
        assert!(out.contains("L2: beta"));
        // No match -> explicit notice + the page head so the model keeps
        // orientation.
        let out = format_fetch("https://example.com", &page, Some("nope"), 1);
        assert!(out.contains("No matches for \"nope\"."));
        assert!(out.contains("alpha"));
    }

    #[test]
    fn find_in_page_runs_before_the_cap() {
        // A match in the tail of a page longer than the cap must still be
        // found (matching runs pre-cap; only the report is capped).
        let mut content = "x\n".repeat(WEB_FETCH_MAX_CHARS / 2);
        content.push_str("needle in the tail\n");
        let page = WebFetchResult {
            title: "T".to_string(),
            content,
        };
        let out = format_fetch("https://example.com", &page, Some("needle"), 1);
        assert!(out.contains("1 match for \"needle\""), "tail match found");
        assert!(out.contains("needle in the tail"));
    }

    #[test]
    fn parse_queries_single_form() {
        let args = serde_json::json!({"query": "rust async", "max_results": 3});
        let q = parse_queries(&args).unwrap();
        assert_eq!(q.len(), 1);
        assert_eq!(q[0].0, "rust async");
        assert_eq!(q[0].1, 3);
    }

    #[test]
    fn parse_queries_array_form() {
        let args = serde_json::json!({"queries": [
            {"query": "a", "max_results": 2},
            {"query": "b", "result_count": 5},
        ]});
        let q = parse_queries(&args).unwrap();
        assert_eq!(q.len(), 2);
        assert_eq!(q[1].1, 5);
    }

    #[test]
    fn parse_queries_missing_errors() {
        let args = serde_json::json!({});
        assert!(parse_queries(&args).is_err());
    }

    #[test]
    fn parse_queries_clamps_count() {
        let args = serde_json::json!({"query": "q", "max_results": 999});
        let q = parse_queries(&args).unwrap();
        assert_eq!(q[0].1, 10);
        let args = serde_json::json!({"query": "q", "max_results": 0});
        let q = parse_queries(&args).unwrap();
        assert_eq!(q[0].1, 1);
    }

    #[test]
    fn parse_queries_rejects_excess_fan_out() {
        // #90: a single call can't request unbounded fan-out.
        let many: Vec<_> = (0..crate::constants::MAX_BATCH_TOOL_ITEMS + 1)
            .map(|i| serde_json::json!({"query": format!("q{i}")}))
            .collect();
        let args = serde_json::json!({ "queries": many });
        assert!(parse_queries(&args).is_err());

        // Exactly at the cap is still accepted.
        let at_cap: Vec<_> = (0..crate::constants::MAX_BATCH_TOOL_ITEMS)
            .map(|i| serde_json::json!({"query": format!("q{i}")}))
            .collect();
        let args = serde_json::json!({ "queries": at_cap });
        assert_eq!(
            parse_queries(&args).unwrap().len(),
            crate::constants::MAX_BATCH_TOOL_ITEMS
        );
    }

    #[tokio::test]
    async fn web_search_batch_survives_empty_and_failed_queries() {
        use crate::domain::{ToolCallId, ToolStatus, TurnId};
        use crate::providers::ctx::test_exec_context;
        use crate::providers::tool::web_client::SearchResult;
        use async_trait::async_trait;
        use std::sync::Arc;

        struct Mock;
        #[async_trait]
        impl SearchProvider for Mock {
            async fn search(
                &self,
                query: &str,
                _count: usize,
            ) -> anyhow::Result<Vec<SearchResult>> {
                match query {
                    "boom" => Err(anyhow::anyhow!("backend down")),
                    "empty" => Ok(Vec::new()),
                    _ => Ok(vec![SearchResult {
                        title: "Title".to_string(),
                        url: "https://example.com".to_string(),
                        snippet: "snip".to_string(),
                        full_content: "content".to_string(),
                    }]),
                }
            }
        }

        let mk = || WebSearchTool {
            backend: Arc::new(Mock),
        };
        let tmp = std::path::PathBuf::from("/tmp");

        // Partial: one good, one empty, one erroring -> success, good kept.
        let (ctx, _rx) = test_exec_context(TurnId(1), ToolCallId(1), tmp.clone());
        let out = mk()
            .execute(
                serde_json::json!({"queries": [{"query":"good"},{"query":"empty"},{"query":"boom"}]}),
                ctx,
            )
            .await;
        assert_eq!(
            out.status,
            ToolStatus::Success,
            "a partial batch must not abort"
        );
        assert!(
            out.output().contains("https://example.com"),
            "keeps the good result"
        );

        // A single empty query is "no results", not a hard error.
        let (ctx, _rx) = test_exec_context(TurnId(2), ToolCallId(2), tmp.clone());
        let out = mk()
            .execute(serde_json::json!({"query": "empty"}), ctx)
            .await;
        assert_eq!(out.status, ToolStatus::Success, "empty is not an error");
        assert!(out.output().contains("no results"));

        // Every query failing IS a tool error.
        let (ctx, _rx) = test_exec_context(TurnId(3), ToolCallId(3), tmp);
        let out = mk()
            .execute(
                serde_json::json!({"queries": [{"query":"boom"},{"query":"boom"}]}),
                ctx,
            )
            .await;
        assert_eq!(out.status, ToolStatus::Error, "total failure is an error");
    }
}