autowebcompat-tools 0.1.0__tar.gz

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.
@@ -0,0 +1,62 @@
1
+ *model
2
+ *model.zst
3
+ *model.zst.etag
4
+ *data_X
5
+ *data_y
6
+ *data_X.zst
7
+ *data_X.zst.etag
8
+ *data_y.zst
9
+ *data_y.zst.etag
10
+ feature_importance.png
11
+ importance.html
12
+ importances.json
13
+ metrics.json
14
+ probs.json
15
+ services/bugbug-api/models/*model*
16
+
17
+ data/
18
+ sheets/
19
+
20
+ .mypy_cache/
21
+ .pytest_cache/
22
+ *.pyc
23
+ .coverage
24
+
25
+ # Distribution / packaging
26
+ .Python
27
+ build/
28
+ develop-eggs/
29
+ dist/
30
+ downloads/
31
+ eggs/
32
+ .eggs/
33
+ lib/
34
+ lib64/
35
+ parts/
36
+ sdist/
37
+ var/
38
+ wheels/
39
+ pip-wheel-metadata/
40
+ share/python-wheels/
41
+ *.egg-info/
42
+ .installed.cfg
43
+ *.egg
44
+ MANIFEST
45
+ cache/
46
+ node_modules/
47
+
48
+ # Logs
49
+ *.log
50
+ # Desktop Service Store
51
+ *.DS_Store
52
+
53
+ # Local env files
54
+ .env
55
+ /services/bugbug-api/docker-compose.override.yml
56
+
57
+ # Local files
58
+ *.local.*
59
+
60
+ # Claude Code local state
61
+ .claude/worktrees/
62
+ .claude/.cc-writes/
@@ -0,0 +1,14 @@
1
+ Metadata-Version: 2.5
2
+ Name: autowebcompat-tools
3
+ Version: 0.1.0
4
+ Summary: Code shared by the autowebcompat agents
5
+ Requires-Python: >=3.14
6
+ Requires-Dist: claude-agent-sdk>=0.2.165
7
+ Requires-Dist: hackbot-runtime[claude-sdk]
8
+ Requires-Dist: mozdownload
9
+ Requires-Dist: mozinstall
10
+ Requires-Dist: pydantic>=2.0.0
11
+ Requires-Dist: requests>=2.32.0
12
+ Provides-Extra: dev
13
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
14
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
@@ -0,0 +1 @@
1
+ 0.1.0
@@ -0,0 +1,55 @@
1
+ """Download AMO extensions and read their Firefox extension IDs."""
2
+
3
+ import json
4
+ import zipfile
5
+ from pathlib import Path
6
+
7
+ import requests
8
+
9
+ AMO_API_TMPL = "https://addons.mozilla.org/api/v5/addons/addon/{slug}/"
10
+ AMO_REQUEST_HEADERS = {"User-Agent": "webcompat-setup"}
11
+ AMO_API_TIMEOUT = 30
12
+ AMO_DOWNLOAD_TIMEOUT = 120
13
+
14
+
15
+ def amo_get(
16
+ url: str, *, timeout: int = AMO_API_TIMEOUT, stream: bool = False
17
+ ) -> requests.Response:
18
+ """Make an AMO HTTP GET with shared defaults and status handling."""
19
+ resp = requests.get(
20
+ url,
21
+ headers=AMO_REQUEST_HEADERS,
22
+ timeout=timeout,
23
+ stream=stream,
24
+ )
25
+ resp.raise_for_status()
26
+ return resp
27
+
28
+
29
+ def resolve_xpi_url(slug: str) -> tuple[str, str]:
30
+ """Return (download_url, version) for the latest signed xpi of an AMO addon."""
31
+ with amo_get(AMO_API_TMPL.format(slug=slug)) as resp:
32
+ data = resp.json()
33
+ ver = data["current_version"]
34
+ return ver["file"]["url"], ver["version"]
35
+
36
+
37
+ def download(url: str, dest: Path) -> None:
38
+ with (
39
+ amo_get(url, timeout=AMO_DOWNLOAD_TIMEOUT, stream=True) as resp,
40
+ dest.open("wb") as f,
41
+ ):
42
+ for chunk in resp.iter_content(chunk_size=64 * 1024):
43
+ if chunk:
44
+ f.write(chunk)
45
+
46
+
47
+ def extract_extension_id(xpi: Path) -> str:
48
+ """Read the gecko extension ID out of the xpi's manifest.json."""
49
+ with zipfile.ZipFile(xpi) as zf, zf.open("manifest.json") as f:
50
+ manifest = json.load(f)
51
+ for key in ("browser_specific_settings", "applications"):
52
+ gecko = manifest.get(key, {}).get("gecko", {})
53
+ if "id" in gecko:
54
+ return gecko["id"]
55
+ raise RuntimeError(f"no gecko extension ID in {xpi}'s manifest.json")
@@ -0,0 +1,232 @@
1
+ import logging
2
+ import os
3
+ import platform
4
+ import stat
5
+ import sys
6
+ import tempfile
7
+ import zipfile
8
+ from datetime import UTC, datetime, timedelta
9
+ from pathlib import Path
10
+ from typing import Literal
11
+
12
+ import mozdownload
13
+ import mozinstall
14
+ import requests
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ # How many earlier days of Nightly to try if the latest build can't be fetched.
19
+ NIGHTLY_FALLBACK_DAYS = 3
20
+
21
+
22
+ def install_firefox(
23
+ channel: Literal["nightly"] | Literal["stable"] | Literal["esr"],
24
+ ) -> Path:
25
+ install_dir = tempfile.mkdtemp(prefix=f"firefox-{channel}-", dir=Path.home())
26
+
27
+ # mozdownload doesn't correctly get arm builds for arm linux
28
+ mozdownload_platform = (
29
+ "linux-arm64" if platform.machine() in ("aarch64", "arm64") else None
30
+ )
31
+
32
+ kwargs = {}
33
+ if channel == "nightly":
34
+ scraper_type = "daily"
35
+ kwargs["branch"] = "mozilla-central"
36
+ else:
37
+ scraper_type = "release"
38
+ if channel == "stable":
39
+ version = "latest"
40
+ else:
41
+ assert channel == "esr"
42
+ version = "latest-esr"
43
+ kwargs["version"] = version
44
+
45
+ logger.info("downloading Firefox %s...", channel)
46
+ scraper = None
47
+ # The newest Nightly's folder is sometimes not yet listed on the archive,
48
+ # in which case mozdownload raises NotFoundError; fall back to earlier days.
49
+ for days_back in range(NIGHTLY_FALLBACK_DAYS + 1 if channel == "nightly" else 1):
50
+ if days_back:
51
+ day = datetime.now(UTC).date() - timedelta(days=days_back)
52
+ kwargs["date"] = day.isoformat()
53
+ logger.warning("falling back to Firefox nightly from %s", day)
54
+ try:
55
+ scraper = mozdownload.FactoryScraper(
56
+ scraper_type,
57
+ platform=mozdownload_platform,
58
+ destination=str(install_dir),
59
+ **kwargs,
60
+ )
61
+ break
62
+ except mozdownload.errors.NotFoundError:
63
+ if days_back == NIGHTLY_FALLBACK_DAYS or channel != "nightly":
64
+ raise
65
+ logger.exception("could not find Firefox nightly build")
66
+ archive = scraper.download()
67
+
68
+ install_path = mozinstall.install(archive, str(install_dir))
69
+ binary = Path(mozinstall.get_binary(install_path, "firefox"))
70
+
71
+ logger.info("installed Firefox at %s", binary)
72
+ return binary
73
+
74
+
75
+ class FirefoxBrowsers:
76
+ def __init__(self) -> None:
77
+ self._nightly: Path | None = None
78
+ self._esr: Path | None = None
79
+ self._stable: Path | None = None
80
+
81
+ @property
82
+ def nightly(self) -> Path:
83
+ if self._nightly is None:
84
+ self._nightly = install_firefox(channel="nightly")
85
+ return self._nightly
86
+
87
+ @property
88
+ def stable(self) -> Path:
89
+ if self._stable is None:
90
+ self._stable = install_firefox(channel="stable")
91
+ return self._stable
92
+
93
+ @property
94
+ def esr(self) -> Path:
95
+ if self._esr is None:
96
+ self._esr = install_firefox(channel="esr")
97
+ return self._esr
98
+
99
+
100
+ def chrome_platform() -> str:
101
+ """Chrome for Testing platform string for the current host."""
102
+ system = platform.system()
103
+ machine = platform.machine().lower()
104
+ if system == "Linux":
105
+ if machine not in {"x86_64", "amd64"}:
106
+ raise RuntimeError(
107
+ "Chrome for Testing has no linux build for "
108
+ f"{platform.machine()}; only x86_64/amd64 is supported. Run the "
109
+ "agent image as linux/amd64, e.g. DOCKER_DEFAULT_PLATFORM=linux/amd64."
110
+ )
111
+ return "linux64"
112
+ if system == "Darwin":
113
+ return "mac-arm64" if machine in {"arm64", "aarch64"} else "mac-x64"
114
+ if system == "Windows":
115
+ return "win64" if machine in {"x86_64", "amd64"} else "win32"
116
+ raise RuntimeError(f"Unsupported platform for Chrome for Testing: {system}")
117
+
118
+
119
+ def resolve_chrome_download_url(channel: str, cft_platform: str) -> str:
120
+ """Look up the Chrome for Testing download URL for a channel + platform."""
121
+ versions_url = (
122
+ "https://googlechromelabs.github.io/chrome-for-testing/"
123
+ "last-known-good-versions-with-downloads.json"
124
+ )
125
+ response = requests.get(versions_url, timeout=120)
126
+ response.raise_for_status()
127
+ data = response.json()
128
+
129
+ entry = data["channels"][channel.capitalize()]
130
+ logger.info("Chrome for Testing %s: version %s", channel, entry["version"])
131
+
132
+ for download in entry["downloads"]["chrome"]:
133
+ if download["platform"] == cft_platform:
134
+ return download["url"]
135
+
136
+ raise RuntimeError(
137
+ f"no Chrome for Testing '{cft_platform}' download in {channel} channel"
138
+ )
139
+
140
+
141
+ def chrome_binary_path(install_dir: Path, cft_platform: str) -> Path:
142
+ """Path to the Chrome for Testing binary within the unpacked archive.
143
+
144
+ Chrome for Testing uses a different executable name/layout per platform:
145
+ on macOS it is inside an `.app` bundle, on Windows it is `chrome.exe`,
146
+ and on Linux it is a `chrome`.
147
+ """
148
+ package = install_dir / f"chrome-{cft_platform}"
149
+ if cft_platform.startswith("mac"):
150
+ return (
151
+ package
152
+ / "Google Chrome for Testing.app"
153
+ / "Contents"
154
+ / "MacOS"
155
+ / "Google Chrome for Testing"
156
+ )
157
+ if cft_platform.startswith("win"):
158
+ return package / "chrome.exe"
159
+ return package / "chrome"
160
+
161
+
162
+ def unzip(archive: Path, dest: Path) -> None:
163
+ """Extract a zip, preserving unix permission bits and recreating symlinks.
164
+
165
+ This keeps the Chrome binary executable and, on macOS, keeps the ``.app``
166
+ bundle's internal symlinks intact.
167
+
168
+ Adapted from wpt's tools/wpt/utils.py::unzip.
169
+ """
170
+ with zipfile.ZipFile(archive) as zip_data:
171
+ for info in zip_data.infolist():
172
+ # external_attr's two high bytes carry the unix st_mode, but only
173
+ # when the archive was created on a unix system (create_system == 3).
174
+ # A DOS/Windows-created archive, or extraction on Windows, carries no
175
+ # useful permission info, so fall back to a plain extract there.
176
+ if info.create_system == 0 or sys.platform == "win32":
177
+ zip_data.extract(info, path=dest)
178
+ continue
179
+
180
+ st_mode = info.external_attr >> 16
181
+ dst_path = os.path.join(dest, info.filename)
182
+ if stat.S_ISLNK(st_mode):
183
+ # Symlinks are stored as files whose contents are the target;
184
+ # recreate the link rather than extracting it as a file.
185
+ link_target = zip_data.read(info)
186
+ os.makedirs(os.path.dirname(dst_path), exist_ok=True)
187
+ if os.path.islink(dst_path):
188
+ os.unlink(dst_path)
189
+ os.symlink(link_target, dst_path)
190
+ else:
191
+ zip_data.extract(info, path=dest)
192
+ # Preserve the permission bits (rwxrwxrwx) only, dropping the
193
+ # sticky/setuid/setgid bits.
194
+ os.chmod(dst_path, st_mode & 0o777)
195
+
196
+
197
+ def install_chrome(channel: Literal["stable"] = "stable") -> Path:
198
+ """Download Chrome for Testing and return the browser binary path."""
199
+ cft_platform = chrome_platform()
200
+ install_dir = Path(tempfile.mkdtemp(prefix=f"chrome-{channel}-", dir=Path.home()))
201
+
202
+ url = resolve_chrome_download_url(channel, cft_platform)
203
+ archive = install_dir / f"chrome-{cft_platform}.zip"
204
+
205
+ logger.info("downloading Chrome for Testing from %s", url)
206
+ with requests.get(url, stream=True, timeout=120) as response:
207
+ response.raise_for_status()
208
+ with archive.open("wb") as out:
209
+ for chunk in response.iter_content(chunk_size=1 << 20):
210
+ if chunk:
211
+ out.write(chunk)
212
+
213
+ unzip(archive, install_dir)
214
+ archive.unlink()
215
+
216
+ binary = chrome_binary_path(install_dir, cft_platform)
217
+ if not binary.exists():
218
+ raise RuntimeError(f"Chrome binary not found at {binary} after unpacking")
219
+
220
+ logger.info("installed Chrome at %s", binary)
221
+ return binary
222
+
223
+
224
+ class ChromeBrowsers:
225
+ def __init__(self) -> None:
226
+ self._stable: Path | None = None
227
+
228
+ @property
229
+ def stable(self) -> Path:
230
+ if self._stable is None:
231
+ self._stable = install_chrome(channel="stable")
232
+ return self._stable
@@ -0,0 +1,43 @@
1
+ import logging
2
+ import os
3
+ import subprocess
4
+ from typing import Self
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+
9
+ class Environment:
10
+ def __init__(self) -> None:
11
+ self.started_processes: list[subprocess.Popen] = []
12
+
13
+ def start(self, cmd: list[str]) -> None:
14
+ logger.info("Running %s", " ".join(cmd))
15
+ self.started_processes.append(subprocess.Popen(cmd))
16
+
17
+ def start_xvfb(self) -> None:
18
+ self.start(
19
+ [
20
+ "Xvfb",
21
+ os.environ["DISPLAY"],
22
+ "-screen",
23
+ "0",
24
+ "%sx%sx%s"
25
+ % (
26
+ os.environ["SCREEN_WIDTH"],
27
+ os.environ["SCREEN_HEIGHT"],
28
+ os.environ["SCREEN_DEPTH"],
29
+ ),
30
+ ]
31
+ )
32
+ self.start(["fluxbox", "-display", os.environ["DISPLAY"]])
33
+
34
+ def __enter__(self) -> Self:
35
+ return self
36
+
37
+ def __exit__(self, *args, **kwargs) -> None:
38
+ for process in self.started_processes:
39
+ process.terminate()
40
+ try:
41
+ process.wait(timeout=30)
42
+ except subprocess.TimeoutExpired:
43
+ process.kill()
@@ -0,0 +1,25 @@
1
+ """The bug an autowebcompat agent works on: a Bugzilla id or inline report text."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Literal
5
+
6
+
7
+ @dataclass
8
+ class BugIdInput:
9
+ bug_id: int
10
+ type: Literal["bug_id"] = "bug_id"
11
+
12
+ def subject(self) -> str:
13
+ return f"bug {self.bug_id}"
14
+
15
+
16
+ @dataclass
17
+ class BugDataInput:
18
+ bug_data: str
19
+ type: Literal["bug_data"] = "bug_data"
20
+
21
+ def subject(self) -> str:
22
+ return self.bug_data
23
+
24
+
25
+ AutoWebcompatInput = BugIdInput | BugDataInput
@@ -0,0 +1,105 @@
1
+ """Stdio configs for the DevTools MCP servers the agents drive.
2
+
3
+ The MCP servers are npm packages pinned in ``package.json`` and installed into
4
+ each agent image with ``npm ci`` (see the agents' Dockerfiles).
5
+ """
6
+
7
+ from pathlib import Path
8
+
9
+ from claude_agent_sdk.types import McpStdioServerConfig
10
+
11
+ NODE_MODULES = Path("/app/node_modules")
12
+
13
+
14
+ def resolve_bin(bin_name: str) -> str:
15
+ """Resolve an installed MCP server binary to an absolute path."""
16
+ binary = NODE_MODULES / ".bin" / bin_name
17
+ if not binary.exists():
18
+ raise RuntimeError(
19
+ f"MCP server binary not found at {binary}; the image should install "
20
+ f"it with `npm ci` (see the Dockerfile)."
21
+ )
22
+ return str(binary)
23
+
24
+
25
+ def build_firefox_devtools_server(
26
+ firefox_path: Path | None = None,
27
+ *,
28
+ headless: bool = True,
29
+ enable_script: bool = True,
30
+ enable_privileged_context: bool = False,
31
+ profile_path: Path | None = None,
32
+ ) -> McpStdioServerConfig:
33
+ """Build the stdio config for the Firefox DevTools MCP server.
34
+
35
+ Args:
36
+ firefox_path: Firefox binary to drive. When ``None`` the server
37
+ auto-detects an installed Firefox.
38
+ headless: Run Firefox without a visible window (required in
39
+ container/CI environments).
40
+ enable_script: Expose the ``evaluate_script`` tool, which runs
41
+ arbitrary JS in the page context.
42
+ enable_privileged_context: Expose the privileged-context tools
43
+ (``list_extensions``, ``evaluate_privileged_script``, prefs, etc.)
44
+ and set ``MOZ_REMOTE_ALLOW_SYSTEM_ACCESS=1`` on the Firefox process.
45
+ Required for the Chrome Mask flow: the agent needs ``list_extensions``
46
+ to resolve the extension's ``moz-extension://<uuid>/`` base URL, and
47
+ navigating to that privileged origin is itself blocked without this.
48
+ profile_path: A pre-built Firefox profile to use as a template (e.g.
49
+ one with the Chrome Mask extension installed). geckodriver copies
50
+ it into a fresh per-session profile, so the template is not
51
+ mutated. When ``None`` the server uses a clean throwaway profile.
52
+ """
53
+ args = []
54
+ if headless:
55
+ args.append("--headless")
56
+ if enable_script:
57
+ args.append("--enable-script")
58
+ if enable_privileged_context:
59
+ args.append("--enable-privileged-context")
60
+ if firefox_path is not None:
61
+ args += ["--firefox-path", str(firefox_path)]
62
+ if profile_path is not None:
63
+ args += ["--profile-path", str(profile_path)]
64
+
65
+ command = resolve_bin("firefox-devtools-mcp-moz")
66
+ if enable_privileged_context:
67
+ return McpStdioServerConfig(
68
+ command=command, args=args, env={"MOZ_REMOTE_ALLOW_SYSTEM_ACCESS": "1"}
69
+ )
70
+ return McpStdioServerConfig(command=command, args=args)
71
+
72
+
73
+ def build_chrome_devtools_server(
74
+ chrome_path: Path | None = None,
75
+ *,
76
+ headless: bool = True,
77
+ no_sandbox: bool = True,
78
+ ) -> McpStdioServerConfig:
79
+ """Build the stdio config for the Chrome DevTools MCP server.
80
+
81
+ Args:
82
+ chrome_path: Chrome binary to drive (the Chrome for Testing build from
83
+ ``browser.install_chrome``). When ``None`` the server lets its
84
+ bundled Puppeteer discover a Chrome installation itself.
85
+ headless: Run Chrome without a visible window (required in
86
+ container/CI environments).
87
+ no_sandbox: Pass ``--no-sandbox`` to Chrome. Required when running as an
88
+ unprivileged user inside a container, where Chrome's setuid sandbox
89
+ cannot initialize and the browser otherwise fails to launch.
90
+ """
91
+ args = []
92
+ if headless:
93
+ args.append("--headless")
94
+ if chrome_path is not None:
95
+ args += ["--executablePath", str(chrome_path)]
96
+
97
+ # Opt out of the MCP server's own data collection: its usage statistics and
98
+ # the CrUX API calls that send performance-trace URLs to Google. This does
99
+ # not touch Chrome's own behavior, only what the MCP server itself reports.
100
+ args += ["--usageStatistics=false", "--performanceCrux=false"]
101
+
102
+ if no_sandbox:
103
+ args += ["--chromeArg=--no-sandbox", "--chromeArg=--disable-setuid-sandbox"]
104
+
105
+ return McpStdioServerConfig(command=resolve_bin("chrome-devtools-mcp"), args=args)
@@ -0,0 +1,53 @@
1
+ """The ``submit_result`` tool an agent calls to hand back its validated result."""
2
+
3
+ from typing import Generic, TypeVar
4
+
5
+ from claude_agent_sdk import McpServerConfig, create_sdk_mcp_server, tool
6
+ from pydantic import BaseModel, ValidationError
7
+
8
+ ResultT = TypeVar("ResultT", bound=BaseModel)
9
+
10
+
11
+ class ResultCollector(Generic[ResultT]):
12
+ """Holds the result submitted by the agent, if any."""
13
+
14
+ def __init__(self, result_cls: type[ResultT]) -> None:
15
+ self.result_cls: type[ResultT] = result_cls
16
+ self.result: ResultT | None = None
17
+
18
+
19
+ def submit_result_tool_name(server_name: str) -> str:
20
+ """The ``submit_result`` tool's name as the agent sees it."""
21
+ return f"mcp__{server_name}__submit_result"
22
+
23
+
24
+ def build_result_server(
25
+ server_name: str, collector: ResultCollector
26
+ ) -> McpServerConfig:
27
+ """Build an in-process MCP server exposing the ``submit_result`` tool.
28
+
29
+ The handler validates the payload against the collector's result class and
30
+ stores it. A validation error is returned to the model (as tool output) so
31
+ it can correct and resubmit rather than failing the run.
32
+ """
33
+
34
+ @tool(
35
+ "submit_result",
36
+ "Submit the final result for this task. Call exactly once, at the end, "
37
+ "after completing the task.",
38
+ {
39
+ **collector.result_cls.model_json_schema(),
40
+ "additionalProperties": False,
41
+ },
42
+ )
43
+ async def submit_result(args: dict) -> dict:
44
+ try:
45
+ collector.result = collector.result_cls.model_validate(args)
46
+ except ValidationError as exc:
47
+ return {
48
+ "content": [{"type": "text", "text": f"Invalid result: {exc}"}],
49
+ "is_error": True,
50
+ }
51
+ return {"content": [{"type": "text", "text": "Result recorded."}]}
52
+
53
+ return create_sdk_mcp_server(name=server_name, tools=[submit_result])