vtcode-core 0.177.1

Core library for VT Code - a Rust-based terminal coding agent
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
use super::*;
use serde_json::{Value, json};

async fn execute_json(tool: &WebFetchTool, args: Value) -> Value {
    tool.execute(args)
        .await
        .expect("web_fetch should return structured JSON output")
}

fn error_text(result: &Value) -> Option<&str> {
    result.get("error").and_then(Value::as_str)
}

#[tokio::test]
async fn rejects_non_https_urls() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "http://example.com",
            "prompt": "Extract the main content"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("");
    assert!(error.contains("Only HTTPS URLs are allowed"));
}

#[tokio::test]
async fn rejects_local_file_urls_with_read_file_guidance() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "file:///tmp/checkpoint.json",
            "prompt": "Read the file"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("");
    assert!(error.contains("remote HTTP(S) URLs"));
    assert_eq!(result["error_type"], "local_resource");
    assert!(result["next_action"].as_str().unwrap_or("").contains("read_file"));
}

#[tokio::test]
async fn rejects_local_file_urls_before_markdown_backend_routing() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "file:///tmp/checkpoint.json",
            "format": "markdown",
            "prompt": "Read the file"
        }),
    )
    .await;

    assert_eq!(result["error_type"], "local_resource");
    assert!(error_text(&result).unwrap_or("").contains("remote HTTP(S) URLs"));
    assert!(result["next_action"].as_str().unwrap_or("").contains("read_file"));
}

#[tokio::test]
async fn rejects_relative_urls_before_markdown_backend_routing() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "README.md",
            "format": "markdown",
            "prompt": "Read the file"
        }),
    )
    .await;

    assert_eq!(result["error_type"], "local_resource");
    assert!(error_text(&result).unwrap_or("").contains("remote HTTP(S) URLs"));
    assert!(result["next_action"].as_str().unwrap_or("").contains("unified_file"));
}

#[tokio::test]
async fn rejects_relative_urls_before_normal_fetch_routing() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "README.md",
            "prompt": "Read the file"
        }),
    )
    .await;

    assert_eq!(result["error_type"], "local_resource");
    assert!(error_text(&result).unwrap_or("").contains("remote HTTP(S) URLs"));
    assert!(result["next_action"].as_str().unwrap_or("").contains("unified_file"));
}

#[tokio::test]
async fn allows_http_when_https_disabled() {
    let tool = WebFetchTool::with_config(
        vtcode_config::WebFetchMode::Restricted,
        Vec::new(),
        Vec::new(),
        Vec::new(),
        false, // strict_https_only = false
    );
    let result = execute_json(
        &tool,
        json!({
            "url": "http://example.com",
            "prompt": "Extract the main content"
        }),
    )
    .await;
    if let Some(error) = error_text(&result) {
        assert!(!error.contains("Only HTTPS URLs are allowed"));
    }
}

#[tokio::test]
async fn rejects_localhost_urls() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "https://localhost:8080",
            "prompt": "Extract the main content"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("");
    assert!(error.contains("local/private networks"));
}

#[tokio::test]
async fn requires_both_url_and_prompt() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "http://example.com"
        }),
    )
    .await;
    // Prompt should be auto-filled; URL then fails HTTPS policy.
    let error = error_text(&result).unwrap_or("");
    assert!(error.contains("Only HTTPS URLs are allowed"));
}

#[tokio::test]
async fn rejects_sensitive_banking_domains() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "https://paypal.com/login",
            "prompt": "Extract the main content"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("");
    assert!(error.contains("blocked for privacy and security reasons"));
}

#[tokio::test]
async fn rejects_sensitive_auth_domains() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "https://accounts.google.com",
            "prompt": "Extract the main content"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("");
    assert!(error.contains("blocked for privacy and security reasons"));
}

#[tokio::test]
async fn rejects_urls_with_credentials() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "https://example.com?password=secret123",
            "prompt": "Extract the main content"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("");
    assert!(error.contains("sensitive pattern"));
}

#[tokio::test]
async fn rejects_urls_with_api_keys() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "https://api.example.com?api_key=sk_live_123456",
            "prompt": "Extract the main content"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("");
    assert!(error.contains("sensitive pattern"));
}

#[tokio::test]
async fn rejects_urls_with_tokens() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "https://example.com?token=xyz123",
            "prompt": "Extract the main content"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("");
    assert!(error.contains("sensitive pattern"));
}

#[tokio::test]
async fn rejects_malicious_url_patterns() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "https://example.com/malware.exe\"",
            "prompt": "Extract the main content"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("");
    assert!(error.contains("potentially malicious pattern"));
}

#[tokio::test]
async fn rejects_typosquatting_domains() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "https://g00gle.com",
            "prompt": "Extract the main content"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("");
    assert!(error.contains("potentially malicious pattern"));
}

#[tokio::test]
async fn rejects_url_shorteners() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "https://bit.ly/xyz123",
            "prompt": "Extract the main content"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("");
    assert!(error.contains("potentially malicious pattern"));
}

#[tokio::test]
async fn whitelist_mode_requires_allowed_domains() {
    let tool = WebFetchTool::with_config(
        vtcode_config::WebFetchMode::Whitelist,
        Vec::new(),
        Vec::new(),
        Vec::new(), // No allowed domains
        true,
    );
    let result = execute_json(
        &tool,
        json!({
            "url": "https://example.com",
            "prompt": "Extract the main content"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("").to_string();
    assert!(error.contains("whitelist") || error.contains("whitelisted"));
}

#[tokio::test]
async fn whitelist_mode_allows_whitelisted_domains() {
    let tool = WebFetchTool::with_config(
        vtcode_config::WebFetchMode::Whitelist,
        Vec::new(),
        Vec::new(),
        vec!["example.com".to_string()], // Only example.com allowed
        true,
    );
    let result = execute_json(
        &tool,
        json!({
            "url": "https://example.com/path",
            "prompt": "Extract the main content"
        }),
    )
    .await;
    if let Some(error) = error_text(&result) {
        assert!(!error.contains("not in the whitelist"));
    }
}

#[tokio::test]
async fn whitelist_mode_rejects_non_whitelisted_domains() {
    let tool = WebFetchTool::with_config(
        vtcode_config::WebFetchMode::Whitelist,
        Vec::new(),
        Vec::new(),
        vec!["allowed.com".to_string()],
        true,
    );
    let result = execute_json(
        &tool,
        json!({
            "url": "https://notallowed.com",
            "prompt": "Extract the main content"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("").to_string();
    assert!(error.contains("not in the whitelist"));
}

#[tokio::test]
async fn restricted_mode_allows_exemptions() {
    let tool = WebFetchTool::with_config(
        vtcode_config::WebFetchMode::Restricted,
        Vec::new(),
        Vec::new(),
        vec!["paypal.com".to_string()], // Exempt from blocklist
        true,
    );
    let result = execute_json(
        &tool,
        json!({
            "url": "https://paypal.com/login",
            "prompt": "Extract the main content"
        }),
    )
    .await;
    if let Some(error) = error_text(&result) {
        assert!(!error.contains("blocked for privacy"));
    }
}

#[tokio::test]
async fn custom_blocked_domains_work() {
    let tool = WebFetchTool::with_config(
        vtcode_config::WebFetchMode::Restricted,
        vec!["custom-blocked.com".to_string()], // Custom blocked domain
        Vec::new(),
        Vec::new(),
        true,
    );
    let result = execute_json(
        &tool,
        json!({
            "url": "https://custom-blocked.com/page",
            "prompt": "Extract the main content"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("").to_string();
    assert!(error.contains("blocked for privacy and security reasons"));
}

#[tokio::test]
async fn custom_blocked_patterns_work() {
    let tool = WebFetchTool::with_config(
        vtcode_config::WebFetchMode::Restricted,
        Vec::new(),
        vec!["custom_secret=".to_string()], // Custom pattern
        Vec::new(),
        true,
    );
    let result = execute_json(
        &tool,
        json!({
            "url": "https://example.com?custom_secret=abc123",
            "prompt": "Extract the main content"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("").to_string();
    assert!(error.contains("sensitive pattern"));
}

#[test]
fn default_headers_contain_text_markdown_accept() {
    let headers = WebFetchTool::default_headers();
    assert!(headers.contains_key(ACCEPT));
    let val = headers.get(ACCEPT).unwrap().to_str().unwrap();
    assert!(val.contains("text/markdown"));
}

#[test]
fn oversized_body_is_truncated_instead_of_rejected() {
    let fetched = fetched_content_from_bytes("αβγ".as_bytes(), 3).expect("valid utf-8 prefix should be returned");

    assert_eq!(fetched.content, "α");
    assert!(fetched.truncated_by_max_bytes);
    assert_eq!(fetched.source_size_bytes, "αβγ".len());
}

#[test]
fn truncation_backs_off_to_utf8_boundary_in_one_pass() {
    // Regression: the old implementation decremented `end` byte-by-byte,
    // which is O(n^2) on bodies whose prefix ends mid-multibyte-char. A 1MB
    // body of multibyte chars must truncate via `valid_up_to()` without
    // producing invalid UTF-8.
    let body = "界".repeat(500_000); // 3 bytes per char, 1.5MB total
    let max_bytes = 1_000_000; // cuts mid-char (not multiple of 3)
    let fetched = fetched_content_from_bytes(body.as_bytes(), max_bytes).expect("valid utf-8 prefix");
    assert!(fetched.truncated_by_max_bytes);
    assert!(fetched.content.len() <= max_bytes);
    assert!(
        fetched.content.len().is_multiple_of(3),
        "must end on a char boundary, got {}",
        fetched.content.len()
    );
}

#[test]
fn body_ending_exactly_at_cap_is_still_truncated() {
    // A body that is exactly `max_bytes` long is NOT truncated; one that
    // ends precisely at the cap after streaming must not be reported as
    // untruncated by the stream path. `fetched_content_from_bytes` alone
    // sees bytes.len() == max_bytes, so callers override the flag.
    let exact = fetched_content_from_bytes("abcde".as_bytes(), 5).expect("utf-8");
    assert!(!exact.truncated_by_max_bytes);

    // Multi-char exact fit that lands on a boundary is also not truncated.
    let fit = fetched_content_from_bytes("αβγ".as_bytes(), 6).expect("utf-8");
    assert!(!fit.truncated_by_max_bytes);
    assert_eq!(fit.content, "αβγ");
}

#[test]
fn description_guides_agents_to_try_llms_txt_first() {
    let tool = WebFetchTool::new();
    let description = tool.description();

    assert!(description.contains("/llms.txt"));
    assert!(description.contains("abc.com"));
    assert!(description.contains("https://abc.com/llms.txt"));
    assert!(description.contains("traverse"));
}

#[test]
fn max_bytes_and_timeout_are_clamped_to_hard_caps() {
    const _: () = {
        assert!(MAX_ALLOWED_BYTES >= MAX_CONTENT_SIZE);
        assert!(MAX_ALLOWED_TIMEOUT_SECS >= DEFAULT_TIMEOUT_SECS);
        assert!(MAX_ALLOWED_BYTES <= 10_000_000); // sanity: under 10MB
        assert!(MAX_ALLOWED_TIMEOUT_SECS <= 300); // sanity: under 5 minutes
    };
}

#[test]
fn ipv4_mapped_ipv6_loopback_is_private() {
    // ::ffff:127.0.0.1 should be caught as loopback
    assert!(is_private_host("::ffff:127.0.0.1"));
}

#[test]
fn ipv4_mapped_ipv6_private_is_private() {
    // ::ffff:10.0.0.1 should be caught as private (class A)
    assert!(is_private_host("::ffff:10.0.0.1"));
    // ::ffff:192.168.1.1 should be caught as private (class C)
    assert!(is_private_host("::ffff:192.168.1.1"));
    // ::ffff:172.16.0.1 should be caught as private (class B)
    assert!(is_private_host("::ffff:172.16.0.1"));
}

#[test]
fn ipv4_mapped_ipv6_link_local_is_private() {
    // ::ffff:169.254.0.1 should be caught as link-local
    assert!(is_private_host("::ffff:169.254.0.1"));
}

#[test]
fn ipv4_compatible_ipv6_loopback_is_private() {
    // ::127.0.0.1 (IPv4-compatible) should be caught
    assert!(is_private_host("::127.0.0.1"));
}

#[test]
fn ipv6_loopback_is_private() {
    assert!(is_private_host("::1"));
}

#[test]
fn ipv6_unique_local_is_private() {
    assert!(is_private_host("fd00::1"));
}

#[test]
fn ipv6_link_local_is_private() {
    assert!(is_private_host("fe80::1"));
}

#[test]
fn ipv4_mapped_ipv6_public_is_not_private() {
    // ::ffff:8.8.8.8 (Google DNS) should NOT be blocked
    assert!(!is_private_host("::ffff:8.8.8.8"));
}

#[tokio::test]
async fn rejects_localhost_tld() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "https://myapp.localhost/api",
            "prompt": "Extract content"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("");
    assert!(error.contains("local/private networks"));
}

/// Regression test for the "who is vinhnx?" case. The default
/// `WebFetchConfig` seeds `allowed_domains` with common developer sites
/// (github.com, npmjs.com, crates.io, etc.). The default `Restricted`
/// mode honors those exemptions, so URLs on those hosts must pass
/// `validate_url` without touching the network.
#[test]
fn default_restricted_mode_allows_common_dev_sites() {
    let tool = WebFetchTool::from_config(&vtcode_config::WebFetchConfig::default());
    // After H1: the defaults come from the TOML allowlist filtered
    // to web-fetch-relevant categories. `docs.rs` and `www.npmjs.com`
    // are not in the TOML and are no longer in defaults; replace
    // them with registry hosts that ARE in the TOML.
    for url in [
        "https://github.com/vinhnx",
        "https://github.com/vinhnx?tab=repositories",
        "https://api.github.com/users/vinhnx",
        "https://api.github.com/users/vinhnx/repos?sort=stars&per_page=20",
        "https://registry.npmjs.org/vinhnx",
        "https://crates.io/users/vinhnx",
        "https://raw.githubusercontent.com/rust-lang/rust/master/README.md",
        "https://en.wikipedia.org/wiki/Rust_(programming_language)",
        "https://pypi.org/project/requests/",
        "https://r.jina.ai/https://example.com",
    ] {
        tool.validate_url(url)
            .unwrap_or_else(|e| panic!("default restricted mode should allow {url}: {e}"));
    }
}

/// Whitelist mode is a strict allowlist: only the user's explicit
/// `allowed_domains` apply, even if the defaults include the host.
/// This test constructs a tool with `Whitelist` mode and an empty
/// user allow list to assert the strict contract.
#[test]
fn whitelist_mode_is_strict_when_user_allow_list_is_empty() {
    let tool = WebFetchTool::from_config(&vtcode_config::WebFetchConfig {
        mode: vtcode_config::WebFetchMode::Whitelist,
        allowed_domains: Vec::new(),
        ..vtcode_config::WebFetchConfig::default()
    });
    let err = tool
        .validate_url("https://github.com/vinhnx")
        .expect_err("whitelist mode must reject domains not in the user allow list");
    assert!(err.to_string().contains("whitelist"), "unexpected error: {err}");
}

#[test]
fn domain_matches_allowed_handles_wildcards() {
    // Apex + subdomains under a wildcard.
    assert!(domain_matches_allowed("example.com", "*.example.com"));
    assert!(domain_matches_allowed("api.example.com", "*.example.com"));
    assert!(domain_matches_allowed("deep.nested.api.example.com", "*.example.com"));
    // Negative matches — wildcard must not be a substring match.
    assert!(!domain_matches_allowed("evilexample.com", "*.example.com"));
    assert!(!domain_matches_allowed("example.com.evil.tld", "*.example.com"));
    // Apex match is also accepted.
    assert!(domain_matches_allowed("example.com", "example.com"));
    assert!(domain_matches_allowed("api.example.com", "example.com"));
}

#[test]
fn domain_matches_allowed_rejects_single_label_wildcards() {
    // L10 (review): a wildcard like `*.com` would match every `.com`
    // host. That's almost certainly a misconfiguration; refuse it
    // outright so an editor who fat-fingers the allowlist doesn't
    // accidentally open the whole TLD.
    assert!(!domain_matches_allowed("example.com", "*.com"));
    assert!(!domain_matches_allowed("api.example.com", "*.com"));
    assert!(!domain_matches_allowed("co.uk", "*.uk"));
    // A multi-label suffix is still allowed.
    assert!(domain_matches_allowed("example.co.uk", "*.co.uk"));
}

#[test]
fn default_allowlist_includes_wildcard_categories() {
    // After H1: the web_fetch defaults are filtered to web-relevant
    // categories. The TOML currently has no `*.foo` wildcards in
    // those categories, so the defaults should not contain any.
    // The matcher itself is still tested for wildcards via
    // `domain_matches_allowed_handles_wildcards` above.
    let config = vtcode_config::WebFetchConfig::default();
    let wildcards: Vec<&str> = config
        .allowed_domains
        .iter()
        .map(|s| s.as_str())
        .filter(|s| s.starts_with("*."))
        .collect();
    assert!(
        wildcards.is_empty(),
        "expected no wildcards in default web_fetch allowlist (TOML has them only in auth/dev_infra which are excluded); got {wildcards:?}"
    );
}

#[test]
fn default_restricted_mode_lets_through_wildcard_hosts() {
    // Regression for the broader TOML allowlist: a URL on a wildcard
    // host should pass `validate_url` under the default `Restricted`
    // mode without any per-session config. The TOML only has wildcards
    // in `auth` / `dev_infra` (excluded by H1), so we exercise the
    // matcher with a user-supplied wildcard instead.
    let tool = WebFetchTool::from_config(&vtcode_config::WebFetchConfig {
        allowed_domains: vec!["*.example.com".to_string()],
        ..vtcode_config::WebFetchConfig::default()
    });
    for url in [
        "https://acme.example.com/authorize",
        "https://deep.nested.api.example.com/api",
    ] {
        tool.validate_url(url)
            .unwrap_or_else(|e| panic!("wildcard allow should accept {url}: {e}"));
    }
}

#[tokio::test]
async fn rejects_test_tld() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "https://example.test/page",
            "prompt": "Extract content"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("");
    assert!(error.contains("local/private networks"));
}

#[tokio::test]
async fn rejects_invalid_tld() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "https://example.invalid/page",
            "prompt": "Extract content"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("");
    assert!(error.contains("local/private networks"));
}

#[tokio::test]
async fn rejects_home_arpa_tld() {
    let tool = WebFetchTool::new();
    let result = execute_json(
        &tool,
        json!({
            "url": "https://myhost.home.arpa/page",
            "prompt": "Extract content"
        }),
    )
    .await;
    let error = error_text(&result).unwrap_or("");
    assert!(error.contains("local/private networks"));
}

/// Regression test for turn_578: a real HTTP 403 from npmjs.com
/// (server-side bot block) must come back as `error_type=http_error`
/// with `http_status=403`, NOT as a "policy_blocked" or "PermissionDenied"
/// response. The agent in turn_578 reported the host as "blocked by the
/// sandbox" because the error format only carried a flat string.
#[test]
fn classifies_http_403_as_server_block_not_policy() {
    let err = anyhow::anyhow!("HTTP request failed with status: 403 Forbidden");
    let response = web_fetch_error_response("https://www.npmjs.com/~vinhnx", 262144, 30, &err);
    assert_eq!(response["error_type"], "http_error");
    assert_eq!(response["http_status"], 403);
    let action = response["next_action"].as_str().unwrap_or("");
    assert!(
        action.contains("anti-bot") || action.contains("rate-limited"),
        "next_action should hint at anti-bot / rate-limit, got: {action}"
    );
}

/// Regression test for turn_578: a real HTTP 404 from crates.io (the
/// user does not exist) must come back as `error_type=http_error`
/// with `http_status=404` and a "the resource does not exist" hint.
#[test]
fn classifies_http_404_with_verify_url_hint() {
    let err = anyhow::anyhow!("HTTP request failed with status: 404 Not Found");
    let response = web_fetch_error_response("https://crates.io/users/vinhnx", 262144, 30, &err);
    assert_eq!(response["error_type"], "http_error");
    assert_eq!(response["http_status"], 404);
    let action = response["next_action"].as_str().unwrap_or("");
    assert!(action.contains("does not exist"), "next_action was: {action}");
}

/// 5xx responses are transient — the hint should nudge the agent to
/// either retry briefly or use web_search as a fallback.
#[test]
fn classifies_http_5xx_as_transient() {
    let err = anyhow::anyhow!("HTTP request failed with status: 503 Service Unavailable");
    let response = web_fetch_error_response("https://example.com", 262144, 30, &err);
    assert_eq!(response["error_type"], "http_error");
    assert_eq!(response["http_status"], 503);
    let action = response["next_action"].as_str().unwrap_or("");
    assert!(action.contains("retry") || action.contains("search"), "got: {action}");
}

/// Network-level errors (timeout, DNS, TLS) should be classified
/// distinctly from HTTP errors so the agent can pick the right
/// fallback.
#[test]
fn classifies_timeout_as_network_error() {
    let err = anyhow::anyhow!("request timed out");
    let response = web_fetch_error_response("https://example.com", 262144, 30, &err);
    assert_eq!(response["error_type"], "network_error");
    assert!(response.get("http_status").is_none() || response["http_status"].is_null());
}

#[test]
fn classifies_tls_error_separately() {
    let err = anyhow::anyhow!("TLS handshake failed: certificate verify failed");
    let response = web_fetch_error_response("https://example.com", 262144, 30, &err);
    assert_eq!(response["error_type"], "tls_error");
}

/// The error response must always carry a `next_action` so the agent
/// loop can decide what to do without re-parsing the free-form message.
#[test]
fn every_error_response_has_next_action() {
    let samples = [
        anyhow::anyhow!("HTTP request failed with status: 418 I'm a teapot"),
        anyhow::anyhow!("dns error: no such host"),
        anyhow::anyhow!("something completely unexpected"),
    ];
    for err in &samples {
        let response = web_fetch_error_response("https://example.com", 262144, 30, err);
        let action = response["next_action"].as_str().unwrap_or("");
        assert!(!action.is_empty(), "next_action must be non-empty; got response {response}");
    }
}

#[test]
fn extract_http_status_delegates_to_classify_helpers() {
    // The local function delegates to `classify_helpers::extract_http_status`,
    // which is the canonical parser. These cases mirror the helpers'
    // own tests so a regression in the delegate is caught here too.
    assert_eq!(extract_http_status("status: 403 Forbidden"), Some(403));
    assert_eq!(
        extract_http_status("HTTP status server error (503 Service Unavailable) for url (https://example.com/)"),
        Some(503)
    );
    assert_eq!(extract_http_status("status:  500 Internal"), Some(500));
    assert_eq!(extract_http_status("no status here"), None);
}