e2e-web 0.1.0__py3-none-any.whl

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.
e2e_web/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ """Synchronous, Web-only agent SDK for pytest, unittest and other hosts."""
2
+
3
+ from .browser import BrowserEngine
4
+ from .cache import FileCacheStore
5
+ from .config import load_env
6
+ from .errors import AssertionFailed, E2EError, ReplayStale, StepTimeout
7
+ from .models import ChatCompletionsExecutor, DeepSeekExecutor, FunctionExecutor
8
+ from .sdk import Web
9
+ from .session import Agent, WebSession
10
+ from .types import ActResult, AgentConfig, CacheConfig, CacheStore, Cancellation, Engine, Executor, ObservationConfig, Secret, StepRecord, Tool, Unique
11
+
12
+ load_env()
13
+
14
+ __all__ = [
15
+ "Web", "WebSession", "Agent", "BrowserEngine", "AgentConfig", "CacheConfig",
16
+ "CacheStore", "FileCacheStore", "Executor", "Engine", "ChatCompletionsExecutor",
17
+ "DeepSeekExecutor", "ObservationConfig", "FunctionExecutor", "Secret", "Unique", "Cancellation", "Tool", "ActResult",
18
+ "StepRecord", "E2EError", "AssertionFailed", "ReplayStale", "StepTimeout", "load_env",
19
+ ]
e2e_web/_utils.py ADDED
@@ -0,0 +1,129 @@
1
+ """JSON, redaction, timeout and input-template implementation helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import time
9
+ import unicodedata
10
+ from typing import Any
11
+
12
+ from .errors import E2EError, StepTimeout
13
+ from .types import Cancellation, Secret, Unique
14
+
15
+
16
+ def canonical(value: Any) -> str:
17
+ """Encode only finite JSON values, with stable object ordering."""
18
+ try:
19
+ return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
20
+ except (TypeError, ValueError, RecursionError) as exc:
21
+ raise E2EError("INVALID_ARGUMENT", "expected finite JSON data") from exc
22
+
23
+
24
+ def digest(value: Any) -> str:
25
+ """Hash canonical JSON for identity and observation comparisons."""
26
+ return hashlib.sha256(canonical(value).encode()).hexdigest()
27
+
28
+
29
+ def normalize(value: str) -> str:
30
+ """Normalize instruction identity without changing internal whitespace."""
31
+ return unicodedata.normalize("NFC", value.replace("\r\n", "\n").replace("\r", "\n")).strip()
32
+
33
+
34
+ def positive(value: float, label: str) -> float:
35
+ """Require finite positive durations and configuration limits."""
36
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0:
37
+ raise E2EError("INVALID_ARGUMENT", f"{label} must be finite and positive")
38
+ return value
39
+
40
+
41
+ class Deadline:
42
+ """One remaining budget for observations, model calls and actions."""
43
+
44
+ def __init__(self, seconds: float, cancellation: Cancellation, session_end: float | None = None):
45
+ self.end = min(time.monotonic() + positive(seconds, "timeout"), session_end or float("inf"))
46
+ self.cancellation = cancellation
47
+
48
+ def remaining(self) -> float:
49
+ """Fail before an operation starts if its deadline or cancellation fired."""
50
+ if self.cancellation.event.is_set():
51
+ raise E2EError("CANCELLED", "session cancelled")
52
+ remaining = self.end - time.monotonic()
53
+ if remaining <= 0:
54
+ raise StepTimeout("STEP_TIMEOUT", "operation deadline elapsed")
55
+ return remaining
56
+
57
+
58
+ class Ledger:
59
+ """Keep secret values outside executor requests and persistent SDK artifacts."""
60
+
61
+ def __init__(self):
62
+ self.secrets: dict[str, Secret] = {}
63
+
64
+ def register(self, secret: Secret) -> None:
65
+ """Reject ambiguous names and empty values before observing a page."""
66
+ if not secret.name or not secret.value:
67
+ raise E2EError("INVALID_ARGUMENT", "secret name and value must be nonempty")
68
+ previous = self.secrets.get(secret.name)
69
+ if previous is not None and previous != secret:
70
+ raise E2EError("INVALID_ARGUMENT", "secret name already registered with another value")
71
+ self.secrets[secret.name] = secret
72
+
73
+ def redact(self, value: Any) -> Any:
74
+ """Redact strings recursively, including dictionary keys."""
75
+ if isinstance(value, str):
76
+ for secret in sorted(self.secrets.values(), key=lambda s: len(s.value), reverse=True):
77
+ value = value.replace(secret.value, f"<secret:{secret.name}>")
78
+ return value
79
+ if isinstance(value, dict):
80
+ return {self.redact(k): self.redact(v) for k, v in value.items()}
81
+ if isinstance(value, list):
82
+ return [self.redact(v) for v in value]
83
+ return value
84
+
85
+ def project(self, params: dict[str, Any]) -> tuple[dict, dict[str, str]]:
86
+ """Project secrets to handles and Unique values to separately tracked slots."""
87
+ unique: dict[str, str] = {}
88
+
89
+ def walk(value: Any, path: str, depth: int) -> Any:
90
+ if depth > 32:
91
+ raise E2EError("INVALID_ARGUMENT", "params exceed 32 levels")
92
+ if isinstance(value, Secret):
93
+ self.register(value)
94
+ return {"kind": "secret", "name": value.name, "purpose": value.purpose}
95
+ if isinstance(value, Unique):
96
+ if not value.value:
97
+ raise E2EError("INVALID_ARGUMENT", "unique input must be nonempty")
98
+ slot = digest(path)[:16]
99
+ unique[slot] = value.value
100
+ return value.value
101
+ if isinstance(value, dict):
102
+ if not all(isinstance(k, str) for k in value):
103
+ raise E2EError("INVALID_ARGUMENT", "params keys must be strings")
104
+ return {k: walk(v, path + "/" + k.replace("~", "~0").replace("/", "~1"), depth + 1) for k, v in value.items()}
105
+ if isinstance(value, list):
106
+ return [walk(v, path + "/" + str(i), depth + 1) for i, v in enumerate(value)]
107
+ return value
108
+
109
+ projected = walk(params, "", 0)
110
+ if len(canonical(projected).encode()) > 65536:
111
+ raise E2EError("INVALID_ARGUMENT", "params exceed 64 KiB")
112
+ values = list(unique.values())
113
+ if any(a in b or b in a for i, a in enumerate(values) for b in values[i + 1:]):
114
+ raise E2EError("INVALID_ARGUMENT", "unique values overlap; use distinct values")
115
+ return self.redact(projected), unique
116
+
117
+
118
+ def template(value: Any, slots: dict[str, str], *, expand: bool = False) -> Any:
119
+ """Substitute per-run unique strings recursively in JSON string values."""
120
+ if isinstance(value, str):
121
+ for slot, actual in sorted(slots.items(), key=lambda x: len(x[1]), reverse=True):
122
+ marker = f"{{{{e2e_unique:{slot}}}}}"
123
+ value = value.replace(marker, actual) if expand else value.replace(actual, marker)
124
+ return value
125
+ if isinstance(value, dict):
126
+ return {k: template(v, slots, expand=expand) for k, v in value.items()}
127
+ if isinstance(value, list):
128
+ return [template(v, slots, expand=expand) for v in value]
129
+ return value
e2e_web/actions.py ADDED
@@ -0,0 +1,192 @@
1
+ """Closed model action vocabulary and portable locator descriptors."""
2
+
3
+ from typing import Any
4
+
5
+ from .errors import E2EError
6
+
7
+
8
+ CLICK_OPS = {"click", "double_click", "right_click"}
9
+ TARGET_OPS = CLICK_OPS | {"long_press", "fill", "type", "press", "check", "uncheck", "select", "hover",
10
+ "upload", "fill_secret", "drag", "scroll_to"}
11
+ FOCUS_OPS = {"type", "press"}
12
+ VALUE_OPS = {"fill", "type", "press", "select", "upload"}
13
+ VISUAL_OPS = {"click_at", "hover_at", "drag_at", "type_at", "press_at", "select_at"}
14
+ TAB_OPS = {"switch_tab", "close_tab"}
15
+ MODIFIERS = {"Alt", "Control", "ControlOrMeta", "Meta", "Shift"}
16
+
17
+
18
+ def _is_select_option(value: Any) -> bool:
19
+ if isinstance(value, str):
20
+ return True
21
+ if not isinstance(value, dict) or len(value) != 1:
22
+ return False
23
+ key, option = next(iter(value.items()))
24
+ if key == "index":
25
+ return type(option) is int and 0 <= option <= 2**53 - 1
26
+ return key in {"label", "value"} and isinstance(option, str)
27
+
28
+
29
+ def recordable_action(action: dict[str, Any]) -> bool:
30
+ op = action["op"]
31
+ return (op not in VISUAL_OPS and op not in TAB_OPS
32
+ and op not in {"tool", "upload", "scroll_find", "resize_viewport", "screenshot"}
33
+ and (op not in FOCUS_OPS or "target" in action) and action.get('times', 1) == 1)
34
+
35
+
36
+ def press_sequence(action: dict[str, Any]) -> list[dict[str, Any]]:
37
+ """Target only the first key press; later presses use the resulting focus."""
38
+ if action['op'] != 'press' or 'times' not in action:
39
+ return [action]
40
+ first = {key: value for key, value in action.items() if key != 'times'}
41
+ return [first, *(dict(op='press', value=action['value']) for _ in range(action['times'] - 1))]
42
+
43
+
44
+ def validate_target(target: Any) -> dict[str, Any]:
45
+ """Validate a serialized locator, including a frame scope and match index."""
46
+ if not isinstance(target, dict) or not isinstance(target.get("by"), str) or target["by"] not in {"role", "text", "label", "placeholder", "test_id", "css", "ref", "semantic"}:
47
+ raise E2EError("MODEL_OUTPUT_INVALID", "target.by must be role, text, label, placeholder, test_id, css, ref or semantic")
48
+ allowed = {"by", "value", "exact", "nth", "frame"} | ({"name"} if target["by"] in {"role", "semantic"} else set())
49
+ if target["by"] == "ref":
50
+ allowed = {"by", "value", "observation"}
51
+ if not isinstance(target.get("observation"), str) or not target["observation"]:
52
+ raise E2EError("MODEL_OUTPUT_INVALID", "ref requires an observation id")
53
+ if target["by"] == "semantic":
54
+ allowed = {"by", "value", "name", "test_id", "frame", "frame_identity", "within"}
55
+ if not isinstance(target.get("name"), str) or not isinstance(target.get("test_id", ""), str):
56
+ raise E2EError("MODEL_OUTPUT_INVALID", "semantic target requires name and optional test_id")
57
+ if 'frame_identity' in target:
58
+ identities = target['frame_identity']
59
+ frames = target.get('frame', [])
60
+ depth = 1 if isinstance(frames, str) else len(frames) if isinstance(frames, list) else -1
61
+ if not isinstance(identities, list) or len(identities) != depth or not all(
62
+ isinstance(item, dict) and set(item) == {'id', 'name', 'src', 'title'} and
63
+ all(isinstance(v, str) for v in item.values()) for item in identities):
64
+ raise E2EError('MODEL_OUTPUT_INVALID', 'frame_identity must describe every frame in the chain')
65
+ if 'within' in target:
66
+ within = target['within']
67
+ if (not isinstance(within, dict) or set(within) - {'role', 'name', 'test_id'}
68
+ or not all(isinstance(v, str) for v in within.values()) or not within.get('role')
69
+ or not (within.get('name') or within.get('test_id'))):
70
+ raise E2EError('MODEL_OUTPUT_INVALID', 'semantic within requires an ancestor role and a name or test_id')
71
+ if set(target) - allowed or not isinstance(target.get("value"), str) or not target["value"]:
72
+ raise E2EError("MODEL_OUTPUT_INVALID", "target requires a nonempty string value and known fields")
73
+ if "name" in target and not isinstance(target["name"], str):
74
+ raise E2EError("MODEL_OUTPUT_INVALID", "target.name must be a string")
75
+ if "exact" in target and type(target["exact"]) is not bool:
76
+ raise E2EError("MODEL_OUTPUT_INVALID", "target.exact must be boolean")
77
+ if "nth" in target and (type(target["nth"]) is not int or target["nth"] < 0):
78
+ raise E2EError("MODEL_OUTPUT_INVALID", "target.nth must be a nonnegative integer")
79
+ if "frame" in target:
80
+ frames = target["frame"] if isinstance(target["frame"], list) else [target["frame"]]
81
+ if not 1 <= len(frames) <= 8 or not all(isinstance(f, str) and f for f in frames):
82
+ raise E2EError("MODEL_OUTPUT_INVALID", "target.frame must be a selector or 1..8 iframe selectors")
83
+ return dict(target)
84
+
85
+
86
+ def validate_action(action: Any) -> dict[str, Any]:
87
+ """Reject invented operations or malformed values before a side effect."""
88
+ if not isinstance(action, dict):
89
+ raise E2EError("MODEL_OUTPUT_INVALID", "action must be an object")
90
+ op = action.get("op")
91
+ if not isinstance(op, str):
92
+ raise E2EError("MODEL_OUTPUT_INVALID", "action.op must be a string")
93
+ fields = {"op"}
94
+ if op in TARGET_OPS:
95
+ if op not in FOCUS_OPS or "target" in action:
96
+ fields.add("target")
97
+ validate_target(action.get("target"))
98
+ elif op == "type" and "replace" in action:
99
+ fields.add("replace")
100
+ if type(action["replace"]) is not bool:
101
+ raise E2EError("MODEL_OUTPUT_INVALID", "type.replace must be boolean")
102
+ if op in VALUE_OPS:
103
+ fields.add("value")
104
+ value = action.get("value")
105
+ if op == "upload":
106
+ if not isinstance(value, list) or not value or not all(isinstance(v, str) and v for v in value):
107
+ raise E2EError("MODEL_OUTPUT_INVALID", "upload value must be a nonempty list of paths")
108
+ elif op == "select":
109
+ if not (all(_is_select_option(option) for option in value) if isinstance(value, list)
110
+ else _is_select_option(value)):
111
+ raise E2EError("MODEL_OUTPUT_INVALID", "select value must be a label, a label/value/index descriptor or a list of options")
112
+ elif not isinstance(value, str):
113
+ raise E2EError("MODEL_OUTPUT_INVALID", "action.value must be a string")
114
+ if op == 'press' and 'times' in action:
115
+ fields.add('times')
116
+ if type(action['times']) is not int or not 1 <= action['times'] <= 20:
117
+ raise E2EError('MODEL_OUTPUT_INVALID', 'press.times must be an integer from 1 to 20')
118
+ elif op == "fill_secret":
119
+ fields.add("secret")
120
+ if not isinstance(action.get("secret"), str):
121
+ raise E2EError("MODEL_OUTPUT_INVALID", "fill_secret requires a named secret")
122
+ elif op == "drag":
123
+ fields.add("to")
124
+ validate_target(action.get("to"))
125
+ elif op in CLICK_OPS and "modifiers" in action:
126
+ fields.add("modifiers")
127
+ modifiers = action["modifiers"]
128
+ if (not isinstance(modifiers, list)
129
+ or not all(isinstance(key, str) and key in MODIFIERS for key in modifiers)
130
+ or len(modifiers) != len(set(modifiers))):
131
+ raise E2EError("MODEL_OUTPUT_INVALID", "modifiers must be an array of distinct supported keys")
132
+ elif op in VISUAL_OPS:
133
+ fields |= {"x", "y", "screenshot"}
134
+ coordinates = {"x", "y"}
135
+ if op == "drag_at":
136
+ coordinates |= {"to_x", "to_y"}
137
+ fields |= coordinates
138
+ if op in {"type_at", "press_at", "select_at"}:
139
+ fields.add("value")
140
+ if not isinstance(action.get("value"), str):
141
+ raise E2EError("MODEL_OUTPUT_INVALID", f"{op} requires a string value")
142
+ if op == "press_at" and not 1 <= len(action["value"]) <= 64:
143
+ raise E2EError("MODEL_OUTPUT_INVALID", "press_at requires a nonempty key of at most 64 characters")
144
+ if op == "type_at" and "replace" in action:
145
+ fields.add("replace")
146
+ if type(action["replace"]) is not bool:
147
+ raise E2EError("MODEL_OUTPUT_INVALID", "type_at.replace must be boolean")
148
+ for key in coordinates:
149
+ if type(action.get(key)) is not int or not 0 <= action[key] <= 100000:
150
+ raise E2EError("MODEL_OUTPUT_INVALID", "coordinates must be nonnegative bounded integers")
151
+ if not isinstance(action.get("screenshot"), str) or not action["screenshot"]:
152
+ raise E2EError("MODEL_OUTPUT_INVALID", "coordinate actions require a screenshot id")
153
+ elif op == "scroll_find":
154
+ fields |= {"target", "direction", "steps"}
155
+ validate_target(action.get("target"))
156
+ if action["target"]["by"] == "ref" or action.get("direction") not in ("up", "down", "left", "right") or type(action.get("steps")) is not int or not 1 <= action["steps"] <= 800:
157
+ raise E2EError("MODEL_OUTPUT_INVALID", "scroll_find requires a portable target, up/down/left/right and 1..800 steps")
158
+ if "container" in action:
159
+ fields.add("container")
160
+ validate_target(action["container"])
161
+ elif op == "navigate":
162
+ fields.add("url")
163
+ if not isinstance(action.get("url"), str):
164
+ raise E2EError("MODEL_OUTPUT_INVALID", "navigate requires a URL")
165
+ elif op == "resize_viewport":
166
+ fields |= {"width", "height"}
167
+ if any(type(action.get(key)) is not int or not 200 <= action[key] <= 4096 for key in ("width", "height")):
168
+ raise E2EError("MODEL_OUTPUT_INVALID", "viewport width and height must be integers from 200 to 4096")
169
+ elif op in TAB_OPS:
170
+ fields.add("tab")
171
+ if type(action.get("tab")) is not int or not 1 <= action["tab"] <= 2**53 - 1:
172
+ raise E2EError("MODEL_OUTPUT_INVALID", "tab must be a positive integer from the observation")
173
+ elif op == "scroll":
174
+ fields |= {"x", "y"}
175
+ if any(type(action.get(k)) is not int or abs(action[k]) > 10000 for k in ("x", "y")):
176
+ raise E2EError("MODEL_OUTPUT_INVALID", "scroll requires bounded integer x/y deltas")
177
+ if "target" in action:
178
+ fields.add("target")
179
+ validate_target(action["target"])
180
+ elif op == "wait":
181
+ fields.add("seconds")
182
+ if type(action.get("seconds")) not in {int, float} or not 0 < action["seconds"] <= 5:
183
+ raise E2EError("MODEL_OUTPUT_INVALID", "wait.seconds must be between 0 and 5")
184
+ elif op == "tool":
185
+ fields |= {"name", "arguments"}
186
+ if not isinstance(action.get("name"), str) or not isinstance(action.get("arguments"), dict):
187
+ raise E2EError("MODEL_OUTPUT_INVALID", "tool requires name and arguments")
188
+ elif op not in {"back", "forward", "reload", "screenshot"}:
189
+ raise E2EError("MODEL_OUTPUT_INVALID", "unknown action operation")
190
+ if set(action) != fields:
191
+ raise E2EError("MODEL_OUTPUT_INVALID", f"{op} requires exactly {sorted(fields)}")
192
+ return dict(action)