agent-search 0.6.2

Unified multi-provider search CLI for AI agents — 12 providers, 13 modes, email verification, one binary
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
mod cache;
mod cli;
mod config;
mod context;
mod engine;
mod errors;
mod logging;
mod output;
mod providers;
mod types;
mod verify;

use clap::Parser;
use cli::{Cli, Commands, ConfigAction, SkillAction};
use config::{config_check, config_set, config_show, load_config};
use context::AppContext;
use output::{Ctx, OutputFormat};
use std::sync::Arc;
use tokio::net::lookup_host;

#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;

/// Global flags read straight from argv. Needed because `query_words` uses
/// `trailing_var_arg`, which otherwise swallows flags placed AFTER a bare query
/// (`search foo --json` — clap never sees the `--json`), and because the
/// help/version/parse-error paths run before clap has populated `Cli`.
#[derive(Default, Clone, Copy)]
struct GlobalFlags {
    json: bool,
    quiet: bool,
    last: bool,
    x_only: bool,
    debug: bool,
}

fn scan_global_flags() -> GlobalFlags {
    let mut f = GlobalFlags::default();
    for arg in std::env::args_os().skip(1) {
        // Everything after `--` is a literal query token, not a flag.
        if arg == "--" {
            break;
        }
        match arg.to_str() {
            Some("--json") => f.json = true,
            Some("--quiet") => f.quiet = true,
            Some("--last") => f.last = true,
            Some("--x") => f.x_only = true,
            Some("--debug") | Some("--verbose") => f.debug = true,
            _ => {}
        }
    }
    f
}

/// Global-flag tokens to strip from a bare query that `trailing_var_arg`
/// captured, so `search foo --json` searches "foo", not "foo --json".
const GLOBAL_FLAG_TOKENS: &[&str] = &["--json", "--quiet", "--last", "--x", "--debug", "--verbose"];

/// Initialize tracing to stderr so provider/engine diagnostics are never silently
/// dropped. Honors `RUST_LOG`; `--debug` raises the default level to `debug`.
/// Writes to stderr only, keeping JSON envelopes on stdout machine-parseable.
fn init_tracing(debug: bool) {
    use tracing_subscriber::{fmt, EnvFilter};
    // `--debug` shows app-level debug but mutes noisy transport crates so the
    // signal (provider/engine diagnostics) isn't buried in connection spam.
    let default = if debug {
        "debug,hyper=warn,hyper_util=warn,reqwest=warn,h2=warn,rustls=warn,tower=warn"
    } else {
        "warn"
    };
    let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default));
    let _ = fmt()
        .with_env_filter(filter)
        .with_writer(std::io::stderr)
        .with_target(false)
        .without_time()
        .try_init();
}

#[tokio::main]
async fn main() {
    // 1. Pre-emptive DNS resolution (starts immediately in background)
    tokio::spawn(async {
        let domains = [
            "api.parallel.ai:443",
            "api.search.brave.com:443",
            "google.serper.dev:443",
            "api.exa.ai:443",
            "api.jina.ai:443",
            "api.tavily.com:443",
            "api.perplexity.ai:443",
        ];
        for domain in domains {
            let _ = lookup_host(domain).await;
        }
    });

    // 2. Start loading config in parallel with CLI parsing
    let config_handle = tokio::task::spawn_blocking(load_config);

    // 3. Pre-scan global flags before clap parses (covers flags trailing a bare
    //    query, plus the help/version/error paths). Init tracing immediately.
    let flags = scan_global_flags();
    init_tracing(flags.debug);
    let json_flag = flags.json;

    // 4. CLI Parsing — use try_parse so we own error handling
    let mut cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(e) => {
            if matches!(
                e.kind(),
                clap::error::ErrorKind::DisplayHelp | clap::error::ErrorKind::DisplayVersion
            ) {
                let format = OutputFormat::detect(json_flag);
                match format {
                    OutputFormat::Json => {
                        let envelope = serde_json::json!({
                            "version": "1",
                            "status": "success",
                            "data": { "usage": e.to_string().trim_end() },
                        });
                        println!("{}", serde_json::to_string_pretty(&envelope).unwrap());
                        std::process::exit(0);
                    }
                    OutputFormat::Table => e.exit(),
                }
            }

            // Parse errors — route through the typed error model (exit 3) so the
            // code/exit namespace lives in one place (errors.rs), not inline here.
            let err = errors::SearchError::InvalidInput {
                message: e.to_string(),
            };
            match OutputFormat::detect(json_flag) {
                OutputFormat::Json => output::json::render_error(&err),
                // Keep clap's rich, colored usage message for humans.
                OutputFormat::Table => eprint!("{e}"),
            }
            std::process::exit(err.exit_code());
        }
    };

    // Merge pre-scanned flags so flags trailing a bare query still take effect.
    cli.json |= flags.json;
    cli.quiet |= flags.quiet;
    cli.last |= flags.last;
    cli.x_only |= flags.x_only;
    cli.debug |= flags.debug;

    let ctx = Ctx::new(cli.json, cli.quiet);

    // 5. Wait for config
    let config = match config_handle.await {
        Ok(Ok(c)) => c,
        // A malformed config is a config error (exit 2 + JSON envelope when
        // piped), not a transient exit-1 plaintext message — otherwise an agent
        // loops forever on an unfixable parse error and can't read the reason.
        Ok(Err(e)) => {
            let err = errors::SearchError::Config(e.to_string());
            match OutputFormat::detect(json_flag) {
                OutputFormat::Json => output::json::render_error(&err),
                OutputFormat::Table => eprintln!("Error: {err}"),
            }
            std::process::exit(err.exit_code());
        }
        Err(join_err) => {
            let err = errors::SearchError::Config(format!("config load task failed: {join_err}"));
            match OutputFormat::detect(json_flag) {
                OutputFormat::Json => output::json::render_error(&err),
                OutputFormat::Table => eprintln!("Error: {err}"),
            }
            std::process::exit(err.exit_code());
        }
    };

    let app = Arc::new(AppContext::new(config));

    // 6. Pre-emptive TLS Handshake
    let is_search = cli.command.is_none() || matches!(cli.command, Some(Commands::Search(_)));
    if is_search && !cli.last {
        let app_c = app.clone();
        tokio::spawn(async move {
            let urls = [
                "https://api.search.brave.com/res/v1/web/search",
                "https://google.serper.dev/search",
                "https://api.exa.ai/search",
            ];
            for url in urls {
                let _ = app_c.client.head(url).send().await;
            }
        });
    }

    let exit_code = match run(cli, &ctx, app).await {
        Ok(code) => code,
        Err(e) => {
            if ctx.is_json() {
                output::json::render_error(&e);
            } else {
                eprintln!("Error: {e}");
                if let Some(s) = e.suggestion() {
                    eprintln!("  {s}");
                }
                // Give humans the same per-provider detail the JSON envelope carries.
                if let errors::SearchError::AllProvidersFailed { failed } = &e {
                    for f in failed {
                        eprintln!("  - {} [{}]: {}", f.provider, f.category.as_str(), f.reason);
                    }
                }
            }
            e.exit_code()
        }
    };

    std::process::exit(exit_code);
}

async fn run(cli: Cli, ctx: &Ctx, app: Arc<AppContext>) -> Result<i32, errors::SearchError> {
    // Handle bare `search "query"` without subcommand
    let command = if let Some(cmd) = cli.command {
        cmd
    } else if cli.last {
        Commands::Search(cli::SearchArgs {
            query: String::new(),
            mode: types::Mode::General,
            count: None,
            providers: None,
            domain: None,
            exclude_domain: None,
            freshness: None,
        })
    } else if !cli.query_words.is_empty() {
        // Drop any global-flag tokens trailing_var_arg swallowed into the query
        // (their effect was already applied via the pre-scan merge in main).
        let query = cli
            .query_words
            .iter()
            .filter(|w| !GLOBAL_FLAG_TOKENS.contains(&w.as_str()))
            .cloned()
            .collect::<Vec<_>>()
            .join(" ");
        Commands::Search(cli::SearchArgs {
            query,
            mode: types::Mode::General,
            count: None,
            providers: None,
            domain: None,
            exclude_domain: None,
            freshness: None,
        })
    } else {
        use clap::CommandFactory;
        if ctx.is_json() {
            let mut buf = Vec::new();
            Cli::command().write_long_help(&mut buf).ok();
            let envelope = serde_json::json!({
                "version": "1",
                "status": "success",
                "data": { "usage": String::from_utf8_lossy(&buf).trim_end() },
            });
            println!("{}", serde_json::to_string_pretty(&envelope).unwrap());
        } else {
            Cli::command().print_help().ok();
            println!();
        }
        return Ok(0);
    };

    match command {
        Commands::Search(mut args) => {
            // --x flag: force X/Twitter search via xAI Grok
            if cli.x_only {
                args.mode = types::Mode::Social;
                args.providers = Some(vec!["xai".to_string()]);
            }

            if cli.last {
                if let Some(cached) = cache::load_last() {
                    if ctx.is_json() {
                        output::json::render(&cached);
                    } else if !ctx.suppress_human() {
                        output::table::render(&cached);
                    }
                    return Ok(0);
                } else {
                    let err = errors::SearchError::Config(
                        "No cached results found. Run a search first.".into(),
                    );
                    if ctx.is_json() {
                        output::json::render_error(&err);
                    } else {
                        eprintln!("No cached results found. Run a search first.");
                    }
                    return Ok(1);
                }
            }

            // Validate provider names early
            if let Some(ref providers) = args.providers {
                const KNOWN: &[&str] = &[
                    "parallel",
                    "brave",
                    "serper",
                    "exa",
                    "jina",
                    "firecrawl",
                    "tavily",
                    "serpapi",
                    "perplexity",
                    "browserless",
                    "stealth",
                    "xai",
                ];
                for p in providers {
                    if !KNOWN.iter().any(|k| k.eq_ignore_ascii_case(p)) {
                        let err = errors::SearchError::Config(format!(
                            "Unknown provider '{}'. Valid: {}",
                            p,
                            KNOWN.join(", ")
                        ));
                        if ctx.is_json() {
                            output::json::render_error(&err);
                        } else {
                            eprintln!("Error: {err}");
                        }
                        return Ok(err.exit_code());
                    }
                }
            }

            let count = args.count.unwrap_or(app.config.settings.count);
            let opts = types::SearchOpts {
                include_domains: args.domain.unwrap_or_default(),
                exclude_domains: args.exclude_domain.unwrap_or_default(),
                freshness: args.freshness,
            };

            // Check query cache (5min TTL)
            let mode_str = args.mode.to_string();
            if args.providers.is_none()
                && opts.include_domains.is_empty()
                && opts.exclude_domains.is_empty()
                && opts.freshness.is_none()
            {
                if let Some(cached) = cache::load_query(&args.query, &mode_str, count) {
                    if ctx.is_json() {
                        output::json::render(&cached);
                    } else if !ctx.suppress_human() {
                        output::table::render(&cached);
                    }
                    return Ok(0);
                }
            }

            // Show spinner for human output (suppressed by --quiet)
            let spinner = if !ctx.is_json() && !ctx.quiet {
                let sp = indicatif::ProgressBar::new_spinner();
                sp.set_style(
                    indicatif::ProgressStyle::default_spinner()
                        .tick_strings(&["   ", ".  ", ".. ", "...", " ..", "  .", "   "])
                        .template("  {spinner:.cyan} searching {msg}")
                        .unwrap(),
                );
                let provider_hint = args
                    .providers
                    .as_ref()
                    .map(|p| format!(" via {}", p.join(", ")))
                    .unwrap_or_default();
                sp.set_message(format!(
                    "\"{}\" [{}{}]",
                    args.query, args.mode, provider_hint
                ));
                sp.enable_steady_tick(std::time::Duration::from_millis(100));
                Some(sp)
            } else {
                None
            };

            let response =
                engine::run(app, &args.query, args.mode, count, &args.providers, &opts).await;

            if let Some(sp) = spinner {
                sp.finish_and_clear();
            }

            let response = response?;

            // Don't cache empty results — a transient no_results shouldn't be
            // replayed for 5 minutes after the cause clears. (Total failure is
            // already an Err and never reaches here.)
            if !response.results.is_empty() {
                cache::save_last(&response);
                cache::save_query(&args.query, &mode_str, count, &response);
            }
            logging::log_search(&response);

            if ctx.is_json() {
                output::json::render(&response);
            } else if !ctx.suppress_human() {
                output::table::render(&response);
            }

            // Total failure is surfaced as Err(AllProvidersFailed) by the engine
            // (propagated via `response?` above), so any Ok response here is a
            // success/partial_success/no_results — all exit 0.
            Ok(0)
        }

        Commands::Config { action } => {
            match action {
                ConfigAction::Show => {
                    if ctx.is_json() {
                        // Use the same resolver as `config check` (is_configured ->
                        // resolve_key) so env-only keys count and all 12 providers
                        // are covered — the old hardcoded list missed parallel +
                        // stealth and ignored env vars.
                        let all = providers::build_providers(&app);
                        let configured: Vec<&str> = all
                            .iter()
                            .filter(|p| p.is_configured())
                            .map(|p| p.name())
                            .collect();
                        let info = serde_json::json!({
                            "version": types::ENVELOPE_VERSION,
                            "status": "success",
                            "config_path": config::config_path().to_string_lossy(),
                            "settings": {
                                "timeout": app.config.settings.timeout,
                                "count": app.config.settings.count,
                            },
                            "providers_configured": configured,
                        });
                        output::json::render_value(&info);
                    } else if !ctx.suppress_human() {
                        config_show(&app.config);
                    }
                }
                ConfigAction::Set { key, value } => {
                    config_set(&key, &value)?;
                    if ctx.is_json() {
                        output::json::render_value(&serde_json::json!({
                            "version": "1",
                            "status": "success",
                            "key": key,
                            "message": format!("Set {key}"),
                        }));
                    } else if !ctx.suppress_human() {
                        eprintln!("Set {key}");
                    }
                }
                ConfigAction::Check => {
                    if ctx.is_json() {
                        let all_providers = providers::build_providers(&app);
                        let all: Vec<(&str, bool)> = all_providers
                            .iter()
                            .map(|p| (p.name(), p.is_configured()))
                            .collect();
                        let configured: Vec<&str> =
                            all.iter().filter(|(_, v)| *v).map(|(k, _)| *k).collect();
                        let unconfigured: Vec<&str> =
                            all.iter().filter(|(_, v)| !v).map(|(k, _)| *k).collect();
                        let total = all.len();
                        output::json::render_value(&serde_json::json!({
                            "version": "1",
                            "status": "success",
                            "configured_count": configured.len(),
                            "total_count": total,
                            "configured": configured,
                            "unconfigured": unconfigured,
                        }));
                    } else if !ctx.suppress_human() {
                        config_check(&app.config);
                    }
                }
                ConfigAction::Path => {
                    let p = config::config_path();
                    if ctx.is_json() {
                        output::json::render_value(&serde_json::json!({
                            "version": "1",
                            "status": "success",
                            "data": {
                                "path": p.to_string_lossy(),
                                "exists": p.exists(),
                            },
                        }));
                    } else if !ctx.suppress_human() {
                        println!("{}", p.display());
                        if !p.exists() {
                            use owo_colors::OwoColorize;
                            println!("  {}", "(file does not exist, using defaults)".dimmed());
                        }
                    }
                }
            }
            Ok(0)
        }

        Commands::AgentInfo => {
            let all = providers::build_providers(&app);
            let providers_info: Vec<serde_json::Value> = all
                .iter()
                .map(|p| {
                    serde_json::json!({
                        "name": p.name(),
                        "configured": p.is_configured(),
                        "capabilities": p.capabilities(),
                        "env_keys": p.env_keys(),
                    })
                })
                .collect();

            let info = serde_json::json!({
                "name": "search",
                "version": env!("CARGO_PKG_VERSION"),
                "description": env!("CARGO_PKG_DESCRIPTION"),
                "commands": ["search", "verify", "config show", "config set", "config check", "config path", "agent-info", "providers", "skill install", "skill status", "update"],
                "command_schemas": {
                    "search": {
                        "description": "Search across providers",
                        "args": [
                            {"name": "-q/--query", "type": "string", "required": true, "description": "Search query"},
                        ],
                        "options": [
                            {"name": "-m/--mode", "type": "string", "required": false, "default": "general",
                             "values": ["general","news","academic","people","deep","extract","similar","scrape","scholar","patents","images","places","social"],
                             "description": "Search mode — chosen explicitly by the caller; the CLI does NOT infer intent from the query"},
                            {"name": "-c/--count", "type": "integer", "required": false, "description": "Number of results"},
                            {"name": "-p/--providers", "type": "string[]", "required": false,
                             "values": ["parallel","brave","serper","exa","jina","firecrawl","tavily","serpapi","perplexity","browserless","stealth","xai"],
                             "description": "Comma-separated provider list"},
                            {"name": "-d/--domain", "type": "string[]", "required": false, "description": "Include only these domains"},
                            {"name": "--exclude-domain", "type": "string[]", "required": false, "description": "Exclude these domains"},
                            {"name": "-f/--freshness", "type": "string", "required": false,
                             "values": ["day","week","month","year"],
                             "description": "Freshness filter"},
                        ]
                    },
                    "verify": {
                        "description": "Check if email addresses exist via SMTP",
                        "args": [
                            {"name": "emails", "type": "string[]", "required": false, "description": "Email addresses to verify"},
                        ],
                        "options": [
                            {"name": "-f/--file", "type": "string", "required": false, "description": "Read emails from file (use - for stdin)"},
                        ],
                        "verdicts": ["valid","invalid","catch_all","unreachable","timeout","syntax_error"],
                        "notes": "No API key required. Uses direct SMTP."
                    },
                    "config show": {"description": "Display current configuration (keys masked)", "args": [], "options": []},
                    "config set": {
                        "description": "Set a configuration value",
                        "args": [
                            {"name": "key", "type": "string", "required": true, "description": "Config key (e.g. keys.brave, settings.timeout)"},
                            {"name": "value", "type": "string", "required": true, "description": "Value to set"},
                        ],
                        "options": []
                    },
                    "config check": {"description": "Health-check which providers are configured", "args": [], "options": []},
                    "config path": {"description": "Show configuration file path", "args": [], "options": []},
                    "agent-info": {"description": "This manifest", "args": [], "options": []},
                    "providers": {"description": "List all providers with status and capabilities", "args": [], "options": []},
                    "skill install": {"description": "Install skill file to agent platforms", "args": [], "options": []},
                    "skill status": {"description": "Check skill installation status", "args": [], "options": []},
                    "update": {
                        "description": "Self-update binary from GitHub Releases",
                        "args": [],
                        "options": [
                            {"name": "--check", "type": "bool", "required": false, "default": false, "description": "Check only, don't install"}
                        ]
                    },
                },
                "global_flags": {
                    "--json": {"type": "bool", "default": false, "description": "Force JSON output (auto-enabled when piped)"},
                    "--quiet": {"type": "bool", "default": false, "description": "Suppress informational output"},
                    "--last": {"type": "bool", "default": false, "description": "Replay last search from cache"},
                    "--x": {"type": "bool", "default": false, "description": "Search X (Twitter) only"},
                    "--debug": {"type": "bool", "default": false, "description": "Verbose diagnostics to stderr (also honors RUST_LOG)"},
                },
                "exit_codes": {
                    "0": "Success",
                    "1": "Transient error (API, network) -- retry",
                    "2": "Config/auth error -- fix setup",
                    "3": "Bad input -- fix arguments",
                    "4": "Rate limited -- wait and retry",
                },
                "envelope": {
                    "version": "1",
                    "success": "{ version, status, query, mode, results, metadata: { elapsed_ms, result_count, providers_queried, providers_failed, provider_failures } }",
                    "error": "{ version, status, error: { code, message, suggestion, provider_failures } }",
                    "statuses": ["success", "partial_success", "no_results"],
                    "provider_failure": "{ provider, category, http_status, code, reason, retryable }",
                    "failure_categories": ["auth", "billing_quota", "rate_limit", "timeout", "network", "bad_request", "server", "parse", "config", "other"],
                },
                "providers": providers_info,
                "modes": ["general","news","academic","people","deep","extract","similar","scrape","scholar","patents","images","places","social"],
                "routing": "explicit — the caller picks -m/--mode and/or -p/--providers. There is no automatic intent detection; an unspecified mode is a plain general multi-provider web search.",
                "config": {
                    "path": config::config_path().to_string_lossy(),
                    "env_prefix": "SEARCH_",
                    "key_precedence": "<PROVIDER>_API_KEY env > SEARCH_KEYS_* env > config file",
                },
                "auto_json_when_piped": true,
                "not_suited_for": {
                    "github_repos": {
                        "task": "Searching GitHub repositories, code, issues, or PRs",
                        "use_instead": "gh search repos <query> [--language=<lang>] [--sort=stars] [--json fullName,description,stargazersCount,url]",
                        "why": "search uses web crawl, not GitHub's API — no star counts, language filters, or structured repo metadata. gh queries GitHub's search API directly."
                    },
                    "github_code": {
                        "task": "Searching code inside GitHub repositories",
                        "use_instead": "gh search code <query> [--language=<lang>] [--json path,repository,textMatches]",
                        "why": "GitHub code search requires GitHub's index, not web search."
                    },
                    "github_issues": {
                        "task": "Searching GitHub issues or pull requests",
                        "use_instead": "gh search issues <query> [--state=open] [--json title,url,state] or gh search prs <query>",
                        "why": "GitHub issues/PRs require GitHub's API for state, labels, and metadata."
                    }
                },
            });

            output::json::render_value(&info);
            Ok(0)
        }

        Commands::Skill { action } => {
            match action {
                SkillAction::Install => cli::skill::install(ctx),
                SkillAction::Status => cli::skill::status(ctx),
            }
            Ok(0)
        }

        Commands::Providers => {
            let all = providers::build_providers(&app);
            let provider_info: Vec<(String, bool, Vec<String>)> = all
                .iter()
                .map(|p| {
                    (
                        p.name().to_string(),
                        p.is_configured(),
                        p.capabilities().iter().map(|s| s.to_string()).collect(),
                    )
                })
                .collect();

            if ctx.is_json() {
                let json: Vec<serde_json::Value> = provider_info
                    .iter()
                    .map(|(name, configured, caps)| {
                        serde_json::json!({
                            "name": name,
                            "configured": configured,
                            "capabilities": caps,
                        })
                    })
                    .collect();
                output::json::render_value(&serde_json::json!({
                    "version": "1",
                    "status": "success",
                    "providers": json,
                }));
            } else if !ctx.suppress_human() {
                output::table::render_providers(&provider_info);
            }
            Ok(0)
        }

        Commands::Verify(args) => {
            let mut emails: Vec<String> = args.emails;
            if let Some(ref path) = args.file {
                let content = if path == "-" {
                    use std::io::Read;
                    let mut buf = String::new();
                    std::io::stdin().read_to_string(&mut buf)?;
                    buf
                } else {
                    std::fs::read_to_string(path)?
                };
                emails.extend(
                    content
                        .lines()
                        .map(|l| l.trim().to_string())
                        .filter(|l| !l.is_empty() && l.contains('@')),
                );
            }

            if emails.is_empty() {
                let err = errors::SearchError::Config(
                    "No email addresses provided. Usage: search verify user@example.com".into(),
                );
                if ctx.is_json() {
                    output::json::render_error(&err);
                } else {
                    eprintln!("Error: {err}");
                }
                return Ok(2);
            }

            let start = std::time::Instant::now();
            let results = match verify::verify_emails(&emails).await {
                Ok(r) => r,
                Err(e) => {
                    if ctx.is_json() {
                        output::json::render_error(&e);
                    } else {
                        eprintln!("Error: {e}");
                    }
                    return Ok(e.exit_code());
                }
            };
            let elapsed = start.elapsed().as_millis();

            let valid_count = results.iter().filter(|r| r.verdict == "valid").count();
            let invalid_count = results.iter().filter(|r| r.verdict == "invalid").count();
            let catch_all_count = results.iter().filter(|r| r.verdict == "catch_all").count();
            // "Couldn't probe" verdicts — e.g. SMTP port 25 blocked on the
            // network (common on cloud/CI egress).
            let unprobed = results
                .iter()
                .filter(|r| r.verdict == "unreachable" || r.verdict == "timeout")
                .count();
            let syntax_count = results
                .iter()
                .filter(|r| r.verdict == "syntax_error")
                .count();
            let total = results.len();

            // Derive status/exit from verdicts instead of always success/0 —
            // "every probe was blocked" must not read as a clean pass. (`invalid`
            // is a successful *negative* answer, so it stays exit 0.)
            let (status, exit) = if total == 0 {
                ("no_results", 0)
            } else if unprobed == total {
                ("all_probes_unreachable", 1)
            } else if syntax_count == total {
                ("invalid_input", 3)
            } else if unprobed > 0 {
                ("partial_success", 0)
            } else {
                ("success", 0)
            };

            let response = serde_json::json!({
                "version": types::ENVELOPE_VERSION,
                "status": status,
                "results": results,
                "metadata": {
                    "elapsed_ms": elapsed,
                    "verified_count": total,
                    "valid_count": valid_count,
                    "invalid_count": invalid_count,
                    "catch_all_count": catch_all_count,
                    "unreachable_count": unprobed,
                }
            });

            if ctx.is_json() {
                output::json::render_value(&response);
            } else if !ctx.suppress_human() {
                verify::render_table(&results);
            }

            Ok(exit)
        }

        Commands::Update { check } => {
            let current = env!("CARGO_PKG_VERSION");

            // self_update is blocking and builds its own (reqwest blocking)
            // runtime. Calling it directly from #[tokio::main] panics with
            // "Cannot drop a runtime in a context where blocking is not
            // allowed", so run it on a blocking thread, off the async runtime.
            if check {
                let res = tokio::task::spawn_blocking(move || {
                    self_update::backends::github::Update::configure()
                        .repo_owner("paperfoot")
                        .repo_name("search-cli")
                        .bin_name("search")
                        .current_version(current)
                        .build()
                        .and_then(|u| u.get_latest_release())
                })
                .await
                .map_err(|e| errors::SearchError::Config(format!("update task failed: {e}")))?;

                match res {
                    Ok(release) => {
                        let up_to_date = release.version == current;
                        if ctx.is_json() {
                            output::json::render_value(&serde_json::json!({
                                "version": types::ENVELOPE_VERSION,
                                "status": "success",
                                "current_version": current,
                                "latest_version": release.version,
                                "update_available": !up_to_date,
                            }));
                        } else if !ctx.suppress_human() {
                            if !up_to_date {
                                eprintln!("Current version: {current}");
                                eprintln!("New version available: {}", release.version);
                                eprintln!("Run `search update` to install");
                            } else {
                                eprintln!("Already up to date (v{current})");
                            }
                        }
                        Ok(0)
                    }
                    Err(e) => {
                        let err = errors::SearchError::Api {
                            provider: "github",
                            code: "update_check_failed",
                            message: e.to_string(),
                            status: None,
                        };
                        if ctx.is_json() {
                            output::json::render_error(&err);
                        } else {
                            eprintln!("Could not check for updates: {e}");
                        }
                        Ok(err.exit_code())
                    }
                }
            } else {
                if !ctx.suppress_human() {
                    eprintln!("Updating search from v{current}...");
                }
                let res = tokio::task::spawn_blocking(
                    move || -> Result<_, self_update::errors::Error> {
                        // self_update's default .update() can resolve to the wrong
                        // (older) release when several are newer than current. Pin
                        // it to the actual latest tag (get_latest_release is correct).
                        let latest = self_update::backends::github::Update::configure()
                            .repo_owner("paperfoot")
                            .repo_name("search-cli")
                            .bin_name("search")
                            .current_version(current)
                            .build()?
                            .get_latest_release()?;
                        self_update::backends::github::Update::configure()
                            .repo_owner("paperfoot")
                            .repo_name("search-cli")
                            .bin_name("search")
                            .current_version(current)
                            .target_version_tag(&format!("v{}", latest.version))
                            .build()?
                            .update()
                    },
                )
                .await
                .map_err(|e| errors::SearchError::Config(format!("update task failed: {e}")))?;

                match res {
                    Ok(status) => {
                        if ctx.is_json() {
                            output::json::render_value(&serde_json::json!({
                                "version": types::ENVELOPE_VERSION,
                                "status": "success",
                                "updated": status.updated(),
                                "version_installed": status.version(),
                            }));
                        } else if !ctx.suppress_human() {
                            if status.updated() {
                                eprintln!("Updated to v{}", status.version());
                            } else {
                                eprintln!("Already up to date (v{current})");
                            }
                        }
                        Ok(0)
                    }
                    Err(e) => {
                        let err = errors::SearchError::Config(format!("Update failed: {e}"));
                        if ctx.is_json() {
                            output::json::render_error(&err);
                        } else {
                            eprintln!("Update failed: {e}");
                            eprintln!(
                                "You can update manually: cargo install agent-search --locked"
                            );
                        }
                        Ok(err.exit_code())
                    }
                }
            }
        }
    }
}