captchakraken 3.2.1 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/AGENTS.md +7 -11
  2. package/LICENSE +165 -145
  3. package/NOTICE +4 -4
  4. package/README.md +12 -13
  5. package/bin/captchakraken.js +25 -0
  6. package/dist/cli-invocation.d.ts +6 -3
  7. package/dist/cli-invocation.js +26 -10
  8. package/dist/humanize.d.ts +37 -1
  9. package/dist/humanize.js +143 -9
  10. package/dist/index.d.ts +13 -12
  11. package/dist/index.js +25 -33
  12. package/dist/kinds.d.ts +15 -2
  13. package/dist/kinds.js +12 -4
  14. package/dist/playwright-types.d.ts +3 -0
  15. package/dist/selectors.d.ts +93 -11
  16. package/dist/selectors.js +226 -116
  17. package/dist/solver.d.ts +94 -12
  18. package/dist/solver.js +569 -203
  19. package/dist/types.d.ts +53 -8
  20. package/dist/verdicts.d.ts +3 -0
  21. package/dist/verdicts.js +40 -0
  22. package/package.json +8 -4
  23. package/python/AGENTS.md +9 -13
  24. package/python/LICENSE +165 -145
  25. package/python/NOTICE +4 -4
  26. package/python/README.md +13 -12
  27. package/python/pyproject.toml +27 -13
  28. package/python/src/captchakraken/__init__.py +43 -46
  29. package/python/src/captchakraken/action_types.py +32 -1
  30. package/python/src/captchakraken/captchakraken.config.json +416 -0
  31. package/python/src/captchakraken/cli.py +141 -31
  32. package/python/src/captchakraken/clipvideo.py +258 -0
  33. package/python/src/captchakraken/config.py +72 -7
  34. package/python/src/captchakraken/demo.py +149 -0
  35. package/python/src/captchakraken/humanize.py +141 -10
  36. package/python/src/captchakraken/image_processor.py +3 -7
  37. package/python/src/captchakraken/keyframes.py +96 -14
  38. package/python/src/captchakraken/kinds.py +14 -2
  39. package/python/src/captchakraken/models.json +37 -3
  40. package/python/src/captchakraken/page_solver.py +600 -252
  41. package/python/src/captchakraken/planner.py +311 -49
  42. package/python/src/captchakraken/pointer/__init__.py +20 -0
  43. package/python/src/captchakraken/pointer/detector.py +333 -0
  44. package/python/src/captchakraken/pointer/elements.py +273 -0
  45. package/python/src/captchakraken/pointer/heads.py +163 -0
  46. package/python/src/captchakraken/pointer/layout.py +319 -0
  47. package/python/src/captchakraken/pointer/marks.py +184 -0
  48. package/python/src/captchakraken/pointer/server.py +150 -0
  49. package/python/src/captchakraken/pointer/service.py +553 -0
  50. package/python/src/captchakraken/pointer/vllm_plugin.py +114 -0
  51. package/python/src/captchakraken/prompts.py +111 -34
  52. package/python/src/captchakraken/selectors.py +221 -135
  53. package/python/src/captchakraken/selfhost.py +423 -0
  54. package/python/src/captchakraken/server_manager.py +139 -11
  55. package/python/src/captchakraken/solver.py +169 -88
  56. package/python/src/captchakraken/tool_calls/board_painted.py +11 -6
  57. package/python/src/captchakraken/tool_calls/fill_tracker.py +152 -0
  58. package/python/src/captchakraken/tool_calls/find_checkbox.py +14 -59
  59. package/python/src/captchakraken/tool_calls/find_grid.py +273 -1191
  60. package/python/src/captchakraken/tool_calls/slide_tracker.py +1102 -0
  61. package/python/src/captchakraken/verdicts.py +52 -0
  62. package/dist/slide-geometry.d.ts +0 -6
  63. package/dist/slide-geometry.js +0 -38
  64. package/python/src/captchakraken/tool_calls/track_piece.py +0 -120
@@ -4,7 +4,6 @@ from __future__ import annotations
4
4
 
5
5
  import hashlib
6
6
  import io
7
- import itertools
8
7
  import json
9
8
  import math
10
9
  import os
@@ -17,18 +16,17 @@ import time
17
16
  import uuid
18
17
  from concurrent.futures import ThreadPoolExecutor
19
18
  from contextlib import contextmanager
20
- from dataclasses import dataclass, field
21
- from typing import AbstractSet, Any, Callable, Dict, List, NamedTuple, Optional, Sequence, Set, Tuple
19
+ from dataclasses import InitVar, dataclass, field
20
+ from typing import AbstractSet, Any, Callable, Dict, List, Mapping, NamedTuple, Optional, Sequence, Set, Tuple, Union
22
21
 
23
- from . import planner
22
+ from . import config, planner
24
23
  from .action_types import CaptchaAction
25
- from .humanize import Humanizer, resolve as resolve_humanizer
24
+ from .humanize import Humanizer, hold, resolve as resolve_humanizer
26
25
  from .kinds import (ActionKind, FrameRole, HumanizationMode, KeyframeMode, PauseKind, Phase, PromptFamily,
27
26
  RecaptchaBanner, RetryMode, SettleVerdict, Vendor, Verdict)
28
- from .selectors import (ACCEPTED_SELECTORS, ENCLAVE_SELECTORS, PIECE_SELECTORS, RESPONSE_SELECTORS, SELECTORS, SLIDER_HANDLE_SELECTORS,
29
- SUBMIT_SELECTORS, TEXT_INPUT_SELECTORS, TEXT_INPUT_VENDOR_SELECTORS, VENDORS, WIDGET_PROBES,
30
- VendorSelectors, WidgetProbe)
31
- from .solver import CaptchaSolver, UnsupportedCaptchaError
27
+ from .selectors import DEFAULT_CONFIG_PATH, DEFAULT_TABLE, SelectorTable, VendorSelectors, WidgetProbe
28
+ from .server_manager import ensure_server
29
+ from .solver import AnimatedRecording, CaptchaSolver, UnsupportedCaptchaError, cut_recording
32
30
  from .timing import PhaseBudget, timings_enabled
33
31
  from .verdicts import RoundVerdict, VerdictLog
34
32
 
@@ -197,6 +195,40 @@ class SolveResult:
197
195
  verdicts: List[RoundVerdict] = field(default_factory=list)
198
196
 
199
197
 
198
+ #: A typed captcha's text box widens the shot only when it sits by the image: the union may be at most this many
199
+ #: times the image's area. A vendor-named box found in the enclosing form can be a whole login form away.
200
+ ANSWER_BOX_MAX_GROWTH = 4.0
201
+
202
+
203
+ class _WithAnswerBox:
204
+ """A typed captcha's image and its text box, photographed and pointed into as one element.
205
+
206
+ BotDetect's widget element is a 280x50 strip holding only the image; its text box is a sibling. Every
207
+ training board and every real capture of a typed captcha shows the box under the image, and on the bare
208
+ strip the pointer read the image as a click puzzle (p(type) 0.46) or doubled a glyph, where the same frame
209
+ with its box read R9VK at p >= 0.89 per character. The answer's points are taken in this union's frame, so
210
+ `bounding_box` is the union everywhere the round reads it; everything else is the element's own.
211
+ """
212
+
213
+ def __init__(self, element: Any, box: Any):
214
+ self._element, self._box = element, box
215
+
216
+ def bounding_box(self) -> Optional[Dict[str, float]]:
217
+ a = self._element.bounding_box()
218
+ b = self._box.bounding_box() if a else None
219
+ if not a or not b:
220
+ return a
221
+ x0, y0 = min(a["x"], b["x"]), min(a["y"], b["y"])
222
+ x1 = max(a["x"] + a["width"], b["x"] + b["width"])
223
+ y1 = max(a["y"] + a["height"], b["y"] + b["height"])
224
+ if (x1 - x0) * (y1 - y0) > ANSWER_BOX_MAX_GROWTH * max(a["width"] * a["height"], 1.0):
225
+ return a
226
+ return {"x": x0, "y": y0, "width": x1 - x0, "height": y1 - y0}
227
+
228
+ def __getattr__(self, name: str) -> Any:
229
+ return getattr(self._element, name)
230
+
231
+
200
232
  @dataclass
201
233
  class _GridSession:
202
234
  grid_boxes: List[Sequence[int]]
@@ -250,12 +282,29 @@ _NOT_THIS_BOARD_POLLS = 3
250
282
  # How long a control we hovered, pressed or typed into takes to stop repainting in reaction. A board read
251
283
  # inside this window is wearing our own feedback, which is not a screen it ever showed by itself.
252
284
  INPUT_SETTLE_MS = 400
285
+ # While a reCAPTCHA tile reloads the hand rests on it, drifting a few pixels every second or two. Reaching for a
286
+ # different reloading tile on every 250 ms poll read as a cursor darting about the board.
287
+ IDLE_DRIFT_EVERY_MS = (1200.0, 2800.0)
288
+ IDLE_DRIFT_PX = 3.0
289
+ # How much longer than `grid_load_timeout_ms` a reCAPTCHA tile that is still painting is waited on.
290
+ GRID_LOAD_CAP_FACTOR = 3
291
+ # A press-and-hold is released once the widget's picture has stopped changing for this long after its fill
292
+ # moved, and at HOLD_MAX_MS whatever it shows. Press & Hold widgets ask for seconds, not tens of seconds.
293
+ HOLD_SETTLE_MS = 900
294
+ HOLD_MAX_MS = 12000
253
295
 
254
296
 
255
297
  @dataclass
256
298
  class PageSolverConfig:
257
299
  humanization: Optional[HumanizationMode] = None
258
300
  humanizer: Optional[Humanizer] = None
301
+ # Every URL pattern and selector the solver detects and drives with: a path to a config file of the shape of the
302
+ # repository's `captchakraken.config.json`, or the parsed object. What it gives is laid over the shipped default,
303
+ # so a file holding only a `custom` entry adds that entry and keeps every built-in vendor.
304
+ selectors: Union[str, "os.PathLike[str]", Mapping[str, Any]] = DEFAULT_CONFIG_PATH
305
+ # Deprecated, kept working: your own vendor entry in code. Prefer `custom` in the `selectors` file;
306
+ # when both are given this one wins.
307
+ custom_selectors: Optional[VendorSelectors] = None
259
308
  touch_driver: Optional[Any] = None
260
309
  touch_transform: Optional[Dict[str, Any]] = None
261
310
  starting_mouse_position: Optional[Tuple[float, float]] = None
@@ -265,16 +314,11 @@ class PageSolverConfig:
265
314
  # A page just navigated has often not drawn its widget; this long is spent looking before "no captcha" is
266
315
  # believed. It is not charged to overall_solve_timeout_ms, which starts when there is something to solve.
267
316
  detection_timeout_ms: int = 15_000
268
- # Repeats of one answer on one board before the solve ends; the first repeats are re-asked at a fresh sample.
317
+ # Repeats of one answer on one board before the solve ends; the first repeats are re-asked naming the refused answer.
269
318
  max_no_progress_rounds: int = 2
270
- # Deprecated and ignored since 3.2.0: a round that performed nothing goes straight on to the next.
271
- post_solve_delay_ms: int = 1_200
272
319
  post_solve_outcome_timeout_ms: int = 1_000
273
320
  post_solve_outcome_poll_ms: int = 75
274
321
  element_screenshot_timeout_ms: int = 8_000
275
- # Deprecated and ignored since 3.2.0: each of these failures now counts against max_solve_loops.
276
- max_unsupported_resolves: int = 3
277
- max_stale_element_retries: int = 3
278
322
  # The pause before a failed round is tried again.
279
323
  stale_element_backoff_ms: int = 900
280
324
  stale_frame_resolve_enabled: bool = True
@@ -300,7 +344,7 @@ class PageSolverConfig:
300
344
  keyframe_wait_timeout_ms: int = 9_000
301
345
  keyframe_wait_poll_ms: int = 120
302
346
  video_extra_inference_ms: int = 8_000
303
- hcaptcha_images_timeout_ms: int = 3_000
347
+ board_images_timeout_ms: int = 3_000
304
348
  grid_load_poll_interval_ms: int = 250
305
349
  grid_load_timeout_ms: int = 8_000
306
350
  board_paint_poll_ms: int = 180
@@ -313,12 +357,29 @@ class PageSolverConfig:
313
357
  recaptcha_tile_hover_enabled: bool = True
314
358
  slide_tolerance_px: float = 2.0
315
359
  slide_max_corrections: int = 3
360
+ # Older names, still accepted. The first three have done nothing since 3.2.0 (each failure counts against
361
+ # max_solve_loops); the last is board_images_timeout_ms, which waits for any vendor's `images`, not only hCaptcha's.
362
+ post_solve_delay_ms: InitVar[Optional[int]] = None
363
+ max_unsupported_resolves: InitVar[Optional[int]] = None
364
+ max_stale_element_retries: InitVar[Optional[int]] = None
365
+ hcaptcha_images_timeout_ms: InitVar[Optional[int]] = None
366
+
367
+ def __post_init__(self, post_solve_delay_ms, max_unsupported_resolves, max_stale_element_retries,
368
+ hcaptcha_images_timeout_ms) -> None:
369
+ if hcaptcha_images_timeout_ms is not None:
370
+ self.board_images_timeout_ms = hcaptcha_images_timeout_ms
316
371
 
317
372
  def video_budget_ms(self) -> int:
318
373
  return (self.video_burst_max_ms + self.keyframe_wait_timeout_ms
319
374
  + self.video_extra_inference_ms)
320
375
 
321
376
 
377
+ # The old name reads and writes the new field; as an InitVar alone it was accepted by __init__ but read back as None.
378
+ PageSolverConfig.hcaptcha_images_timeout_ms = property( # type: ignore[assignment]
379
+ lambda self: self.board_images_timeout_ms,
380
+ lambda self, v: setattr(self, "board_images_timeout_ms", v))
381
+
382
+
322
383
  class Widget(NamedTuple):
323
384
  """What detection found: the handle to photograph, the locator to search inside, and which table entry named it."""
324
385
 
@@ -366,10 +427,10 @@ def _frame_of(at: Any) -> Optional[Any]:
366
427
  return None
367
428
 
368
429
 
369
- def _host_scopes(page: Any) -> List[Any]:
430
+ def _host_scopes(page: Any, enclaves: Sequence[str]) -> List[Any]:
370
431
  """Where the host-page selectors are read: the page, then the inside of every VISIBLE vendor enclave. A hidden enclave
371
432
  is skipped because Playwright judges an element visible within its own document, whatever its frame's visibility."""
372
- return [page, *(f for f in map(_frame_of, _visible(page, ENCLAVE_SELECTORS)) if f is not None)]
433
+ return [page, *(f for f in map(_frame_of, _visible(page, enclaves)) if f is not None)]
373
434
 
374
435
 
375
436
  def _visible_in(scopes: Sequence[Any], selectors: Sequence[str]) -> List[Any]:
@@ -390,8 +451,9 @@ def _has_text(handle: Any) -> bool:
390
451
  return False
391
452
 
392
453
 
393
- SLIDE_PIECE_MIN_PX = 3.0
394
- SLIDE_PIECE_MAX_FRACTION = 0.6
454
+ # The nudge that shows the tracker what the handle moves: enough to separate the part from still ground, little enough
455
+ # that a piece resting against the board's edge stays on it.
456
+ SLIDE_PROBE_PX = 8.0
395
457
 
396
458
  # No prompt and no pictures both read as ready: waiting for `.prompt-text` to exist once paid the whole timeout
397
459
  # before every board of a challenge that draws none (tower_stack: 18s a round, 2/2 -> 0/2).
@@ -419,6 +481,8 @@ _RESOURCES_JS = """() => {
419
481
  class PageSolver:
420
482
  """Drives one Playwright-compatible `page` through a captcha. Reusable across solves."""
421
483
 
484
+ _sel: SelectorTable = DEFAULT_TABLE
485
+
422
486
  def __init__(self, config: Optional[PageSolverConfig] = None,
423
487
  solver: Optional[CaptchaSolver] = None, **solver_kwargs: Any) -> None:
424
488
  self.config = config or PageSolverConfig()
@@ -426,10 +490,14 @@ class PageSolver:
426
490
  solver_kwargs.setdefault("expert", self.config.expert)
427
491
  self._solver = solver or CaptchaSolver(**solver_kwargs)
428
492
  self._human: Humanizer = resolve_humanizer(self.config)
493
+ self._sel = SelectorTable(self.config.custom_selectors, config=self.config.selectors)
494
+ # The config's `detector`: which element detector finds this solver's grids and tick boxes.
495
+ from .pointer import detector as _detector
496
+ _detector.configure(self._sel.config.detector)
429
497
  self._last_submit_frame_hash: Optional[str] = None
430
498
  self._deadline_ms: Optional[float] = None
431
499
  self._budget: Optional[PhaseBudget] = None
432
- self._animated_plan: Optional[Tuple[List[str], str, Any, Any]] = None
500
+ self._animated_plan: Optional[Tuple[AnimatedRecording, str, Any, Any]] = None
433
501
  self._film_frames: List[Any] = []
434
502
  self._film_ms: float = 0.0
435
503
  # The digests of every screen the film holds: what a later burst is checked against to answer
@@ -474,6 +542,7 @@ class PageSolver:
474
542
 
475
543
  def _reset_animated_state(self) -> None:
476
544
  self._acted_on_board = False
545
+ self._submitted_on_board = False
477
546
  self._known_animated = False
478
547
  self._animated_probe_armed = False
479
548
  self._animated_probe_done = False
@@ -482,37 +551,75 @@ class PageSolver:
482
551
  self._keyframe_mode: Optional[KeyframeMode] = None
483
552
  self._keyframe_steady_screens = 0
484
553
  self._last_answer_sig: Optional[str] = None
554
+ self._tried_answers: Set[str] = set()
555
+ self._refreshed_boards: Set[str] = set()
556
+ self._round_board: Optional[str] = None
485
557
  self._no_progress_rounds = 0
486
- self._resample_level = 0
487
- self._apply_sampling()
558
+ self._refused_rounds = 0
559
+ self._fallback_board: Optional[str] = None
560
+ self._exchanges_at_answer = 0
561
+ self._drop_pointer_history()
562
+ self._apply_refusals()
488
563
 
489
- @staticmethod
490
- def _answer_signature(actions: Sequence[Any], retry_mode: Optional[RetryMode]) -> Optional[str]:
491
- """Keyed on retry mode: the missed-tiles answer legitimately overlaps the previous one."""
564
+ def _answer_signature(self, actions: Sequence[Any], retry_mode: Optional[RetryMode]) -> Optional[str]:
565
+ """Keyed on the BOARD and the retry mode, not the answer alone.
566
+
567
+ A paged puzzle's next arrow is at the same point on every page, so a signature over the actions
568
+ alone would call a correct page turn a repeated answer and stop pressing it.
569
+ """
492
570
  try:
493
571
  parts = [(a.get("action"), _round_pts(a.get("target_bounding_boxes")),
494
572
  _round_pts(a.get("target_bounding_box")), _round_pts(a.get("target_coordinates")),
495
573
  _round_pts(a.get("source_bounding_box")), a.get("text"))
496
574
  for a in map(_as_dict, actions)]
497
- return repr((retry_mode, parts))
575
+ return repr((self._fallback_board, retry_mode, parts))
498
576
  except Exception:
499
577
  return None
500
578
 
501
579
  def _note_answer(self, actions: Sequence[Any], retry_mode: Optional[RetryMode]) -> bool:
502
- """True when this answer already ran and changed nothing: resample, re-ask, and arm the probe."""
580
+ """True when this answer already ran and changed nothing: re-ask avoiding it, and arm the probe."""
503
581
  sig = self._answer_signature(actions, retry_mode)
504
- if sig is not None and sig == self._last_answer_sig:
582
+ # A refresh asks for a different board, so the same refresh twice is two boards, not a refused answer. An
583
+ # answer that could not be signed could not be read either, and is not looked into.
584
+ if sig is not None and any(_as_dict(a).get("action") == ActionKind.REFRESH for a in actions):
585
+ self._no_progress_rounds = 0
586
+ self._last_answer_sig = None
587
+ if self._round_board is not None:
588
+ self._refreshed_boards.add(self._round_board)
589
+ return False
590
+ # A vendor can deal the same picture again, which clears the plans but not what was pressed on it. A paged
591
+ # puzzle is exempt: coming back to a page after the others is a new question, because the history differs.
592
+ tried = (self._fallback_board is not None and not self._pointer_history and sig in self._tried_answers)
593
+ if sig is not None and (sig == self._last_answer_sig or tried):
505
594
  self._no_progress_rounds += 1
506
595
  _log(f"[no-progress] the model returned the same answer again ({self._no_progress_rounds} in a row)")
507
- self._resample_level += 1
508
- self._apply_sampling()
596
+ # A board that said nothing to its server has refused nothing, and another plan is one more press.
597
+ if not self._board_stayed_silent():
598
+ self._refused_rounds += 1
599
+ self._apply_refusals()
509
600
  self._invalidate_animated_answer()
510
601
  self._arm_animated_probe()
511
602
  return True
512
603
  self._no_progress_rounds = 0
513
604
  self._last_answer_sig = sig
605
+ if sig is not None:
606
+ self._tried_answers.add(sig)
607
+ self._exchanges_at_answer = self._verdicts.exchanges if self._verdicts else 0
514
608
  return False
515
609
 
610
+ def _another_move_left(self, retry_mode: Optional[RetryMode]) -> bool:
611
+ """Whether the round after a repeat can differ. At temperature 0 the same question gets the same answer,
612
+ so it takes a different question (a retry mode, a film) or one of the model's other plans."""
613
+ target = getattr(self._solver, "planner", None)
614
+ pointer = bool(getattr(getattr(target, "prompts", None), "pointer", False))
615
+ return bool(retry_mode or self._known_animated
616
+ or (self.config.video_solve_enabled and self._animated_probe_armed)
617
+ or (pointer and target.avoid_refused))
618
+
619
+ def _board_stayed_silent(self) -> bool:
620
+ log = self._verdicts
621
+ return log is not None and log.listening and log.exchanges == self._exchanges_at_answer
622
+
516
623
  def _bound_ask_to_the_budget(self) -> None:
517
624
  """Give the planner what is LEFT of the solve, so one ask cannot outlive the whole thing.
518
625
 
@@ -527,13 +634,101 @@ class PageSolver:
527
634
  target.request_timeout_s = max(planner.MIN_REQUEST_TIMEOUT_S,
528
635
  min(planner.DEFAULT_REQUEST_TIMEOUT_S, left_s))
529
636
 
530
- def _apply_sampling(self) -> None:
637
+ def _apply_refusals(self) -> None:
531
638
  target = getattr(self._solver, "planner", None)
532
639
  if target is None:
533
640
  return
534
- target.sampling = sampling = planner.sampling_for_level(self._resample_level)
535
- if sampling:
536
- _log(f"[resample] temperature {sampling['temperature']}, seed {sampling['seed']}")
641
+ # A pointer model is an argmax and samples nothing. Once an answer has come back unchanged and refused,
642
+ # every ask on this board names the answers already tried, and the pointer returns its likeliest other one.
643
+ target.avoid_refused = self._refused_rounds > 0
644
+ if not self._refused_rounds and hasattr(target, "pointer_answers"):
645
+ target.pointer_answers.clear()
646
+ if hasattr(target, "pointer_fallbacks"):
647
+ target.pointer_fallbacks.clear()
648
+ if hasattr(target, "pointer_has_actions"):
649
+ target.pointer_has_actions = False
650
+ self._fallback_board = None
651
+
652
+ def _drop_pointer_history(self) -> None:
653
+ """A paged puzzle's earlier screens do not belong to the next puzzle."""
654
+ directory = getattr(self, "_pointer_history_dir", None)
655
+ if directory:
656
+ shutil.rmtree(directory, ignore_errors=True)
657
+ self._pointer_history: List[str] = []
658
+ self._pointer_history_dir: Optional[str] = None
659
+ planner = getattr(self._solver, "planner", None)
660
+ if planner is not None and hasattr(planner, "pointer_history"):
661
+ planner.pointer_history = self._pointer_history
662
+
663
+ def _keep_pointer_screen(self, shot: str, puzzle_source: Vendor, actions: Sequence[Any]) -> None:
664
+ """A FunCaptcha page turn's answer depends on the screens already seen; keep each one for the next ask.
665
+
666
+ The model reads the earlier screens of the same puzzle as history. Sent only the current page, it
667
+ has nothing to compare against and keeps answering "next arrow", including on the match.
668
+ """
669
+ if puzzle_source != Vendor.FUNCAPTCHA:
670
+ return
671
+ kinds = {_as_dict(a).get("action") for a in actions}
672
+ if kinds != {ActionKind.CLICK}:
673
+ return
674
+ if self._pointer_history_dir is None:
675
+ self._pointer_history_dir = tempfile.mkdtemp(prefix="ck_pghist_")
676
+ path = os.path.join(self._pointer_history_dir, f"{len(self._pointer_history):02d}.png")
677
+ try:
678
+ shutil.copyfile(shot, path)
679
+ except OSError:
680
+ return
681
+ self._pointer_history.append(path)
682
+ while len(self._pointer_history) > 8:
683
+ old = self._pointer_history.pop(0)
684
+ _unlink(old)
685
+ planner = getattr(self._solver, "planner", None)
686
+ if planner is not None and hasattr(planner, "pointer_history"):
687
+ planner.pointer_history = self._pointer_history
688
+
689
+ def _board_hash(self, element: Any, shot: str, filmed: bool) -> str:
690
+ """The board's identity, always from a plain photograph: a filmed frame of an unchanged board differs in bytes."""
691
+ if not filmed:
692
+ return _sha1(shot)
693
+ plain = _tmp_png("board")
694
+ try:
695
+ self._screenshot(element, plain, timeout_ms=self.config.element_screenshot_timeout_ms)
696
+ return _sha1(plain)
697
+ finally:
698
+ _unlink(plain)
699
+
700
+ def _guard_fallbacks_to_board(self, board: str) -> None:
701
+ """A fallback plan answers the board it was read off. Reuse it only while that board is still up.
702
+
703
+ The next round's screenshot is the test. Without it, a vendor that deals a new board without
704
+ saying so has the previous board's second plan pressed onto the new one.
705
+
706
+ A refresh that brought the same picture back has replaced nothing, and every plan has been spent on it.
707
+ """
708
+ if board in self._refreshed_boards:
709
+ raise CaptchaSolveError("no progress: the board came back unchanged after a refresh")
710
+ self._round_board = board
711
+ target = getattr(self._solver, "planner", None)
712
+ if target is None or not getattr(getattr(target, "prompts", None), "pointer", False):
713
+ return
714
+ if self._fallback_board is not None and board != self._fallback_board:
715
+ if self._refused_rounds or getattr(target, "pointer_fallbacks", None):
716
+ _log("[pointer] the board changed; dropping the previous answer's fallbacks")
717
+ self._refused_rounds = 0
718
+ self._apply_refusals()
719
+ self._fallback_board = board
720
+
721
+ def _keep_plans_of_this_many_clicks(self, actions: List[Any]) -> None:
722
+ """A click board with no Verify submits itself at a count, so a plan of any other count leaves its tiles
723
+ ticked and never submits, and the next plan's clicks untick them."""
724
+ plan = [_as_dict(a) for a in actions]
725
+ if not plan or any(a.get("action") != ActionKind.CLICK for a in plan):
726
+ return
727
+ clicks = sum(len(a.get("target_bounding_boxes") or [1]) for a in plan)
728
+ target = getattr(self._solver, "planner", None)
729
+ if getattr(target, "pointer_fallbacks", None):
730
+ target.pointer_fallbacks = [f for f in target.pointer_fallbacks if f.get("action") != ActionKind.CLICK
731
+ or len(f.get("points") or []) == clicks]
537
732
 
538
733
  def _fresh_board(self) -> None:
539
734
  # ONE FILM, ONE BOARD — enforced where the board actually changes. The recorded answer describes the
@@ -545,9 +740,11 @@ class PageSolver:
545
740
  # Its own second look, but only once IT fails: an arm set on the previous board is evidence about that one.
546
741
  self._animated_probe_armed = False
547
742
  self._animated_probe_done = False
548
- self._resample_level = 0
743
+ self._refused_rounds = 0
549
744
  self._acted_on_board = False
550
- self._apply_sampling()
745
+ self._submitted_on_board = False
746
+ self._drop_pointer_history()
747
+ self._apply_refusals()
551
748
 
552
749
  def _check_deadline(self, where: str) -> None:
553
750
  # Called inside loops too: a camoufox session once ran ten minutes past a 120s timeout because only
@@ -614,11 +811,20 @@ class PageSolver:
614
811
 
615
812
  def _get_solution(self, image_path: str, puzzle_source: Vendor, retry_mode: Optional[RetryMode],
616
813
  text_mode: bool = False):
617
- return self._ask(lambda: self._solver.solve(
618
- image_path, puzzle_source=puzzle_source, retry_mode=retry_mode, text_mode=text_mode))
814
+ def solve():
815
+ try:
816
+ return self._solver.solve(image_path, puzzle_source=puzzle_source, retry_mode=retry_mode,
817
+ text_mode=text_mode)
818
+ except UnsupportedCaptchaError:
819
+ # No answer is an empty plan, which presses Skip for a new board. An empty text box is a wrong answer.
820
+ if text_mode:
821
+ raise
822
+ return []
823
+ return self._ask(solve)
619
824
 
620
- def _get_keyframe_solution(self, keyframe_paths: Sequence[str]):
621
- return self._ask(lambda: self._solver.solve_keyframes(keyframe_paths))
825
+ def _get_keyframe_solution(self, recording: AnimatedRecording):
826
+ """The animated ask: keyframes or video, whichever the model's prompt generation was trained on."""
827
+ return self._ask(lambda: self._solver.solve_animated(recording))
622
828
 
623
829
  # ── gestures ─────────────────────────────────────────────────────────
624
830
 
@@ -667,6 +873,17 @@ class PageSolver:
667
873
  return float(coords[0]) * element_box["width"], float(coords[1]) * element_box["height"]
668
874
  return None
669
875
 
876
+ @staticmethod
877
+ def _hold_point_for(action: Dict[str, Any], element_box: Dict[str, float]) -> Optional[Tuple[float, float]]:
878
+ """Element-relative press point of a hold: the model's own point, the middle of its box. A hold can be on a
879
+ bar narrower than that box, and a random spot in it lands off the bar, or close enough to its edge that the
880
+ hand's drift lets go: the widget then never fills, and the same answer fails the same way."""
881
+ bbox = action.get("target_bounding_box")
882
+ if not bbox:
883
+ return None
884
+ x1, y1, x2, y2 = (float(v) for v in bbox)
885
+ return (x1 + x2) / 2 * element_box["width"], (y1 + y2) / 2 * element_box["height"]
886
+
670
887
  def _execute_click(self, page: Any, action: Dict[str, Any], element_box: Dict[str, float],
671
888
  element: Any = None, await_keyframe: Optional[str] = None) -> None:
672
889
  # Every gesture marks the board acted on so the speculative burst is never re-run over a touched board.
@@ -689,6 +906,121 @@ class PageSolver:
689
906
  element_box: Dict[str, float], await_keyframe: str) -> None:
690
907
  self._execute_click(page, action, element_box, element, await_keyframe)
691
908
 
909
+ def _execute_hold(self, page: Any, action: Dict[str, Any], element_box: Dict[str, float], element: Any,
910
+ completes_itself: bool = False) -> bool:
911
+ """Press-and-hold until the widget completes: True when it did, False when the cap ran out.
912
+
913
+ Complete is the vendor's done signal, the widget closing, or its picture having changed (the fill)
914
+ and then sat still for HOLD_SETTLE_MS. A widget that draws no progress at all is held to HOLD_MAX_MS.
915
+ When the answer names the fill's line, the fill reaching its end is complete too: see `_fill_reached`.
916
+ Except on a widget that `completes_itself` (HUMAN's button): it verifies only once it has shown its
917
+ done state, and letting go AT full resets it, so only its own signals end the hold.
918
+ """
919
+ self._acted_on_board = True
920
+ rel = self._hold_point_for(action, element_box)
921
+ if rel is None:
922
+ _log("hold action without a bounding box; skipping")
923
+ return False
924
+ at = (element_box["x"] + rel[0], element_box["y"] + rel[1])
925
+ first = self._element_frame_hash(element)
926
+ seen = {"hash": first, "since": time.monotonic(), "changed": False}
927
+ line = action.get("fill_from_bounding_box") and action.get("fill_to_bounding_box")
928
+ shots = (_tmp_png("hold"), _tmp_png("hold")) if line and not completes_itself else None
929
+ looks: List[Dict[str, Any]] = []
930
+
931
+ def done() -> bool:
932
+ if self.is_captcha_solved(page):
933
+ _debug("hold: the vendor reports solved")
934
+ return True
935
+ try:
936
+ if not element.bounding_box():
937
+ _debug("hold: the widget closed")
938
+ return True
939
+ except Exception:
940
+ _debug("hold: the widget closed")
941
+ return True
942
+ n = len(looks)
943
+ if shots and self._fill_reached(element, action, element_box, shots, looks):
944
+ return True
945
+ # A look that just shot the widget is its frame too: a second screenshot per look slowed the looks
946
+ # enough for a fast fill to pass the mark unseen between two.
947
+ fresh = shots[0 if n == 0 else 1] if shots and len(looks) > n else None
948
+ h, now = (_sha1(fresh) if fresh else self._element_frame_hash(element)), time.monotonic()
949
+ if h != seen["hash"]:
950
+ seen.update(hash=h, since=now, changed=seen["changed"] or h != first)
951
+ return False
952
+ settled = seen["changed"] and (now - seen["since"]) * 1000.0 >= HOLD_SETTLE_MS
953
+ if settled:
954
+ _debug(f"hold: the picture sat still for {HOLD_SETTLE_MS}ms")
955
+ return settled
956
+
957
+ try:
958
+ with self._gesture():
959
+ completed = hold(self._human, page, at, done, HOLD_MAX_MS)
960
+ finally:
961
+ for shot in shots or ():
962
+ _unlink(shot)
963
+ _log("held until the widget completed." if completed else f"released the hold at the {HOLD_MAX_MS}ms cap.")
964
+ return completed
965
+
966
+ def _fill_reached(self, element: Any, action: Dict[str, Any], element_box: Dict[str, float],
967
+ shots: Tuple[str, str], looks: List[Dict[str, Any]]) -> bool:
968
+ """One look at a held widget's fill (`tool_calls.fill_tracker`): True once it reaches the answer's `to`, after
969
+ waiting out the tracker's `release_in` when the fill arrives between looks.
970
+
971
+ The first look only shoots the reference, after the press, so the button's own pressed look is not read as
972
+ fill; `looks` carries what each later look saw. A look that cannot be shot or read is not a release: the
973
+ widget's own signals still end the hold."""
974
+ from .tool_calls.fill_tracker import fill_step
975
+
976
+ first, current = shots
977
+ w, h = element_box["width"], element_box["height"]
978
+ timeout = self.config.element_screenshot_timeout_ms
979
+ try:
980
+ if not looks:
981
+ shot_at = time.monotonic()
982
+ self._screenshot(element, first, timeout_ms=timeout)
983
+ looks.append({"k": self._shot_scale(first, w), "t": (shot_at + time.monotonic()) / 2})
984
+ return False
985
+ shot_at = time.monotonic()
986
+ self._screenshot(element, current, timeout_ms=timeout)
987
+ # The shot was taken somewhere inside the call; its middle is the best guess, and the release is timed
988
+ # from it.
989
+ shot_at = (shot_at + time.monotonic()) / 2
990
+ k, history = looks[0]["k"], looks[1:]
991
+
992
+ def at(bbox: Sequence[float]) -> Tuple[float, float]:
993
+ return (float(bbox[0]) + float(bbox[2])) / 2 * w * k, (float(bbox[1]) + float(bbox[3])) / 2 * h * k
994
+
995
+ gaps = [b["t"] - a["t"] for a, b in zip(history, history[1:])]
996
+ reply = fill_step(first, current, start=at(action["fill_from_bounding_box"]),
997
+ end=at(action["fill_to_bounding_box"]), t=shot_at, history=history, first_t=looks[0]["t"],
998
+ poll_s=sum(gaps) / len(gaps) if gaps else 0.25, tol=self.config.slide_tolerance_px * k)
999
+ except Exception as exc:
1000
+ _debug(f"hold: the fill was not read ({exc})")
1001
+ return False
1002
+ looks.append(reply["observation"])
1003
+ if reply["release"]:
1004
+ _log(f"hold: the fill reaches its mark {reply['release_in'] or 0:.2f}s after a look "
1005
+ f"{(reply['length'] - reply['edge']) / k:+.1f}px short of it")
1006
+ _delay((shot_at + (reply["release_in"] or 0.0) - time.monotonic()) * 1000.0)
1007
+ return bool(reply["release"])
1008
+
1009
+ def _execute_refresh(self, page: Any, scope: Any, action: Dict[str, Any],
1010
+ element_box: Optional[Dict[str, float]]) -> bool:
1011
+ """Deal a new puzzle: the vendor's own control, else the model's point on one. False when there is neither."""
1012
+ control = self._find_control(scope, self._sel.refresh)
1013
+ if control is not None:
1014
+ self._acted_on_board = True
1015
+ self._move_and_click(page, control)
1016
+ elif action.get("target_bounding_box") and element_box:
1017
+ self._execute_click(page, action, element_box)
1018
+ else:
1019
+ _log("the model asked for a new puzzle, and there is no control to deal one; ending the round.")
1020
+ return False
1021
+ _log("asked for a new puzzle instead of solving this one.")
1022
+ return True
1023
+
692
1024
  def _execute_drag(self, page: Any, action: Dict[str, Any], element_box: Dict[str, float]) -> None:
693
1025
  self._acted_on_board = True
694
1026
 
@@ -703,31 +1035,16 @@ class PageSolver:
703
1035
  first = next(iter(_visible(scope, selectors)), None)
704
1036
  return _handle_of(first) if first is not None else None
705
1037
 
706
- def _measure_piece_box(self, scope: Any, widget_width: float) -> Optional[Dict[str, float]]:
707
- """The slider piece's box: the first visible match small enough to be a piece.
708
-
709
- Runs during detection, so it must not mark the board acted on: doing so once disabled the
710
- speculative burst on every slide solve.
711
- """
712
- for candidate in _handles(_visible(scope, PIECE_SELECTORS)):
713
- try:
714
- b = candidate.bounding_box()
715
- except Exception:
716
- continue
717
- if b and SLIDE_PIECE_MIN_PX <= b["width"] <= widget_width * SLIDE_PIECE_MAX_FRACTION:
718
- return b
719
- return None
720
-
721
1038
  def _answer_box(self, scope: Any, at: Any = None) -> Optional[Any]:
722
1039
  """The text box inside the widget, else a vendor-named one in its enclosing fieldset/form.
723
1040
 
724
1041
  Only vendor-named selectors widen: BotDetect's `.BDC_CaptchaDiv` is 280x50 and holds only the image,
725
1042
  with `#captchaCode` in a sibling div. The generic tail there would take a login form's own box.
726
1043
  """
727
- inside = self._find_control(scope, TEXT_INPUT_SELECTORS)
1044
+ inside = self._find_control(scope, self._sel.text_input)
728
1045
  if inside is not None or at is None:
729
1046
  return inside
730
- around = (self._find_control(at.locator(f"xpath={axis}"), TEXT_INPUT_VENDOR_SELECTORS)
1047
+ around = (self._find_control(at.locator(f"xpath={axis}"), self._sel.text_input_vendor)
731
1048
  for axis in ("ancestor::fieldset[1]", "ancestor::form[1]"))
732
1049
  return next((found for found in around if found is not None), None)
733
1050
 
@@ -746,20 +1063,6 @@ class PageSolver:
746
1063
  _log(f"typed {len(text)} character(s) into the captcha field")
747
1064
  return True
748
1065
 
749
- def _track_piece(self, element: Any, before: str, after: str, exclude: Sequence[float],
750
- travel: float = 0.0) -> Optional[Dict[str, Any]]:
751
- from .tool_calls.track_piece import changed_bbox, locate_piece
752
-
753
- try:
754
- self._screenshot(element, after, timeout_ms=self.config.element_screenshot_timeout_ms)
755
- bbox = changed_bbox(before, after, exclude)
756
- if bbox is None:
757
- return None
758
- return {"bbox": bbox, "piece": locate_piece(before, after, travel, exclude)}
759
- except Exception as exc:
760
- _debug(f"track_piece failed: {exc}")
761
- return None
762
-
763
1066
  @staticmethod
764
1067
  def _shot_scale(shot: str, css_width: float) -> float:
765
1068
  dims = _read_png_dimensions(shot)
@@ -767,77 +1070,71 @@ class PageSolver:
767
1070
 
768
1071
  def _execute_slide(self, page: Any, element: Any, scope: Any, action: Dict[str, Any],
769
1072
  element_box: Dict[str, float]) -> bool:
770
- """Aim the handle at the slot once, then look and correct until the piece is home."""
1073
+ """Press the handle, nudge it to see what it moves, then steer that part's point onto its target.
1074
+
1075
+ A generation-3 answer names all three points, so nothing is read from the page but pixels. A generation-2
1076
+ answer names only the target: its handle comes from the selector table and the part it moves is whatever
1077
+ moved most. That path goes when the last generation-2 model does.
1078
+ """
1079
+ from .tool_calls.slide_tracker import TrackingError, slide_step
1080
+
771
1081
  self._acted_on_board = True
772
- tb = action["target_bounding_box"]
773
- target_x = (float(tb[0]) + float(tb[2])) / 2 * element_box["width"]
1082
+ w, h = element_box["width"], element_box["height"]
1083
+
1084
+ def at(bbox: Sequence[float]) -> Tuple[float, float]:
1085
+ return (float(bbox[0]) + float(bbox[2])) / 2 * w, (float(bbox[1]) + float(bbox[3])) / 2 * h
774
1086
 
775
- handle = self._find_control(scope, SLIDER_HANDLE_SELECTORS)
776
- if handle is None:
777
- piece = self._find_control(scope, PIECE_SELECTORS)
778
- box = piece and piece.bounding_box()
1087
+ goal = at(action["target_bounding_box"])
1088
+ if action.get("handle_bounding_box"):
1089
+ handle, seed = at(action["handle_bounding_box"]), at(action["source_bounding_box"])
1090
+ else:
1091
+ slider = self._find_control(scope, self._sel.slider_handle)
1092
+ piece = None if slider is not None else self._find_control(scope, self._sel.piece)
1093
+ box = (slider or piece).bounding_box() if (slider or piece) is not None else None
779
1094
  if not box:
780
1095
  _log("slide action, but the widget has neither a slider nor a draggable piece")
781
1096
  return False
782
- target_y = (float(tb[1]) + float(tb[3])) / 2 * element_box["height"]
783
- with self._gesture():
784
- self._human.drag(page, (box["x"] + box["width"] / 2, box["y"] + box["height"] / 2),
785
- (element_box["x"] + target_x, element_box["y"] + target_y))
786
- return True
787
-
788
- hbox = handle.bounding_box()
789
- if not hbox:
790
- return False
791
- start_x, hold_y = hbox["x"] + hbox["width"] / 2, hbox["y"] + hbox["height"] / 2
792
- # Mask from the handle's band to the widget's bottom: the filled track moves too.
793
- pad = max(4.0, hbox["height"] * 0.35)
794
- band = [0.0, hbox["y"] - element_box["y"] - pad, element_box["width"], element_box["height"]]
795
- shots = [_tmp_png("slide") for _ in range(2)]
1097
+ handle = (box["x"] + box["width"] / 2 - element_box["x"], box["y"] + box["height"] / 2 - element_box["y"])
1098
+ # A piece with no track is the handle itself, and what it moves is it.
1099
+ seed = handle if piece is not None else None
1100
+
1101
+ press = (element_box["x"] + handle[0], element_box["y"] + handle[1])
1102
+ probe = SLIDE_PROBE_PX if goal[0] >= (seed or handle)[0] else -SLIDE_PROBE_PX
1103
+ timeout = self.config.element_screenshot_timeout_ms
1104
+ first, probed, current = (_tmp_png("slide") for _ in range(3))
796
1105
  try:
797
- self._move_to_element(page, handle, padding_percentage=30.0)
1106
+ self._smooth_move(page, *press)
798
1107
  self._human.press(page)
799
1108
  self._human.pause(PauseKind.GRAB)
800
- self._screenshot(element, shots[0], timeout_ms=self.config.element_screenshot_timeout_ms)
801
- scale = self._shot_scale(shots[0], element_box["width"])
802
- exclude = [v * scale for v in band]
803
-
804
- def live_center():
805
- b = self._measure_piece_box(scope, element_box["width"])
806
- return None if b is None else b["x"] + b["width"] / 2.0 - element_box["x"]
807
-
808
- rest = live_center()
809
- offset = target_x - (start_x - element_box["x"] if rest is None else rest)
810
- self._smooth_move(page, start_x + offset, hold_y)
811
-
812
- widths: List[Tuple[float, float]] = []
813
- last_box = last_piece = None
814
- ratio, steered = 1.0, False
815
- for _ in range(self.config.slide_max_corrections):
816
- self._human.pause(PauseKind.PROBE)
817
- seen = self._track_piece(element, shots[0], shots[1], exclude, travel=offset * ratio * scale)
818
- if seen is not None:
819
- box = seen["bbox"]
820
- widths.append((offset, float(box[2] - box[0]) / scale))
821
- last_box, last_piece = box, seen["piece"]
822
- piece_w, ratio = self._solve_slide_geometry(widths, element_box["width"])
823
- live = live_center()
824
- if live is not None:
825
- center = live
826
- elif last_piece is not None:
827
- center = last_piece["centre"] / scale
828
- elif last_box is not None and piece_w is not None:
829
- center = last_box[2] / scale - piece_w / 2.0
830
- else:
831
- continue
832
- steered = True
833
- error = target_x - center
834
- _debug(f"slider: center={center:.1f} target={target_x:.1f} error={error:+.1f} ratio={ratio:.3f}")
835
- if abs(error) <= self.config.slide_tolerance_px:
1109
+ self._screenshot(element, first, timeout_ms=timeout)
1110
+ k = self._shot_scale(first, w)
1111
+ self._smooth_move(page, press[0] + probe, press[1])
1112
+ self._human.pause(PauseKind.PROBE)
1113
+ self._screenshot(element, probed, timeout_ms=timeout)
1114
+ ask = dict(probe_s=probe * k, goal=(goal[0] * k, goal[1] * k), seed=seed and (seed[0] * k, seed[1] * k),
1115
+ handle=(handle[0] * k, handle[1] * k), bounds=(-handle[0] * k, (w - handle[0]) * k),
1116
+ tol=self.config.slide_tolerance_px * k)
1117
+ look, s, history, moves = probed, probe * k, [], 0
1118
+ while True:
1119
+ try:
1120
+ reply = slide_step(first, probed, look, s=s, history=history, **ask)
1121
+ except TrackingError as exc:
1122
+ _log(f"slider: {exc}; released where the handle is")
1123
+ break
1124
+ if look is not probed:
1125
+ history.append(reply["observation"])
1126
+ _debug(f"slider: point at ({reply['pos'][0] / k:.1f}, {reply['pos'][1] / k:.1f}), "
1127
+ f"{reply['error'] / k:.1f}px from its target, {reply['kind']}")
1128
+ if reply["done"] or moves >= self.config.slide_max_corrections:
1129
+ if reply["error"] > ask["tol"]:
1130
+ _log(f"slider: releasing {reply['error'] / k:.1f}px off target")
836
1131
  break
837
- offset += error / ratio
838
- self._smooth_move(page, start_x + offset, hold_y)
839
- if not steered:
840
- _log("slider: the piece never resolved on screen; released where the opening sweep put it")
1132
+ s = reply["next"]
1133
+ dx, dy = (s[0], s[1]) if reply["grabbed"] else (s, 0.0)
1134
+ self._smooth_move(page, press[0] + dx / k, press[1] + dy / k)
1135
+ self._human.pause(PauseKind.PROBE)
1136
+ self._screenshot(element, current, timeout_ms=timeout)
1137
+ look, moves = current, moves + 1
841
1138
  self._human.pause(PauseKind.SETTLE)
842
1139
  finally:
843
1140
  try:
@@ -845,33 +1142,10 @@ class PageSolver:
845
1142
  except Exception:
846
1143
  pass
847
1144
  self._last_input_ms = _now()
848
- for shot in shots:
1145
+ for shot in (first, probed, current):
849
1146
  _unlink(shot)
850
1147
  return True
851
1148
 
852
- @staticmethod
853
- def _solve_slide_geometry(widths: Sequence[Tuple[float, float]],
854
- widget_width: float) -> Tuple[Optional[float], float]:
855
- """Piece width and handle-to-piece ratio from `(offset, changed width)` readings.
856
-
857
- The widest-apart pair over a 16px spread: changed widths are ±1px, so the ratio error is ±0.13 at the
858
- floor and ±0.5 at 4px. An implausible ratio falls back to 1:1 (true of every vendor observed) rather
859
- than a 0.02 that sends the handle off the track and camoufox into a move that never returns.
860
- """
861
- if not widths:
862
- return None, 1.0
863
- piece_w, ratio = None, 1.0
864
- (o1, w1), (o2, w2) = min(widths, key=lambda m: m[0]), max(widths, key=lambda m: m[0])
865
- if o2 - o1 >= 16.0 and 0.2 <= (w2 - w1) / (o2 - o1) <= 3.0:
866
- ratio = (w2 - w1) / (o2 - o1)
867
- piece_w = w1 - ratio * o1
868
- if piece_w is None:
869
- o, w = widths[-1]
870
- piece_w = w - ratio * o
871
- if not (SLIDE_PIECE_MIN_PX <= piece_w <= widget_width * SLIDE_PIECE_MAX_FRACTION):
872
- return None, ratio
873
- return piece_w, ratio
874
-
875
1149
  # ── detection ────────────────────────────────────────────────────────
876
1150
 
877
1151
  def _has_value(self, scopes: Sequence[Any], selector: str) -> bool:
@@ -903,12 +1177,12 @@ class PageSolver:
903
1177
  except Exception:
904
1178
  return 0
905
1179
 
906
- return any(count(p.selector) > 0 for p in WIDGET_PROBES)
1180
+ return any(count(p.selector) > 0 for p in self._sel.widget_probes)
907
1181
 
908
1182
  def detect_captcha(self, page: Any) -> Optional[Widget]:
909
1183
  """Open challenges first, then unsolved checkboxes, then the inline vendors."""
910
- scopes = _host_scopes(page)
911
- for probe in WIDGET_PROBES:
1184
+ scopes = _host_scopes(page, self._sel.enclave)
1185
+ for probe in self._sel.widget_probes:
912
1186
  at = next(iter(_visible_in(scopes, (probe.selector,))), None)
913
1187
  if at is None or self._already_accepted(scopes, at, probe):
914
1188
  continue
@@ -918,7 +1192,7 @@ class PageSolver:
918
1192
 
919
1193
  def _already_accepted(self, scopes: Sequence[Any], at: Any, probe: WidgetProbe) -> bool:
920
1194
  """A checkbox the vendor has already accepted is not a captcha to solve."""
921
- s = SELECTORS[probe.vendor]
1195
+ s = self._sel.selectors[probe.vendor]
922
1196
  if probe.role != FrameRole.CHECKBOX:
923
1197
  return False
924
1198
  return bool(s.response and self._has_value(scopes, s.response)) or bool(s.checked and self._checked_in(at, s.checked))
@@ -930,13 +1204,13 @@ class PageSolver:
930
1204
  except Exception:
931
1205
  return []
932
1206
  blob = " ".join(str(n) for n in (names or []))
933
- return [vendor for vendor, s in VENDORS if any(h in blob for h in s.hosts)]
1207
+ return [vendor for vendor, s in self._sel.vendors if any(h in blob for h in s.hosts)]
934
1208
 
935
1209
  def _unmatched_vendor_frames(self, page: Any) -> List[Vendor]:
936
1210
  """Vendors showing a frame no selector names. Only asked once detection has found nothing, and a passive frame
937
1211
  (an invisible badge, an enclave) is not a widget, so what is left is markup the table no longer matches."""
938
- scopes = _host_scopes(page)
939
- return [vendor for vendor, s in VENDORS if s.hosts and len(_visible_in(scopes, [f'iframe[src*="{h}"]' for h in s.hosts]))
1212
+ scopes = _host_scopes(page, self._sel.enclave)
1213
+ return [vendor for vendor, s in self._sel.vendors if s.hosts and len(_visible_in(scopes, [f'iframe[src*="{h}"]' for h in s.hosts]))
940
1214
  > len(_visible_in(scopes, s.passive))]
941
1215
 
942
1216
  def _no_widget_message(self, page: Any) -> str:
@@ -968,9 +1242,9 @@ class PageSolver:
968
1242
 
969
1243
  def _is_blocked(self, page: Any) -> bool:
970
1244
  """The vendor showing its refusal screen: rate-limited or flagged, with no board to answer."""
971
- scopes = _host_scopes(page)
972
- for probe in WIDGET_PROBES:
973
- blocked = SELECTORS[probe.vendor].blocked
1245
+ scopes = _host_scopes(page, self._sel.enclave)
1246
+ for probe in self._sel.widget_probes:
1247
+ blocked = self._sel.selectors[probe.vendor].blocked
974
1248
  if probe.role != FrameRole.CHALLENGE or not blocked:
975
1249
  continue
976
1250
  at = next(iter(_visible_in(scopes, (probe.selector,))), None)
@@ -987,11 +1261,11 @@ class PageSolver:
987
1261
  def is_captcha_solved(self, page: Any) -> bool:
988
1262
  """The vendor's own done signal: a response token, a painted success state, or a checked box."""
989
1263
  try:
990
- scopes = _host_scopes(page)
991
- if any(self._has_value(scopes, s) for s in RESPONSE_SELECTORS) or _visible_in(scopes, ACCEPTED_SELECTORS):
1264
+ scopes = _host_scopes(page, self._sel.enclave)
1265
+ if any(self._has_value(scopes, s) for s in self._sel.response) or _visible_in(scopes, self._sel.accepted):
992
1266
  return True
993
- for probe in WIDGET_PROBES:
994
- checked = SELECTORS[probe.vendor].checked
1267
+ for probe in self._sel.widget_probes:
1268
+ checked = self._sel.selectors[probe.vendor].checked
995
1269
  if probe.role != FrameRole.CHECKBOX or not checked:
996
1270
  continue
997
1271
  at = next(iter(_visible_in(scopes, (probe.selector,))), None)
@@ -1004,9 +1278,9 @@ class PageSolver:
1004
1278
  def _is_challenge_freshly_rendered(self, page: Any) -> bool:
1005
1279
  """A next round has painted, as opposed to the answered frame animating closed."""
1006
1280
  try:
1007
- scopes = _host_scopes(page)
1008
- for probe in WIDGET_PROBES:
1009
- fresh = SELECTORS[probe.vendor].fresh
1281
+ scopes = _host_scopes(page, self._sel.enclave)
1282
+ for probe in self._sel.widget_probes:
1283
+ fresh = self._sel.selectors[probe.vendor].fresh
1010
1284
  if probe.role != FrameRole.CHALLENGE or not fresh:
1011
1285
  continue
1012
1286
  at = next(iter(_visible_in(scopes, (probe.selector,))), None)
@@ -1022,16 +1296,12 @@ class PageSolver:
1022
1296
  pass
1023
1297
  return False
1024
1298
 
1025
- @staticmethod
1026
- def _banner_is_fatal_after_retry(kind: Optional[RecaptchaBanner]) -> bool:
1027
- return kind in (RecaptchaBanner.SELECT_MORE, RecaptchaBanner.REJECTED)
1028
-
1029
1299
  def _banner_kind(self, page: Any) -> Optional[RecaptchaBanner]:
1030
1300
  """Which verdict banner the open challenge shows; `dynamic-more` is the dynamic board's normal flow, not an error."""
1031
1301
  try:
1032
- scopes = _host_scopes(page)
1033
- for probe in WIDGET_PROBES:
1034
- banners = SELECTORS[probe.vendor].banners
1302
+ scopes = _host_scopes(page, self._sel.enclave)
1303
+ for probe in self._sel.widget_probes:
1304
+ banners = self._sel.selectors[probe.vendor].banners
1035
1305
  if probe.role != FrameRole.CHALLENGE or not banners:
1036
1306
  continue
1037
1307
  at = next(iter(_visible_in(scopes, (probe.selector,))), None)
@@ -1051,11 +1321,15 @@ class PageSolver:
1051
1321
  Treated as a board it cost 70 screenshots and three model calls in one measured solve, two of them answering
1052
1322
  the checkbox picture with a drag.
1053
1323
  """
1054
- box = self._checkbox_box(frame, widget.vendor)
1324
+ box = self._checkbox_box(frame, widget.vendor) if frame is not None else (
1325
+ widget.element if self._sel.selectors[widget.vendor].box else None)
1055
1326
  if box is not None:
1056
1327
  self._move_to_element(page, box)
1057
1328
  else:
1058
- self._smooth_move(page, *self._find_checkbox_on_screen(widget.element))
1329
+ at = self._find_checkbox_on_screen(page, widget.element)
1330
+ if at is None:
1331
+ return
1332
+ self._smooth_move(page, *at)
1059
1333
  self._human.pause(PauseKind.BETWEEN)
1060
1334
  with self._gesture():
1061
1335
  self._human.click(page, self._last_mouse)
@@ -1066,7 +1340,7 @@ class PageSolver:
1066
1340
 
1067
1341
  Turnstile's box is in a closed shadow root, and a frame can refuse access; both are found on screen instead.
1068
1342
  """
1069
- box = SELECTORS[vendor].box
1343
+ box = self._sel.selectors[vendor].box
1070
1344
  if frame is None or not box:
1071
1345
  return None
1072
1346
  try:
@@ -1075,8 +1349,25 @@ class PageSolver:
1075
1349
  _log(f"[checkbox] the box is out of the DOM's reach ({str(exc).splitlines()[0]}); finding it on screen")
1076
1350
  return None
1077
1351
 
1078
- def _find_checkbox_on_screen(self, element: Any) -> Tuple[float, float]:
1079
- """One capture and OpenCV: a point inside the tick box, in page coordinates. No model is asked."""
1352
+ def _find_checkbox_on_screen(self, page: Any, element: Any) -> Optional[Tuple[float, float]]:
1353
+ """A point inside the tick box, in page coordinates, or None when the widget passed without drawing one.
1354
+
1355
+ Turnstile shows "Verifying…" before its box, so an empty capture is looked at again until
1356
+ `detection_timeout_ms`.
1357
+ """
1358
+ deadline = _now() + self.config.detection_timeout_ms
1359
+ while True:
1360
+ at = self._checkbox_on_screen(element)
1361
+ if at is not None:
1362
+ return at
1363
+ if self.is_captcha_solved(page):
1364
+ return None
1365
+ if _now() >= deadline:
1366
+ raise UnsupportedCaptchaError("the checkbox widget shows no tick box to click")
1367
+ _delay(_DETECTION_POLL_MS)
1368
+
1369
+ def _checkbox_on_screen(self, element: Any) -> Optional[Tuple[float, float]]:
1370
+ """One capture and the element detector, no model: a point inside the tick box, or None when none is drawn."""
1080
1371
  from .tool_calls.find_checkbox import find_checkbox
1081
1372
 
1082
1373
  box = element.bounding_box()
@@ -1091,7 +1382,7 @@ class PageSolver:
1091
1382
  finally:
1092
1383
  _unlink(shot)
1093
1384
  if found is None:
1094
- raise UnsupportedCaptchaError("the checkbox widget shows no tick box to click")
1385
+ return None
1095
1386
  x, y, w, h = (v / scale for v in found)
1096
1387
  return box["x"] + x + w * (0.3 + random.random() * 0.4), box["y"] + y + h * (0.3 + random.random() * 0.4)
1097
1388
 
@@ -1109,7 +1400,7 @@ class PageSolver:
1109
1400
  _delay(self.config.post_solve_outcome_poll_ms)
1110
1401
 
1111
1402
  def _get_verify_button(self, scope: Any) -> Optional[Any]:
1112
- return self._find_control(scope, SUBMIT_SELECTORS)
1403
+ return self._find_control(scope, self._sel.submit)
1113
1404
 
1114
1405
  # ── frames and polling ───────────────────────────────────────────────
1115
1406
 
@@ -1229,17 +1520,32 @@ class PageSolver:
1229
1520
  "waiting for the challenge to settle") or SettleVerdict.TIMEOUT
1230
1521
 
1231
1522
  def _wait_for_grid_cells_loaded(self, element: Any) -> bool:
1523
+ """Hold the next ask until every tile has painted: a model asked about a half-loaded board answers it.
1524
+
1525
+ Past `grid_load_timeout_ms` a blank tile that has stopped changing is taken as painted (a pale photo,
1526
+ or a tile whose image never came), and a board with no grid to read is let through. A tile still
1527
+ painting is waited on until GRID_LOAD_CAP_FACTOR times that, or the solve's deadline.
1528
+ """
1232
1529
  cfg = self.config
1233
1530
 
1234
- def judge(frames, _elapsed):
1531
+ def judge(frames, elapsed):
1235
1532
  if len(frames) < 2:
1236
1533
  return None
1237
1534
  boxes = self._find_grid(frames[1])
1238
- states = boxes and self._grid_cell_states(frames[0], frames[1], boxes)
1239
- return True if states and not states["empty"] and not states["changing"] and states["loaded"] else None
1535
+ if not boxes:
1536
+ return False if elapsed >= cfg.grid_load_timeout_ms else None
1537
+ states = self._grid_cell_states(frames[0], frames[1], boxes)
1538
+ if not states or states["changing"] or not states["loaded"]:
1539
+ return None
1540
+ if not states["empty"] or elapsed >= cfg.grid_load_timeout_ms:
1541
+ return True
1542
+ return None
1240
1543
 
1241
- return bool(self._poll(element, cfg.grid_load_timeout_ms, cfg.grid_load_poll_interval_ms,
1242
- judge, "waiting for grid cells to load"))
1544
+ verdict = self._poll(element, cfg.grid_load_timeout_ms * GRID_LOAD_CAP_FACTOR, cfg.grid_load_poll_interval_ms,
1545
+ judge, "waiting for grid cells to load")
1546
+ if verdict is not True:
1547
+ _log("[recaptcha-grid] the board never finished loading; asking about it as it stands")
1548
+ return verdict is True
1243
1549
 
1244
1550
  def _wait_for_board_painted(self, element: Any) -> int:
1245
1551
  """A still board is not a loaded board: hold until the panel's centre carries structure."""
@@ -1268,7 +1574,7 @@ class PageSolver:
1268
1574
  """Best-effort: hold until the board's pictures have painted."""
1269
1575
  try:
1270
1576
  frame.wait_for_function(_BOARD_IMAGES_READY_JS, arg={"prompt": selectors.fresh or "", "images": ",".join(selectors.images)},
1271
- timeout=self.config.hcaptcha_images_timeout_ms)
1577
+ timeout=self.config.board_images_timeout_ms)
1272
1578
  except Exception:
1273
1579
  pass
1274
1580
 
@@ -1386,7 +1692,7 @@ class PageSolver:
1386
1692
  Both bounds are wall-clock. There is no "enough screens, stop" exit: both spellings were measured on
1387
1693
  number_with_highest_value_video and failed every seed either way.
1388
1694
  """
1389
- import cv2
1695
+ from .keyframes import read_frame
1390
1696
 
1391
1697
  cfg = self.config
1392
1698
  floor_ms = float(cfg.video_burst_duration_ms)
@@ -1412,7 +1718,7 @@ class PageSolver:
1412
1718
  if _now() - self._last_input_ms >= INPUT_SETTLE_MS:
1413
1719
  try:
1414
1720
  self._screenshot(element, shot, animations="allow")
1415
- img = cv2.imread(shot)
1721
+ img = read_frame(shot)
1416
1722
  except Exception as exc:
1417
1723
  _debug(f"burst frame failed: {exc}")
1418
1724
  if img is not None:
@@ -1464,20 +1770,17 @@ class PageSolver:
1464
1770
  f"{'ANIMATED' if cycle_closed or animating else 'still'} ({len(order)} screens; {why})")
1465
1771
  return frames, order, cycle_closed or animating, elapsed_ms, cycle_closed
1466
1772
 
1467
- def _slice(self, frames: List[Any], burst_ms: float) -> Tuple[List[str], str]:
1468
- """Cut a burst with the training-side slicer; the model answers with a frame number into it."""
1469
- from .keyframes import extract_keyframes, write_keyframes
1470
-
1471
- kfset = extract_keyframes(frames, fps=measured_fps(len(frames), burst_ms, self.config.video_burst_fps))
1472
- self._keyframe_mode = kfset.mode
1473
- self._keyframe_steady_screens = kfset.steady_screens
1773
+ def _slice(self, frames: List[Any], burst_ms: float) -> Tuple[AnimatedRecording, str]:
1774
+ """Cut a burst with the training-side slicer; its keyframes steer the wait gate whatever the model sees."""
1474
1775
  temp_dir = tempfile.mkdtemp(prefix="ck_keyframes_")
1475
- paths = [str(p) for p in write_keyframes(kfset, temp_dir, stem="challenge")]
1476
- _log(f"[animated] sliced to {len(paths)} keyframe(s) (mode={kfset.mode})")
1477
- return paths, temp_dir
1776
+ recording = cut_recording(frames, measured_fps(len(frames), burst_ms, self.config.video_burst_fps), temp_dir)
1777
+ self._keyframe_mode = recording.keyframes.mode
1778
+ self._keyframe_steady_screens = recording.keyframes.steady_screens
1779
+ _log(f"[animated] sliced to {len(recording.keyframe_paths)} keyframe(s) (mode={recording.keyframes.mode})")
1780
+ return recording, temp_dir
1478
1781
 
1479
- def _record_keyframes(self, element: Any) -> Tuple[List[str], str, bool]:
1480
- """Record the widget and return `(keyframe_paths, temp_dir, moved)`; the caller removes the dir.
1782
+ def _record_keyframes(self, element: Any) -> Tuple[AnimatedRecording, str, bool]:
1783
+ """Record the widget and return `(recording, temp_dir, moved)`; the caller removes the dir.
1481
1784
 
1482
1785
  Frames stay in memory: the intermediate mp4 this used to write was mp4v, which the serving side may not decode.
1483
1786
 
@@ -1544,8 +1847,8 @@ class PageSolver:
1544
1847
  if len(self._film_frames) > len(frames):
1545
1848
  _log(f"[animated] slicing {len(self._film_frames)} frames filmed over "
1546
1849
  f"{self._film_ms / 1000:.1f}s — every round of this board, not just this one")
1547
- paths, temp_dir = self._slice(self._film_frames or frames, self._film_ms or burst_ms)
1548
- return paths, temp_dir, moved
1850
+ recording, temp_dir = self._slice(self._film_frames or frames, self._film_ms or burst_ms)
1851
+ return recording, temp_dir, moved
1549
1852
 
1550
1853
  def _speculate(self, element: Any, shot: str, puzzle_source: Vendor, retry_mode: Optional[RetryMode],
1551
1854
  text_mode: bool) -> Tuple[List[CaptchaAction], List[Dict[str, Any]], Optional[str]]:
@@ -1574,10 +1877,10 @@ class PageSolver:
1574
1877
  self._known_animated = True
1575
1878
  fut.result()
1576
1879
  self._grant_video_budget()
1577
- paths, keyframe_dir = self._slice(frames, burst_ms)
1880
+ recording, keyframe_dir = self._slice(frames, burst_ms)
1578
1881
  with self._phase(Phase.INFERENCE):
1579
- actions, usage = self._get_keyframe_solution(paths)
1580
- self._animated_plan = (paths, keyframe_dir, actions, usage)
1882
+ actions, usage = self._get_keyframe_solution(recording)
1883
+ self._animated_plan = (recording, keyframe_dir, actions, usage)
1581
1884
  return actions, usage, keyframe_dir
1582
1885
  finally:
1583
1886
  pool.shutdown(wait=True)
@@ -1615,9 +1918,7 @@ class PageSolver:
1615
1918
 
1616
1919
  def _answer_region_recurs(self, keyframe_path: str, ref: Any, box: Any) -> bool:
1617
1920
  """Does the chosen keyframe's answer area appear in a sibling keyframe of the same clip?"""
1618
- import cv2
1619
-
1620
- from .keyframes import MATCH_REGION_TOLERANCE, region_diff_ratio
1921
+ from .keyframes import MATCH_REGION_TOLERANCE, read_frame, region_diff_ratio
1621
1922
 
1622
1923
  folder, base = os.path.dirname(keyframe_path), os.path.basename(keyframe_path)
1623
1924
  prefix = re.sub(r"_\d+\.png$", "_", base, flags=re.IGNORECASE)
@@ -1629,18 +1930,16 @@ class PageSolver:
1629
1930
  except OSError:
1630
1931
  return False
1631
1932
  for other in siblings:
1632
- img = cv2.imread(other)
1933
+ img = read_frame(other)
1633
1934
  if img is not None and img.shape == ref.shape and region_diff_ratio(ref, img, box) <= MATCH_REGION_TOLERANCE:
1634
1935
  return True
1635
1936
  return False
1636
1937
 
1637
1938
  def _wait_for_keyframe(self, element: Any, keyframe_path: str, point_norm: Tuple[float, float]) -> bool:
1638
1939
  """Hold until the widget looks like the keyframe around the action point, or the wait is spent."""
1639
- import cv2
1640
-
1641
- from .keyframes import MATCH_REGION_TOLERANCE, region_box, region_diff_ratio
1940
+ from .keyframes import MATCH_REGION_TOLERANCE, read_frame, region_box, region_diff_ratio
1642
1941
 
1643
- ref = cv2.imread(keyframe_path)
1942
+ ref = read_frame(keyframe_path)
1644
1943
  if ref is None:
1645
1944
  return False
1646
1945
  box = region_box(ref.shape[1::-1], point_norm)
@@ -1658,7 +1957,7 @@ class PageSolver:
1658
1957
  self._check_deadline("waiting for the challenge keyframe")
1659
1958
  try:
1660
1959
  self._screenshot(element, probe, animations="allow")
1661
- live = cv2.imread(probe)
1960
+ live = read_frame(probe)
1662
1961
  except Exception:
1663
1962
  live = None
1664
1963
  if live is not None:
@@ -1687,13 +1986,20 @@ class PageSolver:
1687
1986
  session.element_box["y"] + (y1 + y2) / 2 * session.scale_y)
1688
1987
 
1689
1988
  def _hover_cell(self, page: Any, session: _GridSession, cell: int) -> None:
1989
+ """Rest the hand on a tile: reach it once, then drift a few pixels inside it."""
1690
1990
  if not self._human.hovers:
1691
1991
  return
1692
- first = session.grid_boxes[0]
1693
- cx, cy = self._cell_center_page(cell, session)
1694
- self._smooth_move(page,
1695
- cx + (random.random() - 0.5) * (first[2] - first[0]) * session.scale_x * 0.4,
1696
- cy + (random.random() - 0.5) * (first[3] - first[1]) * session.scale_y * 0.4)
1992
+ x1, y1, x2, y2 = session.grid_boxes[cell - 1]
1993
+ left, top = session.element_box["x"] + x1 * session.scale_x, session.element_box["y"] + y1 * session.scale_y
1994
+ right, bottom = session.element_box["x"] + x2 * session.scale_x, session.element_box["y"] + y2 * session.scale_y
1995
+ x, y = self._last_mouse
1996
+ if left <= x <= right and top <= y <= bottom:
1997
+ x, y = x + random.gauss(0.0, IDLE_DRIFT_PX), y + random.gauss(0.0, IDLE_DRIFT_PX)
1998
+ else:
1999
+ cx, cy = self._cell_center_page(cell, session)
2000
+ x, y = cx + (random.random() - 0.5) * (right - left) * 0.4, cy + (random.random() - 0.5) * (bottom - top) * 0.4
2001
+ inset = min(4.0, (right - left) / 4, (bottom - top) / 4)
2002
+ self._smooth_move(page, min(max(x, left + inset), right - inset), min(max(y, top + inset), bottom - inset))
1697
2003
 
1698
2004
  @staticmethod
1699
2005
  def _bbox_to_cell(bbox: Sequence[float], grid_boxes: Sequence[Sequence[int]],
@@ -1714,11 +2020,14 @@ class PageSolver:
1714
2020
  def _hover_loop(self, page: Any, session: _GridSession, cells: Sequence[int]) -> Optional[Callable[[], None]]:
1715
2021
  if not cells:
1716
2022
  return None
1717
- cycle = itertools.cycle(cells)
2023
+ due = [0.0]
1718
2024
 
1719
2025
  def hover():
2026
+ if _now() < due[0]:
2027
+ return
2028
+ due[0] = _now() + random.uniform(*IDLE_DRIFT_EVERY_MS)
1720
2029
  try:
1721
- self._hover_cell(page, session, next(cycle))
2030
+ self._hover_cell(page, session, cells[0])
1722
2031
  except Exception:
1723
2032
  pass
1724
2033
 
@@ -1807,6 +2116,10 @@ class PageSolver:
1807
2116
  loading, _ = self._watch_clicked_tiles(page, element, session, clicked_order)
1808
2117
  self._wait_for_any_clicked_tile_loaded(page, element, session, loading)
1809
2118
  continue
2119
+ if kind == ActionKind.REFRESH:
2120
+ # A new board replaces this one: nothing clicked on it is submitted; the next loop reads the new one.
2121
+ refreshed = self._execute_refresh(page, element.content_frame(), action, element_box)
2122
+ return refreshed or performed, all_usage
1810
2123
  if kind != ActionKind.CLICK:
1811
2124
  _log(f"[recaptcha-grid] round {round_index}: unexpected action; re-solving.")
1812
2125
  continue
@@ -1818,6 +2131,10 @@ class PageSolver:
1818
2131
  clicked_this_round: List[int] = []
1819
2132
  for bbox in bboxes:
1820
2133
  cell = self._bbox_to_cell(bbox, session.grid_boxes, session.screenshot_w, session.screenshot_h)
2134
+ if cell is not None and cell in clicked_this_round:
2135
+ # Two points in one tile: a second press deselects what the first selected.
2136
+ _log(f"[recaptcha-grid] round {round_index}: cell {cell} is already clicked; not pressing it again.")
2137
+ continue
1821
2138
  self._execute_click(page, {"target_bounding_box": bbox}, element_box)
1822
2139
  if cell is not None:
1823
2140
  clicked_order.append(cell)
@@ -1861,13 +2178,13 @@ class PageSolver:
1861
2178
  self._click_checkbox(page, widget, frame)
1862
2179
  return True, []
1863
2180
 
1864
- if frame and role == FrameRole.CHALLENGE and SELECTORS[puzzle_source].images:
2181
+ if frame and role == FrameRole.CHALLENGE and self._sel.selectors[puzzle_source].images:
1865
2182
  if self._last_submit_frame_hash:
1866
2183
  with self._phase(Phase.AWAIT_NEXT_ROUND):
1867
2184
  self._wait_for_change_since(element, self._last_submit_frame_hash)
1868
2185
  self._last_submit_frame_hash = None
1869
- with self._phase(Phase.HCAPTCHA_IMAGES):
1870
- self._wait_for_board_images(frame, SELECTORS[puzzle_source])
2186
+ with self._phase(Phase.BOARD_IMAGES):
2187
+ self._wait_for_board_images(frame, self._sel.selectors[puzzle_source])
1871
2188
 
1872
2189
  # THE TWO QUESTIONS BELOW ARE PUT TO A PAINTED BOARD. Which expert answers the round is read out of
1873
2190
  # the DOM and whether the board cycles is read off its motion, and a widget that has not drawn yet
@@ -1881,9 +2198,11 @@ class PageSolver:
1881
2198
  self._wait_for_board_painted(element)
1882
2199
 
1883
2200
  # Only the DOM can tell a typed captcha from a click puzzle; hCaptcha and reCAPTCHA never type.
1884
- text_mode = puzzle_source not in VENDORS_WITH_BESPOKE_HANDLING and self._answer_box(scope, widget.at) is not None
2201
+ answer_box = None if puzzle_source in VENDORS_WITH_BESPOKE_HANDLING else self._answer_box(scope, widget.at)
2202
+ text_mode = answer_box is not None
1885
2203
  if text_mode:
1886
2204
  _log("widget has a text box; solving as a distorted-text captcha")
2205
+ element = _WithAnswerBox(element, answer_box)
1887
2206
 
1888
2207
  # A reCAPTCHA board is read by its grid below, not filmed.
1889
2208
  filmable = puzzle_source != Vendor.RECAPTCHA and not text_mode
@@ -1910,20 +2229,21 @@ class PageSolver:
1910
2229
  self._wait_for_board_painted(element)
1911
2230
 
1912
2231
  shot = _tmp_png("captcha")
2232
+ self._round_board = None
1913
2233
  performed = slid = answered = have_shot = False
1914
2234
  all_usage: List[Dict[str, Any]] = []
1915
2235
  keyframe_dir: Optional[str] = None
1916
2236
  try:
1917
2237
  if is_animated:
1918
2238
  if self._animated_plan is not None:
1919
- keyframes, keyframe_dir, actions, all_usage = self._animated_plan
2239
+ recording, keyframe_dir, actions, all_usage = self._animated_plan
1920
2240
  reused = actions is not None
1921
2241
  if not reused:
1922
2242
  # Drop the ANSWER, keep the FRAMES — and the frames grow. Filming another chunk and
1923
2243
  # re-slicing the accumulation puts a better question up; re-asking the same frames
1924
2244
  # puts the same question up and gets the same answer back.
1925
2245
  with self._phase(Phase.BURST):
1926
- keyframes, new_dir, moved = self._record_keyframes(element)
2246
+ recording, new_dir, moved = self._record_keyframes(element)
1927
2247
  shutil.rmtree(keyframe_dir, ignore_errors=True)
1928
2248
  keyframe_dir = new_dir
1929
2249
  self._known_animated = self._known_animated or moved
@@ -1932,27 +2252,28 @@ class PageSolver:
1932
2252
  else:
1933
2253
  reused = False
1934
2254
  with self._phase(Phase.BURST):
1935
- keyframes, keyframe_dir, moved = self._record_keyframes(element)
2255
+ recording, keyframe_dir, moved = self._record_keyframes(element)
1936
2256
  self._known_animated = self._known_animated or moved
1937
2257
  # The clip answers the question the probe asked: a board that never moved is a still, and the
1938
2258
  # video expert can only answer a still with a frame number the widget will not take.
1939
- if len(keyframes) < 2 or not self._known_animated:
2259
+ if len(recording.keyframe_paths) < 2 or not self._known_animated:
1940
2260
  _log("[animated] the recording shows a still board; solving it as a still")
1941
2261
  is_animated = False
1942
- shutil.copyfile(keyframes[-1], shot)
2262
+ shutil.copyfile(recording.keyframe_paths[-1], shot)
1943
2263
  have_shot = True
1944
2264
  self._stop_animated_film()
1945
2265
  shutil.rmtree(keyframe_dir, ignore_errors=True)
1946
2266
  keyframe_dir = None
1947
2267
  elif not reused:
1948
2268
  with self._phase(Phase.INFERENCE):
1949
- actions, all_usage = self._get_keyframe_solution(keyframes)
1950
- self._animated_plan = (keyframes, keyframe_dir, actions, all_usage)
2269
+ actions, all_usage = self._get_keyframe_solution(recording)
2270
+ self._animated_plan = (recording, keyframe_dir, actions, all_usage)
1951
2271
 
1952
2272
  if not is_animated:
1953
2273
  if not have_shot:
1954
2274
  with self._phase(Phase.SCREENSHOT):
1955
2275
  self._screenshot(element, shot, timeout_ms=self.config.element_screenshot_timeout_ms)
2276
+ self._guard_fallbacks_to_board(self._board_hash(element, shot, filmed=have_shot))
1956
2277
  if self._should_speculate(puzzle_source, text_mode):
1957
2278
  actions, all_usage, keyframe_dir = self._speculate(element, shot, puzzle_source, retry_mode, text_mode)
1958
2279
  is_animated = keyframe_dir is not None
@@ -1975,10 +2296,12 @@ class PageSolver:
1975
2296
 
1976
2297
  _log("[answer] " + json.dumps({"actions": [_as_dict(a) for a in actions]}, default=str))
1977
2298
  # A repeated answer is not re-performed: the widget already refused it, and every extra press is
1978
- # behaviour a vendor scores. Re-asking with a fresh sample or a recording is the round's only move.
2299
+ # behaviour a vendor scores. Re-asking, or asking a recording, is the round's only move.
1979
2300
  # `_note_answer` drops the refused animated answer on its way through, so the next round re-asks.
1980
2301
  if self._note_answer(actions, retry_mode):
1981
2302
  return False, all_usage
2303
+ if not is_animated:
2304
+ self._keep_pointer_screen(shot, puzzle_source, actions)
1982
2305
  _log(f"executing {len(actions)} action(s)")
1983
2306
 
1984
2307
  for raw_action in actions:
@@ -1998,7 +2321,7 @@ class PageSolver:
1998
2321
  if bbox:
1999
2322
  self._human.pause(PauseKind.BETWEEN)
2000
2323
  performed = answered = True
2001
- elif kind == ActionKind.DRAG and not action.get("source_bounding_box"):
2324
+ elif kind == ActionKind.SLIDE or (kind == ActionKind.DRAG and not action.get("source_bounding_box")):
2002
2325
  if self._execute_slide(page, element, scope, action, element_box):
2003
2326
  performed = slid = True
2004
2327
  elif kind == ActionKind.DRAG:
@@ -2009,6 +2332,13 @@ class PageSolver:
2009
2332
  elif kind == ActionKind.TYPE:
2010
2333
  if self._execute_type(page, scope, action, widget.at):
2011
2334
  performed = answered = True
2335
+ elif kind == ActionKind.HOLD:
2336
+ # The widget submits itself when the hold completes, like a slide on release.
2337
+ self._execute_hold(page, action, element_box, element, self._sel.selectors[widget.vendor].hold_completes)
2338
+ performed = slid = True
2339
+ elif kind == ActionKind.REFRESH:
2340
+ # Nothing after a refresh, Verify included, belongs to the board it replaces.
2341
+ return self._execute_refresh(page, scope, action, element_box), all_usage
2012
2342
  elif kind == ActionKind.WAIT:
2013
2343
  duration = int(action.get("duration_ms") or 0)
2014
2344
  if duration > 0:
@@ -2016,13 +2346,19 @@ class PageSolver:
2016
2346
  performed = True
2017
2347
 
2018
2348
  # A slide submits itself on release, and any Verify found afterwards belongs to the host page and would
2019
- # submit the guarded form while the verdict is in flight. An empty or `done` plan still presses Verify/Skip.
2020
- verify_button = self._get_verify_button(scope) if frame or not slid else None
2021
- if not slid and (answered or not performed) and verify_button:
2349
+ # submit the guarded form while the verdict is in flight, unless this board has already taken a Verify
2350
+ # from us: then that button is the widget's, and a slide on it submits nothing by itself. An empty or
2351
+ # `done` plan still presses Verify/Skip. FunCaptcha's answer is the click itself: an arrow pages and
2352
+ # Submit submits. The generic Verify fallback would submit the page an arrow just turned to.
2353
+ submits = self._submitted_on_board if slid else answered or not performed
2354
+ verify_button = self._get_verify_button(scope) if submits and puzzle_source != Vendor.FUNCAPTCHA else None
2355
+ if verify_button:
2022
2356
  _log(f"clicking Verify to submit ({puzzle_source}).")
2023
2357
  self._move_and_click(page, verify_button)
2024
- performed = True
2358
+ performed = self._submitted_on_board = True
2025
2359
  self._last_submit_frame_hash = self._element_frame_hash(element)
2360
+ elif answered and puzzle_source != Vendor.FUNCAPTCHA:
2361
+ self._keep_plans_of_this_many_clicks(actions)
2026
2362
  finally:
2027
2363
  _unlink(shot)
2028
2364
  held = self._animated_plan[1] if self._animated_plan else None
@@ -2039,6 +2375,9 @@ class PageSolver:
2039
2375
  return CaptchaWatcher(solver=self, page=page, **options)
2040
2376
 
2041
2377
  def solve(self, page: Any) -> SolveResult:
2378
+ # Loading a model takes as long as the whole solve budget, so a cold server must not spend it.
2379
+ if config.selfhost_active():
2380
+ ensure_server(config.base_url())
2042
2381
  start = _now()
2043
2382
  usage: List[Dict[str, Any]] = []
2044
2383
  self._last_submit_frame_hash = None
@@ -2239,8 +2578,15 @@ class PageSolver:
2239
2578
  raise blocked("it is showing its try-again-later screen")
2240
2579
  if said == Verdict.REJECTED:
2241
2580
  _log(f"[verdict] the vendor rejected the answer after {verdict_ms:.0f}ms")
2242
-
2243
- if self._banner_is_fatal_after_retry(self._banner_kind(page)):
2581
+ # Only a refusal earns the server's next plan. A round that ended with no verdict, or on a
2582
+ # board that merely repainted, has not refused anything, and every extra press is behaviour
2583
+ # a vendor scores.
2584
+ self._refused_rounds += 1
2585
+ self._apply_refusals()
2586
+
2587
+ # Only "select all matching images" means tiles were missed; "please try again" is a wrong answer and
2588
+ # deals a new board, which is asked fresh.
2589
+ if self._banner_kind(page) == RecaptchaBanner.SELECT_MORE:
2244
2590
  _log("reCAPTCHA under-selection error; the next round asks for the missed tiles.")
2245
2591
  pending_retry_mode = RetryMode.MISSED_TILES
2246
2592
 
@@ -2249,9 +2595,9 @@ class PageSolver:
2249
2595
  if self._no_progress_rounds:
2250
2596
  stuck = CaptchaSolveError(f"no progress: the model returned the same answer "
2251
2597
  f"{self._no_progress_rounds + 1} times running")
2252
- # A board answered the same way after every resample is one the model cannot read: measured, no
2253
- # solve ever followed a third identical answer, and each further round cost the board 3-7s.
2254
- if self._no_progress_rounds >= cfg.max_no_progress_rounds:
2598
+ # A repeat pressed nothing, so a further round is only worth its 3-7s if it can do something else.
2599
+ if (self._no_progress_rounds >= cfg.max_no_progress_rounds
2600
+ or not self._another_move_left(pending_retry_mode)):
2255
2601
  raise stuck
2256
2602
  again(stuck)
2257
2603
  elif not did_interact:
@@ -2260,6 +2606,8 @@ class PageSolver:
2260
2606
  if cfg.video_solve_enabled:
2261
2607
  self._arm_animated_probe()
2262
2608
  again(CaptchaSolveError("the solver performed no interactions this round"))
2609
+ else:
2610
+ last_failure = None
2263
2611
 
2264
2612
  if isinstance(last_failure, UnsupportedChallengeError):
2265
2613
  raise UnsupportedChallengeError(f"{last_failure} (after {cfg.max_solve_loops} solve loops)")