-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsafe_runner.py
More file actions
790 lines (659 loc) Β· 30.9 KB
/
Copy pathsafe_runner.py
File metadata and controls
790 lines (659 loc) Β· 30.9 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
"""
Deterministic baseline agent runner for Forum-only WebArena tasks.
No LLM. Heuristic policy + Verifier + RiskScorer with Tiered Autonomy Gate.
"""
import json
import os
import re
import sys
import time
import traceback
from collections import deque
from dataclasses import dataclass, field
# ββ Environment variables required by browser_env.env_config ββ
FORUM_URL = "http://localhost:9999"
os.environ["REDDIT"] = FORUM_URL
os.environ["SHOPPING"] = FORUM_URL
os.environ["SHOPPING_ADMIN"] = FORUM_URL
os.environ["GITLAB"] = FORUM_URL
os.environ["WIKIPEDIA"] = FORUM_URL
os.environ["MAP"] = FORUM_URL
os.environ["HOMEPAGE"] = FORUM_URL
# ββ Imports (after env vars are set) ββ
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "third_party", "webarena"))
from browser_env import ScriptBrowserEnv
from browser_env.actions import (
ActionTypes,
create_click_action,
create_goto_url_action,
create_none_action,
create_scroll_action,
create_type_action,
create_stop_action,
)
# ββ Constants ββ
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
WEBARENA_ROOT = os.path.join(PROJECT_ROOT, "third_party", "webarena")
CONFIG_FILE = os.path.join(WEBARENA_ROOT, "config_files", "test.raw.json")
MAX_STEPS = 15
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Verifier β deterministic pre-step validation layer
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@dataclass
class VerifyResult:
"""Result of action verification."""
valid: bool
reason: str
class Verifier:
"""Deterministic verifier layer that validates actions before execution.
Checks:
A) Element Validation β element_id exists, role supports action type
B) Repetition Detection β blocks if same (URL, element_name) > 2 in last 10
C) State Change Detection β detects no-ops post-execution
D) Action Confidence Flag β returns {valid, reason}
"""
CLICKABLE_ROLES = {
"link", "button", "menuitem", "tab", "checkbox", "radio",
"switch", "option", "menuitemcheckbox", "menuitemradio",
"treeitem", "combobox", "searchbox", "textbox",
}
TYPEABLE_ROLES = {
"textbox", "searchbox", "combobox", "spinbutton", "textarea",
}
NON_CLICKABLE_ROLES = {
"RootWebArea", "main", "complementary", "contentinfo",
"navigation", "banner", "sectionheader", "heading",
"StaticText", "InlineTextBox", "generic", "paragraph",
"list", "listitem", "img", "image", "group", "separator",
"region", "status", "alert", "log", "marquee", "timer",
"tooltip", "document", "application", "article", "figure",
"math", "note", "presentation", "none",
}
MAX_REPEAT = 2
HISTORY_SIZE = 10
def __init__(self):
self.history: deque = deque(maxlen=self.HISTORY_SIZE)
self.prev_url: str = ""
self.prev_element_name: str = ""
self.consecutive_same_click: int = 0
self.total_proposed: int = 0
self.total_blocked: int = 0
self.total_noops: int = 0
def validate(self, action, elements, current_url):
"""Validate an action BEFORE env.step()."""
self.total_proposed += 1
action_type = action["action_type"]
element_id = action.get("element_id", "")
# (A) Element Validation
if action_type in (ActionTypes.CLICK, ActionTypes.TYPE, ActionTypes.HOVER):
if element_id:
elem = self._find_elem_by_id(elements, element_id)
if elem is None:
self.total_blocked += 1
return VerifyResult(
valid=False,
reason=f"Element [{element_id}] not found in current a11y tree"
)
role_lower = elem["role"].lower()
if action_type == ActionTypes.CLICK:
if role_lower in {r.lower() for r in self.NON_CLICKABLE_ROLES}:
self.total_blocked += 1
return VerifyResult(
valid=False,
reason=f"CLICK blocked on non-clickable role '{elem['role']}' "
f"[{element_id}] '{elem['name']}'"
)
elif action_type == ActionTypes.TYPE:
if role_lower not in {r.lower() for r in self.TYPEABLE_ROLES}:
self.total_blocked += 1
return VerifyResult(
valid=False,
reason=f"TYPE blocked on non-typeable role '{elem['role']}' "
f"[{element_id}] '{elem['name']}'"
)
# (B) Repetition Detection β by (URL, element_name)
if element_id:
elem = self._find_elem_by_id(elements, element_id)
elem_name = elem["name"] if elem else element_id
pair = (current_url, elem_name)
repeat_count = sum(1 for h in self.history if h == pair)
if repeat_count >= self.MAX_REPEAT:
self.total_blocked += 1
return VerifyResult(
valid=False,
reason=f"Repetition limit: ({current_url}, '{elem_name}') "
f"appeared {repeat_count} times in last {self.HISTORY_SIZE} actions"
)
return VerifyResult(valid=True, reason="All checks passed")
def record_action(self, action, current_url, elements):
"""Record an action after validation, before execution."""
element_id = action.get("element_id", "")
if element_id:
elem = self._find_elem_by_id(elements, element_id)
elem_name = elem["name"] if elem else element_id
self.history.append((current_url, elem_name))
def detect_state_change(self, prev_url, new_url, action, elements):
"""(C) State Change Detection β call AFTER env.step()."""
element_id = action.get("element_id", "")
elem = self._find_elem_by_id(elements, element_id) if element_id else None
elem_name = elem["name"] if elem else element_id
if prev_url == new_url and elem_name:
if elem_name == self.prev_element_name:
self.consecutive_same_click += 1
if self.consecutive_same_click >= 2:
self.total_noops += 1
result = (
f"NO-OP detected: URL unchanged ({new_url}), "
f"element '{elem_name}' clicked {self.consecutive_same_click} "
f"times consecutively"
)
self.prev_element_name = elem_name
self.prev_url = new_url
return result
else:
self.consecutive_same_click = 0
else:
self.consecutive_same_click = 0
self.prev_element_name = elem_name
self.prev_url = new_url
return None
def get_stats(self):
return {
"total_proposed": self.total_proposed,
"total_blocked": self.total_blocked,
"total_noops": self.total_noops,
"history_len": len(self.history),
}
@staticmethod
def _find_elem_by_id(elements, element_id):
for elem in elements:
if elem["id"] == element_id:
return elem
return None
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# RiskScorer β risk-level classification for actions
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class RiskScorer:
"""Deterministic risk scorer that classifies actions as LOW/MEDIUM/HIGH.
Rules:
HIGH: element text contains destructive/auth keywords
(submit, delete, remove, confirm, log out, sign up, register)
OR action is TYPE into a login/registration form field
MEDIUM: element text contains mutating keywords
(search, edit, create, new)
OR action is TYPE into a generic input
LOW: navigation links (forums, wiki, home, comments)
and purely browsing actions (scroll)
"""
# Keywords that indicate HIGH risk β destructive or auth-mutating
HIGH_KEYWORDS = {
"submit", "delete", "remove", "confirm",
"log out", "logout", "sign up", "register",
}
# Keywords that indicate MEDIUM risk β mutating but non-destructive
MEDIUM_KEYWORDS = {
"search", "edit", "create", "new", "filter", "sort",
}
# Keywords that indicate LOW risk β pure navigation/browsing
LOW_KEYWORDS = {
"forums", "wiki", "home", "comments", "submissions",
"all pages", "recent changes", "alphabetical", "tags",
}
# URL patterns for login/registration pages
AUTH_URL_PATTERNS = {"login", "registration", "register", "signup", "sign-up"}
def __init__(self):
# Counters for deterministic gating decisions
self.high_encounter_count: int = 0
self.medium_encounter_count: int = 0
# Stats
self.total_scored: int = 0
self.high_risk_actions: int = 0
self.high_risk_blocked: int = 0
self.medium_risk_actions: int = 0
self.medium_risk_blocked: int = 0
self.low_risk_actions: int = 0
def score(self, action, element_text, current_url):
"""Score an action's risk level.
Args:
action: WebArena action dict
element_text: the name/text of the target element
current_url: current page URL
Returns:
risk_level: "LOW", "MEDIUM", or "HIGH"
"""
self.total_scored += 1
action_type = action["action_type"]
text_lower = element_text.lower()
url_lower = current_url.lower()
# ββ HIGH risk checks ββ
# Check if element text contains HIGH-risk keywords
for keyword in self.HIGH_KEYWORDS:
if keyword in text_lower:
self.high_risk_actions += 1
return "HIGH"
# TYPE action into a form on login/registration page = HIGH
if action_type == ActionTypes.TYPE:
for pattern in self.AUTH_URL_PATTERNS:
if pattern in url_lower:
self.high_risk_actions += 1
return "HIGH"
# ββ MEDIUM risk checks ββ
# Check if element text contains MEDIUM-risk keywords
for keyword in self.MEDIUM_KEYWORDS:
if keyword in text_lower:
self.medium_risk_actions += 1
return "MEDIUM"
# TYPE action on any generic input (not on auth page) = MEDIUM
if action_type == ActionTypes.TYPE:
self.medium_risk_actions += 1
return "MEDIUM"
# ββ LOW risk (default) ββ
# Navigation links, browsing, scrolling = LOW
self.low_risk_actions += 1
return "LOW"
def gate(self, risk_level):
"""Tiered autonomy gate: decide whether to allow the action.
Uses deterministic counters to simulate approval rates:
HIGH: allow 50% β allow on even encounters (1st, 3rd, 5th...)
block on odd encounters (2nd, 4th, 6th...)
MEDIUM: allow 80% β block every 5th encounter
LOW: always allow
Returns:
(allowed: bool, reason: str)
"""
if risk_level == "HIGH":
self.high_encounter_count += 1
if self.high_encounter_count % 2 == 0:
# Block on even encounters (2nd, 4th, 6th...)
self.high_risk_blocked += 1
return False, (
f"HIGH risk gated β simulated denial "
f"(encounter #{self.high_encounter_count}, policy: allow 50%)"
)
else:
return True, (
f"HIGH risk allowed β simulated approval "
f"(encounter #{self.high_encounter_count}, policy: allow 50%)"
)
elif risk_level == "MEDIUM":
self.medium_encounter_count += 1
if self.medium_encounter_count % 5 == 0:
# Block every 5th encounter
self.medium_risk_blocked += 1
return False, (
f"MEDIUM risk gated β simulated denial "
f"(encounter #{self.medium_encounter_count}, policy: allow 80%)"
)
else:
return True, (
f"MEDIUM risk allowed β simulated approval "
f"(encounter #{self.medium_encounter_count}, policy: allow 80%)"
)
else: # LOW
return True, "LOW risk β always allowed"
def get_stats(self):
return {
"total_scored": self.total_scored,
"high_risk_actions": self.high_risk_actions,
"high_risk_blocked": self.high_risk_blocked,
"medium_risk_actions": self.medium_risk_actions,
"medium_risk_blocked": self.medium_risk_blocked,
"low_risk_actions": self.low_risk_actions,
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Task Selector
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def select_forum_task():
"""Select a single forum/reddit task from test.raw.json."""
with open(CONFIG_FILE) as f:
all_tasks = json.load(f)
reddit_tasks = [t for t in all_tasks if "reddit" in t.get("sites", [])]
if not reddit_tasks:
raise RuntimeError("No reddit/forum tasks found in config")
forum_nav = [t for t in reddit_tasks if "forum" in t["intent"].lower()]
if forum_nav:
task = forum_nav[0]
else:
task = reddit_tasks[0]
task["start_url"] = FORUM_URL
task["storage_state"] = None
task["require_login"] = False
return task
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Accessibility Tree Parser
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def parse_a11y_tree(tree_text):
"""Parse accessibility tree text into structured elements."""
elements = []
for line in tree_text.split("\n"):
stripped = line.strip()
if not stripped:
continue
m = re.match(r".*?\[(\S+)\]\s+(\S+)\s+(.*)", stripped)
if m:
elem_id = m.group(1)
role = m.group(2)
rest = m.group(3).strip()
name_match = re.match(r"['\"](.+?)['\"]", rest)
name = name_match.group(1) if name_match else rest
elements.append({
"id": elem_id,
"role": role,
"name": name,
"line": stripped,
})
return elements
def find_element(elements, text_match=None, role_match=None):
"""Find first element matching criteria (case-insensitive)."""
for elem in elements:
if role_match and role_match.lower() not in elem["role"].lower():
continue
if text_match and text_match.lower() not in elem["name"].lower():
continue
return elem
return None
def find_clickable_elements(elements):
"""Return elements that are likely clickable (links, buttons)."""
clickable_roles = {"link", "button", "menuitem", "tab", "searchbox", "textbox"}
return [e for e in elements if e["role"].lower() in clickable_roles]
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Heuristic Policy
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _is_clickable_element(elem):
clickable_roles = {"link", "button", "menuitem", "tab", "searchbox", "textbox"}
return elem["role"].lower() in clickable_roles
def _word_match(word, text):
return bool(re.search(r'\b' + re.escape(word) + r'\b', text, re.IGNORECASE))
def choose_action(instruction, elements, step_num, skip_names=None):
"""Deterministic heuristic policy.
Navigation cycle designed to hit LOW, MEDIUM, and HIGH risk
elements so the RiskScorer + Gate can demonstrate all tiers.
Cycle (7 targets, repeats every 7 steps):
0: Forums β LOW
1: Log in link β HIGH ("Log in" matches high-risk keywords?
No β "Log in" β "log out". It's actually LOW.
But on the login PAGE, the "Log in" BUTTON
is HIGH because "submit" is implied.)
2: Wiki β LOW
3: Sign up link β HIGH ("sign up" matches HIGH keywords)
4: Comments β LOW
5: Filter button β MEDIUM ("filter" matches MEDIUM keywords)
6: Sort button β MEDIUM ("sort" matches MEDIUM keywords)
"""
if skip_names is None:
skip_names = set()
inst_lower = instruction.lower()
clickable = [
e for e in elements
if _is_clickable_element(e) and e["name"] not in skip_names
]
# Navigation cycle β 7 targets to exercise all risk tiers
nav_targets = [
"Forums", # step 0, 7, 14 β LOW
"Log in", # step 1, 8 β HIGH (keyword match)
"Wiki", # step 2, 9 β LOW
"Sign up", # step 3, 10 β HIGH (keyword match)
"Comments", # step 4, 11 β LOW
"Filter on", # step 5, 12 β MEDIUM ("filter")
"Sort by", # step 6, 13 β MEDIUM ("sort")
]
strategy_idx = step_num % len(nav_targets)
target_text = nav_targets[strategy_idx]
# Try to find the navigation target among clickable elements
target = None
for elem in clickable:
if target_text.lower() in elem["name"].lower():
target = elem
break
# ββ Fallback: keyword-based rules ββ
if not target:
if "login" in inst_lower or "log in" in inst_lower:
for elem in clickable:
if "log in" in elem["name"].lower() or "login" in elem["name"].lower():
target = elem
break
if not target and "search" in inst_lower:
for elem in elements:
if (elem["role"].lower() in ("searchbox", "textbox")
and "search" in elem["name"].lower()
and elem["name"] not in skip_names):
search_term = "test search"
action = create_type_action(
text=search_term,
element_id=elem["id"],
)
return action, f"type '{search_term}' into [{elem['id']}] '{elem['name']}'"
if not target and (_word_match("submit", inst_lower) or _word_match("post", inst_lower)):
for elem in clickable:
if _word_match("submit", elem["name"]) or _word_match("post", elem["name"]):
target = elem
break
# ββ Final fallback ββ
if not target:
for elem in clickable:
name = elem["name"].strip().strip("'\"")
if name and name not in ("", "''", '""'):
target = elem
break
if not target and clickable:
target = clickable[0]
if not target:
return create_scroll_action("down"), "scroll down (no valid clickable elements)"
return _make_click(target), f"click [{target['id']}] {target['role']} '{target['name']}'"
def _make_click(element):
return create_click_action(element_id=element["id"])
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Main Runner
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def main():
print("=" * 70)
print(" SAFE RUNNER β Agent + Verifier + RiskScorer Gate")
print("=" * 70)
# ββ Select task ββ
task = select_forum_task()
instruction = task["intent"]
start_url = task["start_url"]
print(f"\nπ Task ID: {task['task_id']}")
print(f"π Instruction: {instruction}")
print(f"π Start URL: {start_url}")
print(f"π Login needed: {task.get('require_login', False)}")
print()
# ββ Temp config ββ
config_path = os.path.join(PROJECT_ROOT, "_temp_task_config.json")
config_data = {
"start_url": start_url,
"storage_state": task.get("storage_state"),
"geolocation": task.get("geolocation"),
}
config_data = {k: v for k, v in config_data.items() if v is not None}
with open(config_path, "w") as f:
json.dump(config_data, f)
# ββ Create environment + verifier + risk scorer ββ
print("π Creating ScriptBrowserEnv...")
env = ScriptBrowserEnv(
headless=False,
observation_type="accessibility_tree",
current_viewport_only=True,
viewport_size={"width": 1280, "height": 720},
sleep_after_execution=0.5,
)
verifier = Verifier()
scorer = RiskScorer()
try:
# ββ Reset environment ββ
print("π Resetting environment (opening browser)...")
obs, info = env.reset(options={"config_file": config_path})
current_url = info["page"].url
verifier.prev_url = current_url
print(f" Page loaded: {current_url}")
# ββ Counters ββ
total_reward = 0.0
done = False
total_actions_proposed = 0
total_actions_executed = 0
for step in range(MAX_STEPS):
print(f"\n{'β' * 60}")
print(f" STEP {step + 1}/{MAX_STEPS}")
print(f"{'β' * 60}")
# Get current observation
tree_text = obs.get("text", "")
print(f"\nπ³ Accessibility tree (first 800 chars):")
print(tree_text[:800])
if len(tree_text) > 800:
print(f" ... ({len(tree_text)} total chars)")
# Parse tree
elements = parse_a11y_tree(tree_text)
clickable_count = len(find_clickable_elements(elements))
print(f"\n Parsed {len(elements)} elements, {clickable_count} clickable")
current_url = info["page"].url
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
# Action Selection β Verify β Risk Score β Gate
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
skip_names = set()
max_retries = 8 # more retries since we now have 2 blocking layers
action = None
description = ""
blocked_log = []
action_accepted = False
for attempt in range(max_retries):
total_actions_proposed += 1
# ββ 1. Choose action ββ
try:
action, description = choose_action(
instruction, elements, step, skip_names
)
except Exception as e:
print(f" β οΈ Action selection error: {e}")
action = create_none_action()
description = "none (error fallback)"
action_accepted = True
break
# Resolve element text for risk scoring
element_id = action.get("element_id", "")
elem = Verifier._find_elem_by_id(elements, element_id) if element_id else None
element_text = elem["name"] if elem else ""
print(f"\n π― Proposed: {description}")
# ββ 2. Verifier check ββ
v_result = verifier.validate(action, elements, current_url)
if not v_result.valid:
blocked_log.append((
description, f"Verifier: {v_result.reason}"
))
print(f" π« BLOCKED (Verifier): {v_result.reason}")
if element_id and elem:
skip_names.add(elem["name"])
if attempt == max_retries - 1:
action = create_scroll_action("down")
description = "scroll down (all alternatives blocked)"
action_accepted = True
print(f" π Fallback: {description}")
continue
print(f" β
Verifier: PASS")
# ββ 3. Risk scoring ββ
risk_level = scorer.score(action, element_text, current_url)
# ββ 4. Tiered autonomy gate ββ
gate_allowed, gate_reason = scorer.gate(risk_level)
if gate_allowed:
print(f" π‘οΈ Risk: {risk_level} β {gate_reason}")
action_accepted = True
break
else:
# GATED β blocked by risk gate
blocked_log.append((
description, f"Gate ({risk_level}): {gate_reason}"
))
print(f" π¨ GATED: [{risk_level}] {element_text}")
print(f" Reason: {gate_reason}")
if element_id and elem:
skip_names.add(elem["name"])
if attempt == max_retries - 1:
action = create_scroll_action("down")
description = "scroll down (all alternatives gated)"
action_accepted = True
print(f" π Fallback: {description}")
continue
# Log blocked/gated summary
if blocked_log:
print(f"\n π Blocked/Gated {len(blocked_log)} action(s) before proceeding:")
for i, (desc, reason) in enumerate(blocked_log):
print(f" {i+1}. {desc} β {reason}")
# ββ Record + Execute ββ
verifier.record_action(action, current_url, elements)
total_actions_executed += 1
prev_url = current_url
try:
obs, reward, terminated, truncated, info = env.step(action)
done = terminated or truncated
total_reward += reward
except Exception as e:
print(f" β Step execution error: {e}")
traceback.print_exc()
try:
obs = env._get_obs()
reward = 0.0
done = False
info = {"page": type("P", (), {"url": prev_url})()}
except Exception:
print(" π Could not recover. Breaking loop.")
break
continue
new_url = info["page"].url
print(f" π Reward: {reward}")
print(f" π Done: {done}")
print(f" π URL: {new_url}")
if info.get("fail_error"):
print(f" β οΈ Error: {info['fail_error']}")
# (C) State Change Detection
noop_msg = verifier.detect_state_change(prev_url, new_url, action, elements)
if noop_msg:
print(f" β οΈ {noop_msg}")
if done:
print(f"\nβ
Task marked as done after {step + 1} steps!")
break
time.sleep(0.3)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Summary
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
v_stats = verifier.get_stats()
r_stats = scorer.get_stats()
print(f"\n{'β' * 70}")
print(f" RUN SUMMARY")
print(f"{'β' * 70}")
print(f" Steps executed: {min(step + 1, MAX_STEPS)}")
print(f" Total reward: {total_reward}")
print(f" Task completed: {done}")
print(f" Final URL: {info['page'].url}")
print(f" Actions proposed: {total_actions_proposed}")
print(f" Actions executed: {total_actions_executed}")
print(f"{'β' * 70}")
print(f" VERIFIER STATS")
print(f"{'β' * 70}")
print(f" Verifier proposed: {v_stats['total_proposed']}")
print(f" Verifier blocked: {v_stats['total_blocked']}")
print(f" No-ops detected: {v_stats['total_noops']}")
print(f" History size: {v_stats['history_len']}")
print(f"{'β' * 70}")
print(f" RISK SCORER STATS")
print(f"{'β' * 70}")
print(f" Total scored: {r_stats['total_scored']}")
print(f" HIGH risk actions: {r_stats['high_risk_actions']}")
print(f" HIGH risk blocked: {r_stats['high_risk_blocked']}")
print(f" MEDIUM risk actions: {r_stats['medium_risk_actions']}")
print(f" MEDIUM risk blocked: {r_stats['medium_risk_blocked']}")
print(f" LOW risk actions: {r_stats['low_risk_actions']}")
print(f"{'β' * 70}")
except Exception as e:
print(f"\nπ₯ Fatal error: {e}")
traceback.print_exc()
finally:
print("\nπ§Ή Closing browser...")
try:
env.close()
print(" Browser closed cleanly.")
except Exception as e:
print(f" Warning during close: {e}")
if os.path.exists(config_path):
os.remove(config_path)
print("\nβ
safe_runner.py finished.\n")
if __name__ == "__main__":
main()