autowebcompat-tools 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.
File without changes
@@ -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])
@@ -0,0 +1,253 @@
1
+ """One Claude session per task, ending in a validated result."""
2
+
3
+ import logging
4
+ from abc import ABC, abstractmethod
5
+ from dataclasses import dataclass
6
+ from datetime import datetime
7
+ from pathlib import Path
8
+ from typing import Any, Generic
9
+
10
+ from claude_agent_sdk import (
11
+ ClaudeAgentOptions,
12
+ ClaudeSDKClient,
13
+ EffortLevel,
14
+ McpServerConfig,
15
+ ResultMessage,
16
+ )
17
+ from claude_agent_sdk.types import SystemPromptPreset
18
+ from hackbot_runtime import AgentError
19
+ from hackbot_runtime.claude import Reporter
20
+ from pydantic import ValidationError
21
+
22
+ from autowebcompat_tools.result import (
23
+ ResultCollector,
24
+ ResultT,
25
+ build_result_server,
26
+ submit_result_tool_name,
27
+ )
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ @dataclass
33
+ class TaskConfig:
34
+ model: str | None = None
35
+ max_turns: int | None = None
36
+ effort: EffortLevel | None = None
37
+ log: Path | None = None
38
+ verbose: bool = True
39
+ headless: bool = False
40
+
41
+
42
+ @dataclass
43
+ class TaskRun:
44
+ name: str
45
+ start_time: datetime
46
+ end_time: datetime
47
+ num_turns: int
48
+ total_cost_usd: float | None
49
+
50
+
51
+ class RetryResultError(Exception):
52
+ """Raised by ``handle_result`` to ask the agent to fix and resubmit."""
53
+
54
+
55
+ class RunTracker:
56
+ """Accumulates per-task turn counts and costs across the run's stages."""
57
+
58
+ def __init__(self) -> None:
59
+ self.task_runs: list[TaskRun] = []
60
+ self.current_task: tuple[str, datetime] | None = None
61
+
62
+ @property
63
+ def num_turns(self) -> int:
64
+ return sum(item.num_turns for item in self.task_runs)
65
+
66
+ @property
67
+ def total_cost_usd(self) -> float:
68
+ return sum(
69
+ item.total_cost_usd
70
+ for item in self.task_runs
71
+ if item.total_cost_usd is not None
72
+ )
73
+
74
+ def start_task(self, name: str) -> None:
75
+ self.current_task = name, datetime.now()
76
+
77
+ def end_task(self, name: str, result_msg: ResultMessage) -> None:
78
+ if self.current_task is None:
79
+ logger.warning("Got end_task without start_task")
80
+ return
81
+ current_name, start_time = self.current_task
82
+ if current_name != name:
83
+ logger.warning(
84
+ "Got end_task with name %s but current_task was %s", name, current_name
85
+ )
86
+ self.current_task = None
87
+ return
88
+ self.task_runs.append(
89
+ TaskRun(
90
+ name=name,
91
+ start_time=start_time,
92
+ end_time=datetime.now(),
93
+ num_turns=result_msg.num_turns,
94
+ total_cost_usd=result_msg.total_cost_usd,
95
+ )
96
+ )
97
+
98
+
99
+ async def last_result(
100
+ client: ClaudeSDKClient, reporter: Reporter, subject: Any
101
+ ) -> ResultMessage:
102
+ """Drain the response to the last query and return its ResultMessage."""
103
+ result_msg: ResultMessage | None = None
104
+ async for msg in client.receive_response():
105
+ reporter.message(msg)
106
+ if isinstance(msg, ResultMessage):
107
+ result_msg = msg
108
+ if result_msg is None:
109
+ raise AgentError(f"{subject}: agent produced no result message")
110
+ return result_msg
111
+
112
+
113
+ class Task(ABC, Generic[ResultT]):
114
+ """One Claude session, ending in a validated ``submit_result`` payload.
115
+
116
+ The system prompt is Claude Code's own unless the agent overrides
117
+ ``system_prompt()``: a preset with an ``append``, or a full replacement
118
+ string. The task itself goes in the user prompt. Each agent sets its own
119
+ ``result_server_name`` for the ``submit_result`` tool.
120
+ """
121
+
122
+ name: str = "unnamed-task"
123
+ result_cls: type[ResultT]
124
+ result_server_name: str
125
+
126
+ def __init__(self, task_config: TaskConfig, run_tracker: RunTracker):
127
+ self.task_config = task_config
128
+ self.run_tracker = run_tracker
129
+ self.result_collector = ResultCollector(self.result_cls)
130
+ self.allowed_tools: list[str] = ["Read", "Grep", "Glob", "Bash"]
131
+ self.mcp_servers: dict[str, McpServerConfig] = {}
132
+ result_server = self.result_server()
133
+ if result_server is not None:
134
+ self.add_mcp_server(
135
+ self.result_server_name,
136
+ result_server,
137
+ [submit_result_tool_name(self.result_server_name)],
138
+ )
139
+
140
+ def add_mcp_server(
141
+ self, name: str, server: McpServerConfig, tools: list[str]
142
+ ) -> None:
143
+ self.mcp_servers[name] = server
144
+ self.allowed_tools.extend(tools)
145
+
146
+ def result_server(self) -> McpServerConfig | None:
147
+ return build_result_server(self.result_server_name, self.result_collector)
148
+
149
+ def system_prompt(self) -> str | SystemPromptPreset:
150
+ return {"type": "preset", "preset": "claude_code"}
151
+
152
+ @abstractmethod
153
+ def user_prompt(self) -> str: ...
154
+
155
+ @abstractmethod
156
+ def subject(self) -> Any: ...
157
+
158
+ def agent_options(self) -> ClaudeAgentOptions:
159
+ return ClaudeAgentOptions(
160
+ system_prompt=self.system_prompt(),
161
+ mcp_servers=self.mcp_servers,
162
+ permission_mode="bypassPermissions",
163
+ allowed_tools=self.allowed_tools,
164
+ model=self.task_config.model,
165
+ max_turns=self.task_config.max_turns,
166
+ setting_sources=[],
167
+ # DevTools snapshots of complex pages can exceed the SDK's default
168
+ # 1 MiB message buffer, which kills the reader fatally.
169
+ max_buffer_size=10 * 1024 * 1024,
170
+ effort=self.task_config.effort,
171
+ )
172
+
173
+ def handle_result(self, msg: ResultMessage) -> ResultT:
174
+ if self.result_collector.result is None:
175
+ raise AgentError(
176
+ f"{self.subject()}: agent finished without submitting a result via submit_result"
177
+ )
178
+ return self.result_collector.result
179
+
180
+ async def run(self) -> ResultT:
181
+ self.run_tracker.start_task(self.name)
182
+ subject = self.subject()
183
+ preview = str(subject)
184
+ if len(preview) > 200:
185
+ preview = f"{preview[:200]}..."
186
+ logger.info("Running %s with %s", self.__class__.__name__, preview)
187
+
188
+ msg: ResultMessage | None = None
189
+ try:
190
+ with Reporter(
191
+ verbose=self.task_config.verbose, log_path=self.task_config.log
192
+ ) as reporter:
193
+ reporter.header(subject)
194
+
195
+ async with ClaudeSDKClient(options=self.agent_options()) as client:
196
+ await client.query(self.user_prompt())
197
+ msg = await last_result(client, reporter, subject)
198
+ self.check_error(msg, subject)
199
+ try:
200
+ result = self.handle_result(msg)
201
+ except RetryResultError as exc:
202
+ # One follow-up turn for StructuredTask
203
+ await client.query(
204
+ f"Invalid result: {exc}. Fix it and resubmit."
205
+ )
206
+ msg = await last_result(client, reporter, subject)
207
+ self.check_error(msg, subject)
208
+ try:
209
+ result = self.handle_result(msg)
210
+ except RetryResultError as retry_exc:
211
+ raise AgentError(
212
+ f"{subject}: {self.name} failed: {retry_exc}"
213
+ ) from retry_exc
214
+ finally:
215
+ if msg is not None:
216
+ self.run_tracker.end_task(self.name, msg)
217
+ return result
218
+
219
+ def check_error(self, msg: ResultMessage, subject: Any) -> None:
220
+ if msg.is_error:
221
+ raise AgentError(
222
+ f"{subject}: {self.name} failed: {msg.result or msg.subtype}"
223
+ )
224
+
225
+
226
+ class StructuredTask(Task[ResultT]):
227
+ """A Task whose result is the session's structured output.
228
+
229
+ Invalid output is retried in two layers:
230
+
231
+ - The CLI checks the output against the JSON schema and lets the agent retry
232
+ within the turn, up to 5 times by default (``MAX_STRUCTURED_OUTPUT_RETRIES``).
233
+ - Output that passes the schema but fails a Pydantic validator the schema
234
+ can't express (e.g. "this file exists") gets one follow-up turn asking for
235
+ a fix.
236
+ """
237
+
238
+ def result_server(self) -> McpServerConfig | None:
239
+ return None
240
+
241
+ def agent_options(self) -> ClaudeAgentOptions:
242
+ options = super().agent_options()
243
+ options.output_format = {
244
+ "type": "json_schema",
245
+ "schema": self.result_cls.model_json_schema(),
246
+ }
247
+ return options
248
+
249
+ def handle_result(self, msg: ResultMessage) -> ResultT:
250
+ try:
251
+ return self.result_cls.model_validate(msg.structured_output)
252
+ except ValidationError as exc:
253
+ raise RetryResultError(str(exc)) from exc
@@ -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,11 @@
1
+ autowebcompat_tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ autowebcompat_tools/amo.py,sha256=je70ekRHjiyGnEa8SBrXBzehRJHdq32r4FCSibZZVYY,1718
3
+ autowebcompat_tools/browser.py,sha256=22oLAm7_qQPrpNi4QmEU9_K8KG8e7qE-CGwglyt1u7E,8272
4
+ autowebcompat_tools/environment.py,sha256=1Bv4EC5r7y-v8_TNW3NuSSmvEiWm1EH26zicR6ULc6o,1174
5
+ autowebcompat_tools/inputs.py,sha256=0XLmnL4XRBT8L5VVeZlXIHMffSyA4_w7TuFz8L5Y66k,502
6
+ autowebcompat_tools/mcp_servers.py,sha256=oBeTlK6hYAGddx14Qk-CgKrIYrizk_dyW2uhBrU9Jyc,4310
7
+ autowebcompat_tools/result.py,sha256=0mWF0xVIOjKwpycfYOVOiH0RF4zVsK4XdMr7Usi8LQM,1874
8
+ autowebcompat_tools/task.py,sha256=TgUQEwz3f8K6vYOrmoLl-roj1EvmCDSu38MgrdQ4cOQ,8688
9
+ autowebcompat_tools-0.1.0.dist-info/METADATA,sha256=EwDeM7srBDu2KdPBDrlVP4w7PS20MXU9k7ejSrCftAY,455
10
+ autowebcompat_tools-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ autowebcompat_tools-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any