Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
3689 lines (3429 loc) · 143 KB
/
Copy pathmain.py
File metadata and controls
3689 lines (3429 loc) · 143 KB
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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Planner + Executor scaffold for Amazon shopping (local models).
Planner: Qwen 2.5 7B produces a JSON plan.
Executor: Qwen 2.5 3B executes each step with AgentRuntime assertions.
M4 Optimizations:
- Auto device mapping for optimal layer distribution across unified memory
- BFloat16 dtype (optimized for Apple Neural Engine)
- SDPA attention implementation (faster than eager on MPS)
- Low CPU memory usage mode for better memory management
Environment overrides (optional):
- DEVICE_MAP: Set to "mps" or "cpu" to override auto-detection
- TORCH_DTYPE: Set to "bf16", "fp16" to override dtype
"""
from __future__ import annotations
import asyncio
import base64
import builtins
import importlib
import json
import os
import random
import re
import time
import uuid
import hashlib
import sys
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any, Iterable
import torch
from dotenv import load_dotenv
from transformers import AutoModelForCausalLM, AutoTokenizer
sys.path.insert(
0, os.path.join(os.path.dirname(__file__), "..", "amazon_shopping", "shared")
)
from video_generator_simple import create_demo_video
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "amazon_shopping_with_assertions"))
from main import StepTokenUsage
from predicate.actions import click_async, press_async
from predicate.agent_runtime import AgentRuntime
from predicate.async_api import AsyncPredicateBrowser
from predicate.backends.playwright_backend import PlaywrightBackend
from predicate.backends.sentience_context import SentienceContext
from predicate.cursor_policy import CursorPolicy
from predicate.failure_artifacts import FailureArtifactsOptions
from predicate.llm_provider import LocalVisionLLMProvider, MLXVLMProvider
from predicate.models import Snapshot, SnapshotOptions
from predicate.snapshot_diff import SnapshotDiff
from predicate.trace_event_builder import TraceEventBuilder
from predicate.tracer_factory import create_tracer
from predicate.verification import (
all_of,
any_of,
custom,
element_count,
exists,
not_exists,
url_contains,
url_matches,
)
from predicate import CaptchaOptions, HumanHandoffSolver
SEARCH_QUERY = os.getenv("AMAZON_QUERY", "thinkpad")
DEFAULT_PLAN_URL = "https://www.amazon.com"
@dataclass
class LlmResult:
content: str
prompt_tokens: int
completion_tokens: int
total_tokens: int
# ---------------------------------------------------------------------------
# Config: PlannerExecutorConfig (matches design doc + webbench reference)
# ---------------------------------------------------------------------------
@dataclass
class PlannerExecutorConfig:
"""
Configuration for Planner + Executor agent.
Based on docs/PLANNER_EXECUTOR_DESIGN.md and webbench/webbench/agents/planner_executor_agent.py.
Key features:
- Incremental limit escalation (initial_limit -> max_limit with limit_step increments)
- Vision fallback configuration
- Retry settings for verification
"""
# Snapshot limit escalation settings (from design doc RetryConfig)
snapshot_limit_base: int = 60
snapshot_limit_max: int = 200
snapshot_limit_step: int = 30
# Retry configuration
verify_timeout_s: float = 10.0
verify_poll_s: float = 0.5
verify_max_attempts: int = 5
executor_repair_attempts: int = 2
# Vision fallback
vision_fallback_enabled: bool = True
max_vision_calls: int = 3
# Planner settings
planner_max_tokens: int = 2048
planner_repair_attempts: int = 3
# Executor settings
executor_max_tokens: int = 96
# Stabilization (post-action wait for DOM to settle)
stabilize_enabled: bool = True
stabilize_poll_s: float = 0.35
stabilize_max_attempts: int = 6
# ---------------------------------------------------------------------------
# SnapshotContext: Shared page state between Planner and Executor
# ---------------------------------------------------------------------------
@dataclass
class SnapshotContext:
"""
Shared page state between Planner and Executor to avoid redundant captures.
Based on docs/PLANNER_EXECUTOR_DESIGN.md Section 3.
"""
snapshot: Snapshot
compact_representation: str
screenshot_base64: str | None
captured_at: datetime
limit_used: int
snapshot_success: bool = True
requires_vision: bool = False
def is_stale(self, max_age_seconds: float = 5.0) -> bool:
"""Check if snapshot is too old to reuse."""
return (datetime.now() - self.captured_at).total_seconds() > max_age_seconds
def should_use_vision(self) -> bool:
"""Check if executor should skip snapshot and use vision directly."""
return not self.snapshot_success or self.requires_vision
def detect_snapshot_failure(snap: Snapshot) -> tuple[bool, str | None]:
"""
Detect if snapshot is unusable and should trigger vision fallback.
Based on docs/PLANNER_EXECUTOR_DESIGN.md Section 4.
Returns:
(should_use_vision, reason)
"""
# Check explicit status field (tri-state: success, error, require_vision)
status = getattr(snap, "status", "success")
if status == "require_vision":
return True, "require_vision"
if status == "error":
error = getattr(snap, "error", None)
return True, f"snapshot_error:{error}"
# Check diagnostics if available
diag = getattr(snap, "diagnostics", None)
if diag:
# Low confidence indicates unreliable snapshot
confidence = getattr(diag, "confidence", 1.0)
if confidence is not None and float(confidence) < 0.3:
return True, "low_confidence"
# Canvas-heavy pages need vision
has_canvas = getattr(diag, "has_canvas", False)
elements = getattr(snap, "elements", []) or []
if has_canvas and len(elements) < 5:
return True, "canvas_page"
# Very few elements usually indicates a problem
elements = getattr(snap, "elements", []) or []
if len(elements) < 3:
return True, "too_few_elements"
return False, None
def now_iso() -> str:
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def append_jsonl(path: Path, payload: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(payload, ensure_ascii=True) + "\n")
def get_device_map() -> str:
override = os.getenv("DEVICE_MAP")
if override:
return override
# On Apple Silicon, use "mps" to avoid accelerate auto device_map
# issues (e.g., inferred max_memory missing "cpu").
if torch.backends.mps.is_available():
return "mps"
return "auto"
def get_torch_dtype() -> torch.dtype:
override = os.getenv("TORCH_DTYPE")
if override:
if override.lower() == "bf16":
return torch.bfloat16
if override.lower() == "fp16":
return torch.float16
# Use bfloat16 on MPS (Apple Silicon M1/M2/M3/M4) for better performance
# bfloat16 is optimized for Apple Neural Engine and has better numerical stability
if torch.backends.mps.is_available():
return torch.bfloat16
return torch.float16
class LocalHFModel:
def __init__(self, model_name: str, device_map: str, torch_dtype: torch.dtype):
self.model_name = model_name
self.tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
# Build model loading kwargs with MPS-specific optimizations
load_kwargs = {
"device_map": device_map,
"dtype": torch_dtype,
"low_cpu_mem_usage": True, # Better memory management for large models
}
# MPS-specific optimizations for Apple Silicon (M1/M2/M3/M4)
if torch.backends.mps.is_available():
# MPS doesn't support flash attention - use eager or sdpa
# eager is more stable on MPS but sdpa is faster if available
load_kwargs["attn_implementation"] = "sdpa" # Scaled Dot Product Attention
# Note: If you encounter errors, fallback to "eager"
# load_kwargs["attn_implementation"] = "eager"
try:
self.model = AutoModelForCausalLM.from_pretrained(
model_name,
**load_kwargs
)
except RuntimeError as exc:
msg = str(exc)
if "Invalid buffer size" in msg and torch.backends.mps.is_available():
raise RuntimeError(
"Model allocation failed on MPS (Apple Silicon). "
"This usually means the model is too large for the available memory. "
"Try a smaller HF model (e.g., Qwen/Qwen2.5-3B-Instruct) or use MLX "
"with a 4-bit model (PLANNER_PROVIDER=mlx, EXECUTOR_PROVIDER=mlx)."
) from exc
raise
def generate(
self,
system: str,
user: str,
max_new_tokens: int = 256,
temperature: float = 0.0,
) -> LlmResult:
messages = [
{"role": "system", "content": system},
{"role": "user", "content": user},
]
encoding = self.tokenizer.apply_chat_template(
messages, return_tensors="pt", add_generation_prompt=True
)
device = getattr(self.model, "device", "cpu")
if hasattr(encoding, "to"):
encoding = encoding.to(device)
input_ids = None
attention_mask = None
try:
input_ids = encoding["input_ids"]
if "attention_mask" in encoding:
attention_mask = encoding["attention_mask"]
except Exception:
input_ids = encoding
input_ids = input_ids.to(device)
if attention_mask is not None:
attention_mask = attention_mask.to(device)
if attention_mask is None:
attention_mask = torch.ones_like(input_ids)
do_sample = temperature > 0
output_ids = self.model.generate(
input_ids,
attention_mask=attention_mask,
max_new_tokens=max_new_tokens,
do_sample=do_sample,
temperature=temperature if do_sample else None,
pad_token_id=self.tokenizer.eos_token_id,
eos_token_id=self.tokenizer.eos_token_id,
)
generated = output_ids[0][input_ids.shape[-1] :]
text = self.tokenizer.decode(generated, skip_special_tokens=True)
prompt_tokens = int(input_ids.shape[-1])
completion_tokens = int(generated.shape[-1])
return LlmResult(
content=text.strip(),
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
total_tokens=prompt_tokens + completion_tokens,
)
class LocalMLXModel:
def __init__(self, model_name: str):
self.model_name = model_name
try:
self._mlx_lm = importlib.import_module("mlx_lm")
except Exception as exc:
raise RuntimeError(
"mlx-lm is required for MLX text models. Install with: pip install mlx-lm"
) from exc
load_fn = getattr(self._mlx_lm, "load", None)
if not load_fn:
raise RuntimeError("mlx_lm.load not available in your mlx-lm install.")
self.model, self.tokenizer = load_fn(model_name)
def _build_prompt(self, system: str, user: str) -> str:
messages = [
{"role": "system", "content": system},
{"role": "user", "content": user},
]
apply_chat_template = getattr(self.tokenizer, "apply_chat_template", None)
if callable(apply_chat_template):
# Disable thinking mode for Qwen 3.5 models to get direct JSON output
kwargs: dict[str, Any] = {"tokenize": False, "add_generation_prompt": True}
if "qwen3" in self.model_name.lower():
kwargs["enable_thinking"] = False
return apply_chat_template(messages, **kwargs)
return f"{system}\n\n{user}"
def generate(
self,
system: str,
user: str,
max_new_tokens: int = 256,
temperature: float = 0.0,
) -> LlmResult:
prompt = self._build_prompt(system, user)
generate_fn = getattr(self._mlx_lm, "generate", None)
if not generate_fn:
raise RuntimeError("mlx_lm.generate not available in your mlx-lm install.")
kwargs: dict[str, Any] = {"max_tokens": max_new_tokens}
if temperature and temperature > 0:
try:
sample_utils = importlib.import_module("mlx_lm.sample_utils")
make_sampler = getattr(sample_utils, "make_sampler", None)
if callable(make_sampler):
kwargs["sampler"] = make_sampler(temp=temperature)
except Exception:
pass
text = generate_fn(
self.model,
self.tokenizer,
prompt,
**kwargs,
)
# mlx-lm doesn't expose token usage directly, so we calculate it
# using the tokenizer
try:
prompt_tokens = len(self.tokenizer.encode(prompt))
completion_tokens = len(self.tokenizer.encode(text.strip()))
except Exception:
prompt_tokens = 0
completion_tokens = 0
return LlmResult(
content=text.strip(),
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
total_tokens=prompt_tokens + completion_tokens,
)
def extract_json(text: str) -> dict[str, Any]:
# Strip DeepSeek R1 thinking tokens (</think> marks end of reasoning)
if "</think>" in text:
text = text.split("</think>", 1)[-1].strip()
# Also handle plain "think" without XML tags (some models output this way)
# Look for common patterns that indicate end of reasoning
for marker in ["</think>", "\n\n```json", "\n```json", "\n\n{"]:
if marker in text:
idx = text.find(marker)
if marker.startswith("\n"):
text = text[idx:].strip()
break
# Prefer fenced JSON blocks if present.
fence_match = re.search(r"```json\s*([\s\S]+?)\s*```", text, flags=re.IGNORECASE)
if fence_match:
return json.loads(fence_match.group(1))
# Fallback: first {...} block
start = text.find("{")
end = text.rfind("}")
if start == -1 or end == -1 or end <= start:
raise ValueError("No JSON object found in planner output")
return json.loads(text[start : end + 1])
def parse_click_id(text: str) -> int | None:
m = re.search(r"CLICK\s*\(\s*(\d+)\s*\)", text, flags=re.IGNORECASE)
return int(m.group(1)) if m else None
def emit_snapshot_trace(runtime: AgentRuntime, snap: Snapshot) -> None:
if not snap:
return
prev = getattr(runtime, "_trace_prev_snapshot", None)
try:
elements_with_diff = SnapshotDiff.compute_diff_status(snap, prev)
payload = snap.model_dump()
payload["elements"] = elements_with_diff
snap_with_diff = Snapshot(**payload)
except Exception:
snap_with_diff = snap
setattr(runtime, "_trace_prev_snapshot", snap)
setattr(runtime, "_trace_last_snapshot", snap_with_diff)
# Include step_index for Studio compatibility
step_index = getattr(runtime, "step_index", None)
snapshot_data = TraceEventBuilder.build_snapshot_event(snap_with_diff)
if step_index is not None:
snapshot_data["step_index"] = step_index
if snap.screenshot:
screenshot_base64 = (
snap.screenshot.split(",", 1)[1]
if snap.screenshot.startswith("data:image")
else snap.screenshot
)
snapshot_data["screenshot_base64"] = screenshot_base64
if snap.screenshot_format:
snapshot_data["screenshot_format"] = snap.screenshot_format
runtime.tracer.emit(
"snapshot",
snapshot_data,
step_id=getattr(runtime, "step_id", None),
)
def _compute_hash(value: str) -> str:
return hashlib.sha256(value.encode("utf-8", errors="ignore")).hexdigest()
def find_no_thanks_button_id(snap) -> int | None:
if not snap or not getattr(snap, "elements", None):
return None
candidates = []
for el in snap.elements:
try:
if getattr(el, "role", "") != "button":
continue
text = (getattr(el, "text", "") or "").strip()
if "no thanks" not in text.lower():
continue
in_viewport = bool(getattr(el, "in_viewport", True))
doc_y = getattr(el, "doc_y", None)
importance = getattr(el, "importance", 0) or 0
candidates.append((not in_viewport, doc_y if doc_y is not None else 1e9, -importance, el.id))
except Exception:
continue
if not candidates:
return None
candidates.sort()
return candidates[0][3]
def drawer_visible_in_snapshot(snap) -> bool:
if not snap or not getattr(snap, "elements", None):
return False
for el in snap.elements:
try:
text = (getattr(el, "text", "") or "").strip()
nearby = (getattr(el, "nearby_text", "") or "").strip()
combined = f"{text} {nearby}".strip().lower()
if (
"no thanks" in combined
or "add protection" in combined
or "add to your order" in combined
):
return True
except Exception:
continue
return False
def find_checkout_button_id(snap) -> int | None:
if not snap or not getattr(snap, "elements", None):
return None
candidates = []
for el in snap.elements:
try:
el_id = getattr(el, "id", None)
if not isinstance(el_id, int) or el_id <= 0:
continue
role = (getattr(el, "role", "") or "").lower()
if role not in {"button", "link"}:
continue
text = (getattr(el, "text", "") or "").strip()
nearby = (getattr(el, "nearby_text", "") or "").strip()
combined = f"{text} {nearby}".strip()
lowered = combined.lower()
if "checkout" not in lowered and "proceed to checkout" not in lowered:
continue
if (
"add to cart" in lowered
or "buy now" in lowered
or "add protection" in lowered
or "no thanks" in lowered
):
continue
in_viewport = bool(getattr(el, "in_viewport", True))
doc_y = getattr(el, "doc_y", None)
importance = getattr(el, "importance", 0) or 0
is_checkout_button = 0 if "checkout" in lowered else 1
candidates.append(
(
not in_viewport,
is_checkout_button,
doc_y if doc_y is not None else 1e9,
-importance,
el_id,
)
)
except Exception:
continue
if not candidates:
return None
candidates.sort()
return candidates[0][4] # el_id is at index 4
def find_search_box_id(snap) -> int | None:
if not snap or not getattr(snap, "elements", None):
return None
candidates = []
for el in snap.elements:
try:
role = (getattr(el, "role", "") or "").lower()
if role not in {"searchbox", "textbox", "combobox"}:
continue
text = (getattr(el, "text", "") or "").strip()
in_viewport = bool(getattr(el, "in_viewport", True))
doc_y = getattr(el, "doc_y", None)
importance = getattr(el, "importance", 0) or 0
prefers_search = 0 if "search" in text.lower() else 1
candidates.append(
(
not in_viewport,
prefers_search,
doc_y if doc_y is not None else 1e9,
-importance,
el.id,
)
)
except Exception:
continue
if not candidates:
return None
candidates.sort()
return candidates[0][4]
def find_first_product_link_id(snap, keyword: str) -> int | None:
"""
Find the first valid product link in search results.
Prioritization:
1. Links with /dp/ or /gp/product/ in href (REQUIRED - these are product pages)
2. Links containing the search keyword in text (preferred but not required)
3. Links with lower doc_y (higher on page)
4. Links with higher importance
Explicitly excludes:
- Filter/refinement links (refinements= in href)
- Sponsored labels and menu items
"""
if not snap or not getattr(snap, "elements", None):
return None
key = (keyword or "").strip().lower()
candidates = []
for el in snap.elements:
try:
role = (getattr(el, "role", "") or "").lower()
if role != "link":
continue
href = (getattr(el, "href", "") or "").lower()
# REQUIRED: Must be a product page link
if "/dp/" not in href and "/gp/product/" not in href:
continue
# EXCLUDE: Filter/refinement links
if "refinements=" in href or "rh=" in href:
continue
text = (getattr(el, "text", "") or "").strip()
# Skip empty text or very short text (likely icons)
if not text or len(text) < 3:
continue
# Skip obvious non-product items
text_lower = text.lower()
if any(skip in text_lower for skip in [
"sponsored", "free shipping", "prime", "filter", "sort by",
"amazon haul", "see all", "show more"
]):
continue
in_viewport = bool(getattr(el, "in_viewport", True))
doc_y = getattr(el, "doc_y", None)
importance = getattr(el, "importance", 0) or 0
# Prioritize: keyword match (0=has keyword, 1=no keyword), viewport, doc_y, importance
has_keyword = 0 if key and key in text_lower else 1
candidates.append(
(has_keyword, not in_viewport, doc_y if doc_y is not None else 1e9, -importance, el.id)
)
except Exception:
continue
if not candidates:
return None
candidates.sort()
return candidates[0][4]
def is_valid_product_link(snap, element_id: int) -> bool:
"""
Check if the executor's click choice is a valid product link.
Returns True if the element:
- Is a link with href containing /dp/ or /gp/product/, OR
- Is a link with product-like text (brand + product name) and NOT a filter/rating link
Returns False if the element:
- Contains refinements= or rh= (filter links)
- Is a star rating link
- Has text indicating a filter/sponsored item
This is used to validate executor selections before clicking.
"""
if not snap or not getattr(snap, "elements", None) or element_id is None:
return False
for el in snap.elements:
try:
if getattr(el, "id", None) != element_id:
continue
role = (getattr(el, "role", "") or "").lower()
if role != "link":
return False
href = (getattr(el, "href", "") or "").lower()
text = (getattr(el, "text", "") or "").strip().lower()
# Explicit filter links are invalid
if "refinements=" in href or "rh=" in href:
return False
# Rating/star links are invalid
if "out of 5 stars" in text or "rating" in text:
return False
# Filter-like text patterns are invalid
filter_patterns = [
"free shipping", "apply", "filter", "prime", "sponsored ad -",
"see more", "show more", "a icon", "checkbox",
"traditional laptops", "customer ratings", "credit card",
"no annual fee", "cash back", "reward points"
]
if any(p in text for p in filter_patterns):
return False
# If href has product path, it's valid
if "/dp/" in href or "/gp/product/" in href:
return True
# If text looks like a product title, accept it even without /dp/ in href
# Product titles typically have brand + specs (e.g., "Lenovo ThinkPad E16 Gen 2 Business...")
# This handles JavaScript-navigated links where href might not contain the full path
if len(text) > 10:
# Check for product-like patterns (brand names, model numbers, specs)
product_indicators = [
"thinkpad", "lenovo", "laptop", "computer", "notebook",
"gen ", "business", "16gb", "32gb", "ssd", "ram", "ddr"
]
if any(ind in text for ind in product_indicators):
return True
return False
except Exception:
continue
return False
def find_add_to_cart_button_id(snap) -> int | None:
if not snap or not getattr(snap, "elements", None):
return None
candidates = []
for el in snap.elements:
try:
role = (getattr(el, "role", "") or "").lower()
if role != "button":
continue
text = (getattr(el, "text", "") or "").strip()
if not text:
continue
lowered = text.lower()
if "add to cart" not in lowered:
continue
if "buy now" in lowered:
continue
in_viewport = bool(getattr(el, "in_viewport", True))
doc_y = getattr(el, "doc_y", None)
importance = getattr(el, "importance", 0) or 0
candidates.append(
(not in_viewport, doc_y if doc_y is not None else 1e9, -importance, el.id)
)
except Exception:
continue
if not candidates:
return None
candidates.sort()
return candidates[0][3]
def build_planner_prompt(
task: str,
strict: bool = False,
schema_errors: str | None = None,
*,
start_url: str | None = None,
site_type: str | None = None,
auth_state: str | None = None,
planner_mode: str | None = None,
) -> tuple[str, str]:
system = (
"You are the PLANNER. Output a JSON plan for an Executor to run.\n"
"The Executor can only click/type using element IDs from snapshots.\n"
"Include explicit verification predicates per step.\n"
"Use stop_if_true for sign-in redirect after checkout.\n"
"If 'Add to Cart' is not found on a product page, include optional substeps to scroll down and retry.\n"
"Avoid brittle selectors like class=... for search-result clicks; prefer URL-based verifies.\n"
"If a soft-block page appears on Amazon with a 'Click to Continue' button, "
"include an optional substep to detect and click it.\n"
"Do NOT hardcode product URLs like /dp/product-url; use a CLICK step on the first product link.\n"
"Return ONLY a JSON object. No explanations, no <think> tags, no code fences."
)
strict_note = (
"\nReturn ONLY a JSON object. Do not include any other text.\n"
if strict
else ""
)
schema_note = (
f"\nSchema/smoothness issues from last attempt:\n{schema_errors}\n"
if schema_errors
else ""
)
mode = (planner_mode or os.getenv("PLANNER_MODE", "diet")).lower()
affordances = []
site = (site_type or "commerce").lower()
if site == "commerce":
affordances = [
"There is usually a search box in the header.",
"Search results appear as a repeated list of product links.",
"Product pages typically have an 'Add to Cart' button.",
"A cart/checkout button appears after adding to cart.",
]
elif site == "search":
affordances = [
"There is a search box near the top.",
"Results appear as a repeated list of links.",
]
payload = {
"task": task,
"done_when": ["url contains /dp/ after click", "checkout is reachable"],
"start_url": start_url or DEFAULT_PLAN_URL,
"site_type": site,
"auth_state": auth_state or "unknown",
"constraints": {
"max_steps": 8,
"no_vision": True,
"abort_on_captcha": True,
"allowed_actions": ["navigate", "click", "type", "press", "scroll", "wait", "assert"],
},
"ui_affordances": affordances if mode in {"diet_hints", "diet+hints"} else [],
"output_schema": {
"steps": [
{
"id": 1,
"goal": "string",
"action": "NAVIGATE|CLICK|TYPE_AND_SUBMIT|SCROLL",
"intent": "string",
"target": "natural language target (no selectors)",
"input": "optional",
"verify": ["1-2 predicate specs"],
}
]
},
}
payload_text = json.dumps(payload, indent=2)
user = f"""
Task payload (diet mode):
{payload_text}
{strict_note}
Planner contract:
- Use ONLY the fields in the schema example below.
- Max required steps: 8 (optional_substeps do not count).
- One action per step. Do not repeat similar CLICK intents back-to-back.
- For search flows, the core template is mandatory:
NAVIGATE → CLICK(search_box) → TYPE_AND_SUBMIT(query) → CLICK(first_product_link) → CLICK(add_to_cart) → NAVIGATE(cart) → CLICK(proceed_to_checkout)
- Every required step must include >=1 verify predicate.
- Avoid fragile verify-only checks (e.g., exists("role=textbox")) unless paired with a
more specific predicate.
- For first_product_link, use verify url_contains("/dp/") instead of class selectors.
- Allowed actions: NAVIGATE, CLICK, TYPE_AND_SUBMIT, SCROLL.
Predicates allowed: url_contains, url_matches, exists, not_exists, element_count, any_of, all_of.
Note: url_contains expects a single string; use any_of for multiple options.
Step archetypes (choose from these only):
1) NAVIGATE(target=url, verify=[url_contains|url_matches])
2) CLICK(intent=..., verify=[exists/not_exists/url_contains/any_of/all_of])
3) TYPE_AND_SUBMIT(input=..., verify=[url_contains|url_matches])
4) SCROLL(target=down|up, verify=[optional])
Output JSON with fields:
- task: string
- notes: list of strings
- steps: list of steps (id, goal, action, target/intent/input, verify, required, stop_if_true?, optional_substeps?)
Format example (match keys exactly):
{{
"task": "Amazon shopping cart checkout flow",
"notes": ["Executor uses stealth typing", "Stop on sign-in redirect"],
"steps": [
{{
"id": 1,
"goal": "Navigate to Amazon homepage",
"action": "NAVIGATE",
"target": "https://www.amazon.com",
"verify": [{{ "predicate": "url_contains", "args": ["amazon."] }}],
"required": true
}},
{{
"id": 2,
"goal": "Focus the search box",
"action": "CLICK",
"intent": "search_box",
"verify": [{{ "predicate": "any_of", "args": [
{{ "predicate": "exists", "args": ["role=searchbox"] }},
{{ "predicate": "exists", "args": ["role=textbox"] }},
{{ "predicate": "exists", "args": ["role=combobox"] }}
]}}],
"required": true
}},
{{
"id": 3,
"goal": "Type search query and submit",
"action": "TYPE_AND_SUBMIT",
"input": "thinkpad",
"verify": [{{ "predicate": "url_contains", "args": ["k=thinkpad"] }}],
"required": true
}},
{{
"id": 4,
"goal": "Click the first product in search results, go to product details page",
"action": "CLICK",
"intent": "first_product_link",
"verify": [{{ "predicate": "url_contains", "args": ["/dp/"] }}],
"required": true
}},
{{
"id": 5,
"goal": "Click the 'Add to Cart' button",
"action": "CLICK",
"intent": "add_to_cart",
"verify": [{{ "predicate": "any_of", "args": [
{{ "predicate": "exists", "args": ["text~'Added to Cart'"] }},
{{ "predicate": "url_contains", "args": ["cart"] }}
]}}],
"required": true,
"optional_substeps": [
{{
"id": 1,
"goal": "Scroll down if the Add to Cart button is not visible",
"action": "SCROLL",
"target": "down",
"required": false
}},
{{
"id": 2,
"goal": "Retry clicking Add to Cart after scrolling",
"action": "CLICK",
"intent": "add_to_cart_retry",
"verify": [{{ "predicate": "any_of", "args": [
{{ "predicate": "exists", "args": ["text~'Added to Cart'"] }},
{{ "predicate": "url_contains", "args": ["cart"] }}
]}}],
"required": false
}},
{{
"id": 3,
"goal": "If 'Add to Your Order' drawer appears, click 'No thanks'",
"action": "CLICK",
"intent": "drawer_no_thanks",
"verify": [{{ "predicate": "not_exists", "args": ["text~'Add to Your Order'"] }}],
"required": false
}}
]
}}
,
{{
"id": 6,
"goal": "Navigate to cart page",
"action": "NAVIGATE",
"target": "https://www.amazon.com/gp/cart/view.html",
"verify": [{{ "predicate": "any_of", "args": [
{{ "predicate": "url_contains", "args": ["cart"] }},
{{ "predicate": "exists", "args": ["text~'Subtotal'"] }}
]}}],
"required": true
}},
{{
"id": 7,
"goal": "Proceed to checkout",
"action": "CLICK",
"intent": "proceed_to_checkout",
"verify": [{{ "predicate": "any_of", "args": [
{{ "predicate": "url_contains", "args": ["signin"] }},
{{ "predicate": "url_contains", "args": ["/ap/"] }},
{{ "predicate": "url_contains", "args": ["checkout"] }}
]}}],
"required": true,
"stop_if_true": true
}}
]
}}
Unsmooth example (INVALID):
{{"steps":[
{{"id":1,"action":"CLICK","intent":"search_box","verify":[{{"predicate":"any_of","args":[{{"predicate":"exists","args":["role=searchbox"]}},{{"predicate":"exists","args":["role=textbox"]}}]}}],"required":true}},
{{"id":2,"action":"CLICK","intent":"search_box","verify":[{{"predicate":"any_of","args":[{{"predicate":"exists","args":["role=searchbox"]}},{{"predicate":"exists","args":["role=textbox"]}}]}}],"required":true}}
]}}
Reason: redundant CLICK intents back-to-back.
Smooth example (VALID):
{{"steps":[
{{"id":1,"action":"CLICK","intent":"search_box","verify":[{{"predicate":"any_of","args":[{{"predicate":"exists","args":["role=searchbox"]}},{{"predicate":"exists","args":["role=textbox"]}}]}}],"required":true}},
{{"id":2,"action":"TYPE_AND_SUBMIT","input":"thinkpad","verify":[{{"predicate":"url_contains","args":["k=thinkpad"]}}],"required":true}}
]}}
{schema_note}
"""
return system, user
def extract_plan_with_retry(
planner: LocalHFModel, task: str, max_attempts: int = 2
) -> tuple[dict[str, Any], str]:
last_output = ""
last_errors = ""
planner_name = str(getattr(planner, "model_name", ""))
planner_requires_strict = (
os.getenv("PLANNER_STRICT", "1").lower() in {"1", "true", "yes"}
or "deepseek-r1" in planner_name.lower()
)
for attempt in range(1, max_attempts + 1):
max_tokens = 1536 if attempt == 1 else 2048
sys_prompt, user_prompt = build_planner_prompt(
task,
strict=(planner_requires_strict or attempt > 1),
schema_errors=last_errors or None,
start_url=DEFAULT_PLAN_URL,
site_type="commerce",
auth_state="unknown",
planner_mode=os.getenv("PLANNER_MODE", "diet"),
)
resp = planner.generate(
sys_prompt, user_prompt, temperature=0.0, max_new_tokens=max_tokens
)
last_output = resp.content
try:
plan = extract_json(resp.content)
plan = normalize_plan(plan)
errors = validate_plan(plan)
smoothness = validate_plan_smoothness(plan, task)
if errors or smoothness:
combined = []
if errors:
combined.extend(errors)