captchaforge 0.2.36

[DO NOT USE — UNDER ACTIVE DEVELOPMENT, NOT PRODUCTION-READY] Captcha solver scaffolding for chromiumoxide-driven browsers. The architecture is in place (vendor solvers, retry-loop iframe walking, VLM provider abstraction, real-WAF bench harness) but the live-vendor success rate is still 0% — Cloudflare Turnstile / hCaptcha / reCAPTCHA detect us at a TLS / CDP fingerprint layer that no flag-based stealth has cleared. Watch the repo; do not depend on this for any real workload.
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
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
use super::*;

// ─── VLM provider abstraction ────────────────────────────────────────────────
//
// Three back-ends supported, picked in this priority order at construction
// time:
//
//   1. **Anthropic Claude** — when `ANTHROPIC_API_KEY` is set in the env.
//      Strongest visual reasoning of the three; recommended for image-grid
//      captchas that need spatial understanding ("select all crosswalks").
//      Default model: `claude-haiku-4-5` (fast + cheap; switch to
//      `claude-sonnet-4-6` via `CAPTCHAFORGE_VLM_MODEL` for harder grids).
//
//   2. **OpenAI** — when `OPENAI_API_KEY` is set and Anthropic isn't.
//      Default model: `gpt-4o-mini`.
//
//   3. **Ollama (local)** — fallback when no API key is present. The
//      "anyone-can-run-this-bench" path: works with a locally-installed
//      Ollama running `llama3.2-vision:11b` (the bench's reproducibility
//      contract — no API keys, no paid SaaS, just `ollama serve` +
//      `ollama pull llama3.2-vision:11b`). Endpoint defaults to
//      `http://localhost:11434`.
//
// The provider abstraction is honoured even when `with_endpoint` /
// `with_model` are called explicitly — those override the per-provider
// defaults but don't change the back-end. Use `with_provider` to switch
// back-ends from code (e.g. force Ollama for an integration test).

const DEFAULT_OLLAMA_BASE: &str = "http://localhost:11434";
const DEFAULT_OLLAMA_MODEL: &str = "llama3.2-vision:11b";
const DEFAULT_ANTHROPIC_BASE: &str = "https://api.anthropic.com";
const DEFAULT_ANTHROPIC_MODEL: &str = "claude-haiku-4-5";
const DEFAULT_OPENAI_BASE: &str = "https://api.openai.com";
const DEFAULT_OPENAI_MODEL: &str = "gpt-4o-mini";

const ENV_VLM_ENDPOINT: &str = "CAPTCHAFORGE_VLM_ENDPOINT";
const ENV_VLM_MODEL: &str = "CAPTCHAFORGE_VLM_MODEL";
const ENV_ANTHROPIC_KEY: &str = "ANTHROPIC_API_KEY";
const ENV_OPENAI_KEY: &str = "OPENAI_API_KEY";

/// Which VLM back-end to call. See module-level docs for the
/// auto-detection priority + per-provider defaults.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VlmProvider {
    /// Local Ollama instance — the default-everyone-can-reproduce path.
    /// No API key required; talks to `/api/generate`.
    Ollama,
    /// Anthropic Claude vision API — picked when `ANTHROPIC_API_KEY` is set.
    /// Talks to `/v1/messages` with image content blocks.
    Anthropic,
    /// OpenAI GPT-4o vision — picked when `OPENAI_API_KEY` is set
    /// (and Anthropic is not). Talks to `/v1/chat/completions` with
    /// image_url content parts.
    OpenAI,
}

impl VlmProvider {
    fn default_endpoint(self) -> &'static str {
        match self {
            Self::Ollama => DEFAULT_OLLAMA_BASE,
            Self::Anthropic => DEFAULT_ANTHROPIC_BASE,
            Self::OpenAI => DEFAULT_OPENAI_BASE,
        }
    }
    fn default_model(self) -> &'static str {
        match self {
            Self::Ollama => DEFAULT_OLLAMA_MODEL,
            Self::Anthropic => DEFAULT_ANTHROPIC_MODEL,
            Self::OpenAI => DEFAULT_OPENAI_MODEL,
        }
    }
}

/// Raw Ollama `/api/generate` request body.
#[derive(Debug, Serialize)]
struct OllamaRequest<'a> {
    model: &'a str,
    prompt: &'a str,
    images: Vec<String>,
    stream: bool,
}

/// Relevant fields from Ollama `/api/generate` response.
#[derive(Debug, Deserialize)]
struct OllamaResponse {
    response: String,
}

/// Send a screenshot (base64 PNG/JPEG) and a text prompt to a VLM endpoint.
/// Returns the model's raw text reply. Dispatches to the appropriate
/// per-provider adapter; the calling code stays provider-agnostic.
async fn vlm_query(
    client: &reqwest::Client,
    provider: VlmProvider,
    endpoint: &str,
    model: &str,
    api_key: Option<&str>,
    image_b64: &str,
    prompt: &str,
    timeout_ms: u64,
) -> Result<String> {
    match provider {
        VlmProvider::Ollama => vlm_query_ollama(client, endpoint, model, image_b64, prompt, timeout_ms).await,
        VlmProvider::Anthropic => {
            let key = api_key.ok_or_else(|| anyhow!("anthropic provider needs api_key"))?;
            vlm_query_anthropic(client, endpoint, model, key, image_b64, prompt, timeout_ms).await
        }
        VlmProvider::OpenAI => {
            let key = api_key.ok_or_else(|| anyhow!("openai provider needs api_key"))?;
            vlm_query_openai(client, endpoint, model, key, image_b64, prompt, timeout_ms).await
        }
    }
}

async fn vlm_query_ollama(
    client: &reqwest::Client,
    endpoint: &str,
    model: &str,
    image_b64: &str,
    prompt: &str,
    timeout_ms: u64,
) -> Result<String> {
    let req = OllamaRequest {
        model,
        prompt,
        images: vec![image_b64.to_string()],
        stream: false,
    };
    let resp = client
        .post(format!("{}/api/generate", endpoint.trim_end_matches('/')))
        .json(&req)
        .timeout(Duration::from_millis(timeout_ms))
        .send()
        .await
        .map_err(|e| anyhow!("ollama request failed: {}", e))?;
    if !resp.status().is_success() {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        return Err(anyhow!("ollama returned {}: {}", status, body));
    }
    let ollama_resp: OllamaResponse = resp
        .json()
        .await
        .map_err(|e| anyhow!("ollama json parse: {}", e))?;
    Ok(ollama_resp.response)
}

/// Anthropic Messages API call with a single image content block.
/// Image must be base64-encoded PNG (the page-screenshot format the
/// solver already produces); we hardcode `image/png` accordingly.
async fn vlm_query_anthropic(
    client: &reqwest::Client,
    endpoint: &str,
    model: &str,
    api_key: &str,
    image_b64: &str,
    prompt: &str,
    timeout_ms: u64,
) -> Result<String> {
    let body = serde_json::json!({
        "model": model,
        "max_tokens": 512,
        "messages": [{
            "role": "user",
            "content": [
                { "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": image_b64 } },
                { "type": "text", "text": prompt },
            ],
        }],
    });
    let resp = client
        .post(format!("{}/v1/messages", endpoint.trim_end_matches('/')))
        .header("x-api-key", api_key)
        .header("anthropic-version", "2023-06-01")
        .header("content-type", "application/json")
        .json(&body)
        .timeout(Duration::from_millis(timeout_ms))
        .send()
        .await
        .map_err(|e| anyhow!("anthropic request failed: {}", e))?;
    if !resp.status().is_success() {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        return Err(anyhow!("anthropic returned {}: {}", status, body));
    }
    let val: serde_json::Value = resp.json().await.map_err(|e| anyhow!("anthropic json parse: {}", e))?;
    // Response shape: { content: [{ type: "text", text: "..." }, ...] }
    val["content"]
        .as_array()
        .and_then(|arr| arr.iter().find(|c| c["type"] == "text"))
        .and_then(|c| c["text"].as_str())
        .map(|s| s.to_string())
        .ok_or_else(|| anyhow!("anthropic response missing text content: {val}"))
}

async fn vlm_query_openai(
    client: &reqwest::Client,
    endpoint: &str,
    model: &str,
    api_key: &str,
    image_b64: &str,
    prompt: &str,
    timeout_ms: u64,
) -> Result<String> {
    let data_url = format!("data:image/png;base64,{}", image_b64);
    let body = serde_json::json!({
        "model": model,
        "max_tokens": 512,
        "messages": [{
            "role": "user",
            "content": [
                { "type": "text", "text": prompt },
                { "type": "image_url", "image_url": { "url": data_url } },
            ],
        }],
    });
    let resp = client
        .post(format!("{}/v1/chat/completions", endpoint.trim_end_matches('/')))
        .header("authorization", format!("Bearer {}", api_key))
        .header("content-type", "application/json")
        .json(&body)
        .timeout(Duration::from_millis(timeout_ms))
        .send()
        .await
        .map_err(|e| anyhow!("openai request failed: {}", e))?;
    if !resp.status().is_success() {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        return Err(anyhow!("openai returned {}: {}", status, body));
    }
    let val: serde_json::Value = resp.json().await.map_err(|e| anyhow!("openai json parse: {}", e))?;
    // Response shape: { choices: [{ message: { content: "..." } }] }
    val["choices"][0]["message"]["content"]
        .as_str()
        .map(|s| s.to_string())
        .ok_or_else(|| anyhow!("openai response missing content: {val}"))
}

/// Extract the first JSON object embedded in free-form text (handles markdown fences).
pub(crate) fn extract_json(text: &str) -> Option<&str> {
    if let Some(start) = text.find("```json") {
        let rest = &text[start + 7..];
        if let Some(end) = rest.find("```") {
            return Some(rest[..end].trim());
        }
    }
    if let Some(start) = text.find('{') {
        let rest = &text[start..];
        let mut depth = 0;
        let mut end = None;
        for (i, c) in rest.char_indices() {
            match c {
                '{' => depth += 1,
                '}' => {
                    depth -= 1;
                    if depth == 0 {
                        end = Some(i + 1);
                        break;
                    }
                }
                _ => {}
            }
        }
        if let Some(e) = end {
            return Some(&rest[..e]);
        }
    }
    None
}

// ─── VlmCaptchaSolver ─────────────────────────────────────────────────────────

/// Solves image-based CAPTCHAs via a vision-language model (VLM) such as
/// Ollama-hosted llama3.2-vision.
///
/// Supported sub-types:
///   * Image-grid   (reCAPTCHA / hCaptcha "select all traffic lights")
///   * Text-based   (type the characters shown)
///   * Click-target (click on a specific object / button)
pub struct VlmCaptchaSolver {
    pub(crate) client: reqwest::Client,
    pub(crate) provider: VlmProvider,
    pub(crate) endpoint: String,
    pub(crate) model: String,
    pub(crate) api_key: Option<String>,
    pub(crate) config: SolveConfig,
}

impl Default for VlmCaptchaSolver {
    fn default() -> Self {
        Self::new()
    }
}

impl VlmCaptchaSolver {
    pub fn new() -> Self {
        Self::new_with_env(|name| std::env::var(name).ok())
    }

    /// Construct a solver, using the supplied closure to look up env
    /// variables. The public [`Self::new`] uses [`std::env::var`];
    /// tests use this overload to assert env precedence without
    /// mutating real process env (which is `unsafe` in the 2024
    /// edition and forbidden by the crate's `#![forbid(unsafe_code)]`).
    pub(crate) fn new_with_env<F>(env: F) -> Self
    where
        F: Fn(&str) -> Option<String>,
    {
        let config = SolveConfig::default();
        // Provider auto-detection priority: ANTHROPIC_API_KEY > OPENAI_API_KEY
        // > Ollama. Anthropic wins because Claude's vision is the strongest
        // for the spatial-reasoning image-grid case ("select all crosswalks").
        // Users who want a specific back-end set the matching env var.
        let api_key_anthropic = env(ENV_ANTHROPIC_KEY).filter(|s| !s.is_empty());
        let api_key_openai = env(ENV_OPENAI_KEY).filter(|s| !s.is_empty());
        let (provider, api_key) = if let Some(k) = api_key_anthropic {
            (VlmProvider::Anthropic, Some(k))
        } else if let Some(k) = api_key_openai {
            (VlmProvider::OpenAI, Some(k))
        } else {
            (VlmProvider::Ollama, None)
        };
        // Endpoint + model: explicit env wins, else per-provider default.
        let endpoint = env(ENV_VLM_ENDPOINT)
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| provider.default_endpoint().to_string());
        let model = env(ENV_VLM_MODEL)
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| provider.default_model().to_string());
        Self {
            client: reqwest::Client::builder()
                .timeout(Duration::from_millis(config.client_http_timeout_ms))
                .build()
                .unwrap_or_else(|_| reqwest::Client::new()),
            provider,
            endpoint,
            model,
            api_key,
            config,
        }
    }

    /// Force a specific provider (overrides env auto-detection). Useful
    /// for integration tests that need to pin Ollama even when an env
    /// API key is present, or for callers that want to ship a specific
    /// fallback chain.
    pub fn with_provider(mut self, provider: VlmProvider) -> Self {
        self.provider = provider;
        if self.endpoint.is_empty() {
            self.endpoint = provider.default_endpoint().to_string();
        }
        self
    }

    /// Provide an explicit API key (overrides env auto-detection).
    pub fn with_api_key(mut self, key: impl Into<String>) -> Self {
        self.api_key = Some(key.into());
        self
    }

    /// Override the VLM endpoint (default: `http://localhost:11434`).
    pub fn with_endpoint(mut self, url: impl Into<String>) -> Self {
        self.endpoint = url.into();
        self
    }

    /// Override the VLM model name (default: `llama3.2-vision:11b`).
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.model = model.into();
        self
    }

    /// Provide a custom solve configuration.
    pub fn with_config(mut self, config: SolveConfig) -> Self {
        self.config = config;
        self
    }

    pub fn grid_prompt(task: &str) -> String {
        format!(
            r#"You are solving an image-grid CAPTCHA.
Task: {}
Respond with a JSON object exactly like this:
{{"selected": [0,1,2], "confidence": 0.95}}
where `selected` is a list of zero-based tile indices that match the task.
If none match, use an empty list.
Only respond with the JSON object, no extra text."#,
            task
        )
    }

    pub fn text_captcha_prompt() -> String {
        r#"You are solving a text CAPTCHA.
Read the text in the image and respond with a JSON object exactly like this:
{"text": "answer", "confidence": 0.95}
Only respond with the JSON object, no extra text."#
            .to_string()
    }

    pub fn click_target_prompt(target: &str) -> String {
        format!(
            r#"You are solving a click-target CAPTCHA.
Click the object described as: "{}"
Respond with a JSON object exactly like this:
{{"x": 123, "y": 456, "confidence": 0.95}}
where x and y are pixel coordinates in the screenshot.
Only respond with the JSON object, no extra text."#,
            target
        )
    }
}

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

    fn method(&self) -> SolveMethod {
        SolveMethod::VisionLLM
    }

    fn supports(&self, kind: &crate::captcha_detect::DetectedCaptcha) -> bool {
        use crate::captcha_detect::DetectedCaptcha;
        // VLM screenshot+vision can attempt any visual captcha,
        // including TOML-rule vendors whose providers recommend
        // VisionLLM as a fallback method.
        matches!(
            kind,
            DetectedCaptcha::RecaptchaV2
                | DetectedCaptcha::RecaptchaV3
                | DetectedCaptcha::HCaptcha
                | DetectedCaptcha::ImageCaptcha
                | DetectedCaptcha::Turnstile
                | DetectedCaptcha::CanvasCaptcha
                | DetectedCaptcha::ShadowDomCaptcha
                | DetectedCaptcha::MultiStepCaptcha
                | DetectedCaptcha::SliderCaptcha
                | DetectedCaptcha::Custom(_)
        )
    }

    async fn solve(
        &self,
        page: &Page,
        captcha_info: &crate::captcha_detect::CaptchaInfo,
    ) -> Result<CaptchaSolveResult> {
        let t0 = Instant::now();
        let image_b64 = screenshot_b64(page).await?;

        // Use the detected kind to pick a prompt strategy.
        match captcha_info.kind {
            crate::captcha_detect::DetectedCaptcha::RecaptchaV2
            | crate::captcha_detect::DetectedCaptcha::HCaptcha
            | crate::captcha_detect::DetectedCaptcha::ImageCaptcha => {
                // Image grid challenge. Pull the task description from
                // the page itself (e.g. "Select all icons that are
                // animals") rather than passing a generic instruction —
                // the VLM does much better when the task matches what
                // the user sees.
                let task_text = page
                    .evaluate(
                        r#"(() => {
                            const probes = [
                                '.rc-imageselect-desc-no-canonical', '.rc-imageselect-desc',
                                '.task-text', '.captcha-prompt',
                                '#widget > div', '.captcha-task'
                            ];
                            for (const sel of probes) {
                                const el = document.querySelector(sel);
                                if (el && el.textContent && el.textContent.trim().length > 0) {
                                    return el.textContent.trim();
                                }
                            }
                            return 'Select all matching images';
                        })()"#,
                    )
                    .await
                    .ok()
                    .and_then(|r| r.into_value::<String>().ok())
                    .unwrap_or_else(|| "Select all matching images".to_string());
                let prompt = Self::grid_prompt(&task_text);
                let raw = vlm_query(
                    &self.client,
                    self.provider,
                    &self.endpoint,
                    &self.model,
                    self.api_key.as_deref(),
                    &image_b64,
                    &prompt,
                    self.config.vlm_http_timeout_ms,
                )
                .await?;

                let json_str = extract_json(&raw).unwrap_or(&raw);
                let val: serde_json::Value =
                    serde_json::from_str(json_str).unwrap_or(serde_json::Value::Null);
                let confidence = val["confidence"].as_f64().unwrap_or(0.5) as f32;
                let selected: Vec<usize> = val["selected"]
                    .as_array()
                    .unwrap_or(&vec![])
                    .iter()
                    .filter_map(|v| v.as_u64().map(|n| n as usize))
                    .collect();

                // Click each selected tile via direct DOM dispatch
                // — far more reliable than computing mouse coordinates
                // across iframe boundaries. Probe the grid first to
                // get the actual tile elements + dimensions, then
                // dispatch a click event on each by index.
                //
                // Grid probes per vendor:
                //   - reCAPTCHA v2:  .rc-imageselect-tile (img wrapper)
                //   - hCaptcha:      .task-image (sometimes .image)
                //   - Generic:       td > img inside the grid table
                let click_indices_js = format!(
                    r#"
                    ((indices) => {{
                        const probes = [
                            '.rc-imageselect-tile',
                            '.task-image',
                            '.image-task',
                            '.hcaptcha-checkbox-img',
                            '.rc-imageselect-table td',
                            '.hcaptcha-table td',
                            '.captcha-grid > .tile',
                            // Generic local-grid selectors: icon picker,
                            // color picker, image picker. Order matters
                            // — first non-empty match wins.
                            '#widget .icon-item',
                            '#widget .color-item',
                            '#widget .cell',
                            '#widget .grid > .cell',
                        ];
                        let tiles = null;
                        for (const sel of probes) {{
                            const els = document.querySelectorAll(sel);
                            if (els.length > 0) {{ tiles = Array.from(els); break; }}
                        }}
                        if (!tiles || tiles.length === 0) return {{ ok: false, count: 0 }};
                        let clicked = 0;
                        for (const idx of indices) {{
                            const el = tiles[idx];
                            if (!el) continue;
                            const r = el.getBoundingClientRect();
                            const cx = r.left + r.width / 2;
                            const cy = r.top + r.height / 2;
                            ['mousedown','mouseup','click'].forEach(t => {{
                                el.dispatchEvent(new MouseEvent(t, {{
                                    bubbles: true, button: 0,
                                    clientX: cx, clientY: cy
                                }}));
                            }});
                            clicked++;
                        }}
                        /* Find + click the verify/submit button. */
                        const verifyProbes = [
                            '#recaptcha-verify-button',
                            '.rc-button-default',
                            '.button-submit',
                            '[data-pp="submit"]',
                            'button[type="submit"]',
                            // Generic verify button used by local-mock
                            // grid fixtures (icon_selection,
                            // color_match, image/grid).
                            '#widget #submit',
                            '#widget button',
                        ];
                        for (const sel of verifyProbes) {{
                            const b = document.querySelector(sel);
                            if (b) {{ b.click(); break; }}
                        }}
                        return {{ ok: true, count: clicked, total: tiles.length }};
                    }})({selected})
                    "#,
                    selected = serde_json::to_string(&selected).unwrap_or_else(|_| "[]".into())
                );
                let _ = page.evaluate(click_indices_js).await;

                let success = confidence > 0.5 && !selected.is_empty();
                let cookies = if success {
                    crate::cookies::capture_from_page(page)
                        .await
                        .unwrap_or_default()
                } else {
                    Vec::new()
                };
                Ok(CaptchaSolveResult {
                    solution: serde_json::to_string(&selected).unwrap_or_default(),
                    confidence,
                    method: SolveMethod::VisionLLM,
                    time_ms: t0.elapsed().as_millis() as u64,
                    success,
                    screenshot: None,
                    cookies,
                    verified_outcome: None,
                })
            }
            crate::captcha_detect::DetectedCaptcha::RecaptchaV3
            | crate::captcha_detect::DetectedCaptcha::CanvasCaptcha
            | crate::captcha_detect::DetectedCaptcha::ShadowDomCaptcha => {
                // Text-based challenge — read the rendered text out of
                // a canvas/SVG widget and type it into the response
                // input. CanvasCaptchaDetector covers canvas, SVG,
                // rotated-text, math, icon, and color sub-types; the
                // text path is the right default.
                let prompt = Self::text_captcha_prompt();
                let raw = vlm_query(
                    &self.client,
                    self.provider,
                    &self.endpoint,
                    &self.model,
                    self.api_key.as_deref(),
                    &image_b64,
                    &prompt,
                    self.config.vlm_http_timeout_ms,
                )
                .await?;

                let json_str = extract_json(&raw).unwrap_or(&raw);
                let val: serde_json::Value =
                    serde_json::from_str(json_str).unwrap_or(serde_json::Value::Null);
                let text = val["text"].as_str().unwrap_or("").trim().to_string();
                let confidence = val["confidence"].as_f64().unwrap_or(0.5) as f32;

                // Type the answer into the response field. Try the
                // top-level light DOM first; on miss, walk shadow roots
                // and same-origin iframes to find the input. Mirrors
                // the WaitForTokenSolver's piercing probe.
                let typed_via_pierce = page
                    .evaluate(
                        format!(
                            r#"((answer) => {{
                                function* walkAllRoots(root) {{
                                    const queue = [root];
                                    const seen = new WeakSet();
                                    while (queue.length) {{
                                        const r = queue.shift();
                                        if (seen.has(r)) continue;
                                        seen.add(r);
                                        yield r;
                                        const subtree = r.querySelectorAll ? r.querySelectorAll('*') : [];
                                        for (const el of subtree) {{
                                            if (el.shadowRoot) queue.push(el.shadowRoot);
                                            if (el.tagName === 'IFRAME') {{
                                                let inner = null;
                                                try {{ inner = el.contentDocument; }} catch (_) {{}}
                                                if (inner) queue.push(inner);
                                            }}
                                        }}
                                    }}
                                }}
                                for (const root of walkAllRoots(document)) {{
                                    let inp = null;
                                    try {{ inp = root.querySelector('input[type=text], input:not([type]), textarea, .rc-response-input, input[name="captcha"], input[name="answer"]'); }} catch(_) {{ continue; }}
                                    if (!inp) continue;
                                    inp.focus(); inp.value = answer;
                                    inp.dispatchEvent(new Event('input', {{bubbles: true}}));
                                    inp.dispatchEvent(new Event('change', {{bubbles: true}}));
                                    return true;
                                }}
                                return false;
                            }})({})"#,
                            serde_json::to_string(&text).unwrap_or_else(|_| "\"\"".into())
                        ),
                    )
                    .await
                    .and_then(|r| r.into_value::<bool>().map_err(Into::into))
                    .unwrap_or(false);
                if !typed_via_pierce {
                    // Fallback to find_element click+type if the JS pierce missed.
                    if let Ok(input) = page
                        .find_element("input[type=text], textarea, .rc-response-input")
                        .await
                    {
                        input.click().await.ok();
                        input.type_str(&text).await.ok();
                    }
                }

                let success = confidence > 0.5 && !text.is_empty();
                let cookies = if success {
                    crate::cookies::capture_from_page(page)
                        .await
                        .unwrap_or_default()
                } else {
                    Vec::new()
                };
                Ok(CaptchaSolveResult {
                    solution: text.clone(),
                    confidence,
                    method: SolveMethod::VisionLLM,
                    time_ms: t0.elapsed().as_millis() as u64,
                    success,
                    screenshot: None,
                    cookies,
                    verified_outcome: None,
                })
            }
            _ => {
                // Generic click-target fallback.
                let prompt = Self::click_target_prompt("the CAPTCHA checkbox or submit button");
                let raw = vlm_query(
                    &self.client,
                    self.provider,
                    &self.endpoint,
                    &self.model,
                    self.api_key.as_deref(),
                    &image_b64,
                    &prompt,
                    self.config.vlm_http_timeout_ms,
                )
                .await?;

                let json_str = extract_json(&raw).unwrap_or(&raw);
                let val: serde_json::Value =
                    serde_json::from_str(json_str).unwrap_or(serde_json::Value::Null);
                let x = val["x"].as_f64().unwrap_or(0.0);
                let y = val["y"].as_f64().unwrap_or(0.0);
                let confidence = val["confidence"].as_f64().unwrap_or(0.0) as f32;

                let viewport = page
                    .evaluate("window.innerWidth + ',' + window.innerHeight")
                    .await?
                    .into_value::<String>()
                    .unwrap_or_default();
                let mut parts = viewport.split(',');
                let vw: f64 = parts.next().and_then(|s| s.parse().ok()).unwrap_or(1920.0);
                let vh: f64 = parts.next().and_then(|s| s.parse().ok()).unwrap_or(1080.0);

                if x > 0.0 && y > 0.0 && x < vw && y < vh {
                    crate::behavior::click_realistic(page, x, y).await?;
                }

                let success = confidence > 0.5;
                let cookies = if success {
                    crate::cookies::capture_from_page(page)
                        .await
                        .unwrap_or_default()
                } else {
                    Vec::new()
                };
                Ok(CaptchaSolveResult {
                    solution: format!("click:{},{}:{:.2}", x as i64, y as i64, confidence),
                    confidence,
                    method: SolveMethod::VisionLLM,
                    time_ms: t0.elapsed().as_millis() as u64,
                    success,
                    screenshot: None,
                    cookies,
                    verified_outcome: None,
                })
            }
        }
    }
}

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

    #[test]
    fn vlm_solver_defaults_when_env_returns_none() {
        let s = VlmCaptchaSolver::new_with_env(|_| None);
        assert_eq!(s.endpoint, "http://localhost:11434");
        assert_eq!(s.model, "llama3.2-vision:11b");
    }

    #[test]
    fn vlm_solver_env_overrides_defaults() {
        let s = VlmCaptchaSolver::new_with_env(|k| match k {
            "CAPTCHAFORGE_VLM_ENDPOINT" => Some("http://env-host:11434".into()),
            "CAPTCHAFORGE_VLM_MODEL" => Some("env-model:latest".into()),
            _ => None,
        });
        assert_eq!(s.endpoint, "http://env-host:11434");
        assert_eq!(s.model, "env-model:latest");
    }

    #[test]
    fn vlm_solver_builder_overrides_env() {
        let s = VlmCaptchaSolver::new_with_env(|k| match k {
            "CAPTCHAFORGE_VLM_ENDPOINT" => Some("http://env-host:11434".into()),
            "CAPTCHAFORGE_VLM_MODEL" => Some("env-model:latest".into()),
            _ => None,
        })
        .with_endpoint("http://builder:11434")
        .with_model("builder-model:7b");
        assert_eq!(s.endpoint, "http://builder:11434");
        assert_eq!(s.model, "builder-model:7b");
    }

    #[test]
    fn vlm_solver_empty_env_falls_through_to_defaults() {
        let s = VlmCaptchaSolver::new_with_env(|_| Some(String::new()));
        assert_eq!(s.endpoint, "http://localhost:11434");
        assert_eq!(s.model, "llama3.2-vision:11b");
    }

    #[test]
    fn vlm_solver_env_constants_match_documented_names() {
        // The CLAUDE.md / README contract is the env-var names. Pin
        // them so a rename is a deliberate breaking change.
        assert_eq!(ENV_VLM_ENDPOINT, "CAPTCHAFORGE_VLM_ENDPOINT");
        assert_eq!(ENV_VLM_MODEL, "CAPTCHAFORGE_VLM_MODEL");
        assert_eq!(ENV_ANTHROPIC_KEY, "ANTHROPIC_API_KEY");
        assert_eq!(ENV_OPENAI_KEY, "OPENAI_API_KEY");
    }

    #[test]
    fn vlm_solver_no_api_key_picks_ollama() {
        let s = VlmCaptchaSolver::new_with_env(|_| None);
        assert_eq!(s.provider, VlmProvider::Ollama);
        assert!(s.api_key.is_none());
        assert_eq!(s.endpoint, "http://localhost:11434");
        assert_eq!(s.model, "llama3.2-vision:11b");
    }

    #[test]
    fn vlm_solver_anthropic_api_key_picks_anthropic() {
        let s = VlmCaptchaSolver::new_with_env(|k| match k {
            "ANTHROPIC_API_KEY" => Some("sk-ant-test".into()),
            _ => None,
        });
        assert_eq!(s.provider, VlmProvider::Anthropic);
        assert_eq!(s.api_key.as_deref(), Some("sk-ant-test"));
        assert_eq!(s.endpoint, "https://api.anthropic.com");
        assert_eq!(s.model, "claude-haiku-4-5");
    }

    #[test]
    fn vlm_solver_openai_api_key_picks_openai_when_no_anthropic() {
        let s = VlmCaptchaSolver::new_with_env(|k| match k {
            "OPENAI_API_KEY" => Some("sk-openai-test".into()),
            _ => None,
        });
        assert_eq!(s.provider, VlmProvider::OpenAI);
        assert_eq!(s.api_key.as_deref(), Some("sk-openai-test"));
        assert_eq!(s.endpoint, "https://api.openai.com");
        assert_eq!(s.model, "gpt-4o-mini");
    }

    #[test]
    fn vlm_solver_anthropic_wins_over_openai_when_both_set() {
        // Anthropic is preferred — strongest visual reasoning of the three.
        // If users want OpenAI specifically, they unset ANTHROPIC_API_KEY.
        let s = VlmCaptchaSolver::new_with_env(|k| match k {
            "ANTHROPIC_API_KEY" => Some("sk-ant-test".into()),
            "OPENAI_API_KEY" => Some("sk-openai-test".into()),
            _ => None,
        });
        assert_eq!(s.provider, VlmProvider::Anthropic);
        assert_eq!(s.api_key.as_deref(), Some("sk-ant-test"));
    }

    #[test]
    fn vlm_solver_with_provider_overrides_env_detection() {
        // Force Ollama even when Anthropic env key is present — useful
        // for integration tests that need a deterministic local back-end.
        let s = VlmCaptchaSolver::new_with_env(|k| match k {
            "ANTHROPIC_API_KEY" => Some("sk-ant-test".into()),
            _ => None,
        })
        .with_provider(VlmProvider::Ollama);
        assert_eq!(s.provider, VlmProvider::Ollama);
    }

    #[test]
    fn vlm_solver_with_api_key_overrides_env_detection() {
        let s = VlmCaptchaSolver::new_with_env(|_| None).with_api_key("override-key");
        assert_eq!(s.api_key.as_deref(), Some("override-key"));
    }

    #[test]
    fn vlm_solver_empty_anthropic_key_falls_through_to_ollama() {
        // Empty string treated same as unset (matches the existing
        // CAPTCHAFORGE_VLM_ENDPOINT empty-fallthrough contract).
        let s = VlmCaptchaSolver::new_with_env(|k| match k {
            "ANTHROPIC_API_KEY" => Some(String::new()),
            _ => None,
        });
        assert_eq!(s.provider, VlmProvider::Ollama);
    }

    #[test]
    fn vlm_provider_default_endpoints_and_models_consistent() {
        // Catch a regression where the per-provider defaults drift
        // out of sync with the documented constants.
        assert_eq!(VlmProvider::Ollama.default_endpoint(), DEFAULT_OLLAMA_BASE);
        assert_eq!(VlmProvider::Ollama.default_model(), DEFAULT_OLLAMA_MODEL);
        assert_eq!(VlmProvider::Anthropic.default_endpoint(), DEFAULT_ANTHROPIC_BASE);
        assert_eq!(VlmProvider::Anthropic.default_model(), DEFAULT_ANTHROPIC_MODEL);
        assert_eq!(VlmProvider::OpenAI.default_endpoint(), DEFAULT_OPENAI_BASE);
        assert_eq!(VlmProvider::OpenAI.default_model(), DEFAULT_OPENAI_MODEL);
    }

    #[test]
    fn vlm_solver_custom_endpoint() {
        let s = VlmCaptchaSolver::new().with_endpoint("http://ollama.internal:11434");
        assert_eq!(s.endpoint, "http://ollama.internal:11434");
    }

    #[test]
    fn vlm_solver_custom_model() {
        let s = VlmCaptchaSolver::new().with_model("llava:13b");
        assert_eq!(s.model, "llava:13b");
    }

    #[test]
    fn vlm_solver_chained_builders() {
        let s = VlmCaptchaSolver::new()
            .with_endpoint("http://gpu-box:11434")
            .with_model("llama3.2-vision:72b");
        assert_eq!(s.endpoint, "http://gpu-box:11434");
        assert_eq!(s.model, "llama3.2-vision:72b");
    }

    #[test]
    fn grid_prompt_includes_task() {
        let prompt = VlmCaptchaSolver::grid_prompt("Select all traffic lights");
        assert!(prompt.contains("Select all traffic lights"));
        assert!(prompt.contains("selected"));
        assert!(prompt.contains("confidence"));
    }

    #[test]
    fn text_captcha_prompt_is_valid() {
        let prompt = VlmCaptchaSolver::text_captcha_prompt();
        assert!(prompt.contains("text"));
        assert!(prompt.contains("confidence"));
    }

    #[test]
    fn click_target_prompt_includes_target() {
        let prompt = VlmCaptchaSolver::click_target_prompt("submit button");
        assert!(prompt.contains("submit button"));
        assert!(prompt.contains('"'));
    }

    #[test]
    fn extract_json_from_plain_text() {
        let s = r#"Some preamble {"key": "value"} trailing"#;
        assert_eq!(extract_json(s), Some(r#"{"key": "value"}"#));
    }

    #[test]
    fn extract_json_from_markdown_fence() {
        let s = "```json\n{\"answer\": 42}\n```";
        assert_eq!(extract_json(s), Some("{\"answer\": 42}"));
    }

    #[test]
    fn extract_json_no_json_returns_none() {
        assert_eq!(extract_json("no json here"), None);
    }
}