File size: 9,966 Bytes
6e721ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Browser agent core: observe -> act -> verify -> recover.

The agent grounds task targets semantically (role + text/label/name) in a
fresh DOM snapshot before every step. When an action or a verification
fails it can *recover* (recovery ON):

  * re-ground the target with fallback strategies (structural match:
    the submit control of the named form/container, partial-text match),
  * dismiss a blocking overlay via its dismiss control,
  * retry within a small budget (MAX_RETRIES).

With recovery OFF none of that happens: the first failure ends the task.
That ablation is what the eval measures. Every failure and recovery is
written to a JSONL run log.
"""
from __future__ import annotations

import json
import time
from dataclasses import dataclass, field

from .snapshot import Snapshot

ACTION_TIMEOUT_MS = 3000
VERIFY_TIMEOUT_S = 2.0
MAX_RETRIES = 2

DISMISS_TEXTS = {"×", "x", "close", "accept", "accept all", "dismiss",
                 "got it", "ok", "no thanks"}


@dataclass
class Target:
    """Semantic description of the element a step acts on."""
    role: str                       # button | link | textbox | combobox | checkbox | radio
    text: str = ""                  # visible text (buttons, links)
    label: str = ""                 # <label> text (form fields)
    name: str = ""                  # name attribute
    form: str = ""                  # enclosing form/container id (fallback hint)
    kind: str = ""                  # e.g. "submit" (structural fallback hint)


@dataclass
class Step:
    action: str                     # click | fill | select | check
    target: Target
    value: str = ""
    verify: object = None           # callable(page) -> bool, or None


@dataclass
class Task:
    name: str
    fixture: str                    # file name under fixtures/
    steps: list
    adversarial: bool = False
    description: str = ""


@dataclass
class TaskResult:
    task: str
    success: bool = False
    steps_completed: int = 0
    attempts: int = 0
    recoveries: int = 0
    error: str = ""


class RunLog:
    def __init__(self, path: str):
        self.path = path
        self._fh = open(path, "a", encoding="utf-8")

    def write(self, task: str, event: str, **kw) -> None:
        rec = {"ts": round(time.time(), 3), "task": task, "event": event}
        rec.update(kw)
        self._fh.write(json.dumps(rec) + "\n")
        self._fh.flush()

    def close(self) -> None:
        self._fh.close()


def _role_matches(rec: dict, role: str) -> bool:
    tag, typ = rec["tag"], rec["type"]
    if role == "button":
        return tag == "button" or rec["role"] == "button" or \
            (tag == "input" and typ in ("submit", "button"))
    if role == "link":
        return tag == "a"
    if role == "textbox":
        return tag == "textarea" or (tag == "input" and typ in
                                     ("", "text", "password", "email", "search"))
    if role == "combobox":
        return tag == "select"
    if role == "checkbox":
        return tag == "input" and typ == "checkbox"
    if role == "radio":
        return tag == "input" and typ == "radio"
    return False


class Agent:
    def __init__(self, page, recovery: bool = True, log: RunLog | None = None):
        self.page = page
        self.recovery = recovery
        self.log = log

    # -- observation / grounding -------------------------------------------
    def _find_exact(self, snap: Snapshot, t: Target) -> dict | None:
        """Exact semantic match: text/label/name must match as specified."""
        best = None
        for rec in snap.elements:
            if not rec["visible"] or rec["disabled"]:
                continue
            if not _role_matches(rec, t.role):
                continue
            score = 1
            if t.text:
                if rec["text"] == t.text:
                    score = 100
                elif t.text.lower() in rec["text"].lower():
                    score = 50
                else:
                    continue
            if t.label:
                if rec["label"] == t.label:
                    score = max(score, 100)
                else:
                    continue
            if t.name:
                if rec["name"] == t.name:
                    score = max(score, 100)
                else:
                    continue
            if best is None or score > best[0]:
                best = (score, rec)
        return best[1] if best else None

    def _find_fallback(self, snap: Snapshot, t: Target) -> dict | None:
        """Re-grounding strategies used only in recovery: the target may
        have been renamed or moved, so fall back to structure."""
        cands = [r for r in snap.elements
                 if r["visible"] and not r["disabled"] and _role_matches(r, t.role)]
        if t.form:
            in_scope = [r for r in cands
                        if r["form"] == t.form or t.form in r.get("ancestors", [])]
            if t.kind == "submit":
                subs = [r for r in in_scope
                        if r["type"] == "submit" or r["tag"] == "button"]
                if len(subs) == 1:
                    return subs[0]
            if len(in_scope) == 1:
                return in_scope[0]
            if in_scope:
                cands = in_scope
        # last resort: a single visible candidate of that role on the page
        if len(cands) == 1:
            return cands[0]
        return None

    # -- action -------------------------------------------------------------
    def _act(self, rec: dict, step: Step) -> None:
        recipe = rec["recipe"]
        if not recipe:
            raise RuntimeError(f"no locator recipe for {rec['ref']}")
        loc = self.page.locator(recipe).first
        if step.action == "click":
            loc.click(timeout=ACTION_TIMEOUT_MS)
        elif step.action == "fill":
            loc.fill(step.value, timeout=ACTION_TIMEOUT_MS)
        elif step.action == "select":
            loc.select_option(step.value, timeout=ACTION_TIMEOUT_MS)
        elif step.action == "check":
            loc.check(timeout=ACTION_TIMEOUT_MS)
        else:
            raise ValueError(f"unknown action {step.action}")

    def _dismiss_overlay(self, task_name: str) -> bool:
        snap = Snapshot.take(self.page)
        for rec in snap.elements:
            if not rec["visible"] or rec["disabled"] or not rec["recipe"]:
                continue
            if _role_matches(rec, "button") and \
                    rec["text"].strip().lower() in DISMISS_TEXTS:
                try:
                    self.page.locator(rec["recipe"]).first.click(timeout=1500)
                    if self.log:
                        self.log.write(task_name, "recovery",
                                       kind="dismiss_overlay",
                                       control=rec["text"])
                    return True
                except Exception:
                    pass
        return False

    def _verify(self, step: Step) -> bool:
        if step.verify is None:
            return True
        deadline = time.time() + VERIFY_TIMEOUT_S
        while True:
            try:
                if step.verify(self.page):
                    return True
            except Exception:
                pass
            if time.time() >= deadline:
                return False
            time.sleep(0.1)

    # -- the loop -------------------------------------------------------------
    def run_task(self, task: Task) -> TaskResult:
        res = TaskResult(task=task.name)
        for idx, step in enumerate(task.steps, start=1):
            ok = self._run_step(task, idx, step, res)
            if not ok:
                res.error = res.error or f"step {idx} failed"
                return res
            res.steps_completed += 1
        res.success = True
        if self.log:
            self.log.write(task.name, "task_success",
                           attempts=res.attempts, recoveries=res.recoveries)
        return res

    def _run_step(self, task: Task, idx: int, step: Step,
                  res: TaskResult) -> bool:
        retries_left = MAX_RETRIES if self.recovery else 0
        reground = False
        while True:
            res.attempts += 1
            snap = Snapshot.take(self.page)
            if self.log:
                self.log.write(task.name, "observe", step=idx,
                               elements=len(snap))
            rec = self._find_fallback(snap, step.target) if reground \
                else self._find_exact(snap, step.target)
            failure = None
            failure_full = ""
            if rec is None:
                failure = "target_not_found"
            else:
                try:
                    self._act(rec, step)
                except Exception as exc:  # timeout, intercept, stale, ...
                    failure_full = str(exc)
                    failure = f"action_error: {failure_full.splitlines()[0][:160]}"
                else:
                    if self._verify(step):
                        if self.log:
                            self.log.write(task.name, "step_ok", step=idx,
                                           ref=rec["ref"])
                        return True
                    failure = "verify_failed"
            if self.log:
                self.log.write(task.name, "failure", step=idx, reason=failure,
                               recovery=self.recovery)
            if not self.recovery or retries_left <= 0:
                res.error = f"step {idx}: {failure}"
                return False
            # --- recovery ---
            retries_left -= 1
            res.recoveries += 1
            if "intercepts pointer events" in failure_full:
                self._dismiss_overlay(task.name)
            reground = True
            if self.log:
                self.log.write(task.name, "recovery", step=idx,
                               kind="reground_retry")