diff --git a/agents/autowebcompat-diagnosis/hackbot_agents/autowebcompat_diagnosis/broker.py b/agents/autowebcompat-diagnosis/hackbot_agents/autowebcompat_diagnosis/broker.py index ec97ae0f90c..6cc6323bf33 100644 --- a/agents/autowebcompat-diagnosis/hackbot_agents/autowebcompat_diagnosis/broker.py +++ b/agents/autowebcompat-diagnosis/hackbot_agents/autowebcompat_diagnosis/broker.py @@ -10,11 +10,11 @@ from contextlib import asynccontextmanager from typing import AsyncIterator -import bugsy import uvicorn from agent_tools import bugzilla from agent_tools.bugzilla import BugzillaContext from agent_tools.claude_sdk import build_sdk_server +from bugzilla_client import BugzillaClient, BugzillaSettings from mcp.server.streamable_http_manager import ( Receive, Scope, @@ -38,8 +38,10 @@ class BrokerInputs(BaseSettings): def build_app(inputs: BrokerInputs) -> Starlette: - client = bugsy.Bugsy( - api_key=inputs.bugzilla_api_key, bugzilla_url=inputs.bugzilla_api_url + client = BugzillaClient( + BugzillaSettings( + api_url=inputs.bugzilla_api_url, api_key=inputs.bugzilla_api_key + ) ) ctx = BugzillaContext(client=client) sdk_config = build_sdk_server("bugzilla", ctx, bugzilla.TOOLS) @@ -49,7 +51,7 @@ def build_app(inputs: BrokerInputs) -> Starlette: @asynccontextmanager async def lifespan(app: Starlette) -> AsyncIterator[None]: - async with manager.run(): + async with client, manager.run(): log.info( "bugzilla broker ready on %s:%d (read-only)", inputs.host, diff --git a/agents/autowebcompat-diagnosis/pyproject.toml b/agents/autowebcompat-diagnosis/pyproject.toml index 4ac3a316dbe..2664ce2620b 100644 --- a/agents/autowebcompat-diagnosis/pyproject.toml +++ b/agents/autowebcompat-diagnosis/pyproject.toml @@ -7,7 +7,7 @@ dependencies = [ "hackbot-runtime[claude-sdk]", "agent-tools[bugzilla]", "autowebcompat-tools", - "bugsy", + "bugzilla-client", "six", "claude-agent-sdk>=0.1.30", "mcp>=1.0.0", @@ -18,6 +18,7 @@ dependencies = [ [tool.uv.sources] hackbot-runtime = { workspace = true } agent-tools = { workspace = true } +bugzilla-client = { workspace = true } autowebcompat-tools = { workspace = true } [build-system] diff --git a/agents/autowebcompat-intervention/hackbot_agents/autowebcompat_intervention/broker.py b/agents/autowebcompat-intervention/hackbot_agents/autowebcompat_intervention/broker.py index 6394bc6b045..d3c69be8126 100644 --- a/agents/autowebcompat-intervention/hackbot_agents/autowebcompat_intervention/broker.py +++ b/agents/autowebcompat-intervention/hackbot_agents/autowebcompat_intervention/broker.py @@ -19,13 +19,13 @@ import logging from contextlib import asynccontextmanager -import bugsy import uvicorn from agent_tools import bugzilla from agent_tools import phabricator as phabricator_tools from agent_tools.bugzilla import BugzillaContext from agent_tools.claude_sdk import build_sdk_server from agent_tools.phabricator import PhabricatorContext +from bugzilla_client import BugzillaClient, BugzillaSettings from mcp.server.streamable_http_manager import StreamableHTTPSessionManager from phabricator_client import PhabricatorClient, PhabricatorSettings from phabricator_proxy import create_app as conduit_proxy @@ -60,8 +60,10 @@ async def handler(scope, receive, send): def build_app(inputs: BrokerInputs) -> Starlette: - client = bugsy.Bugsy( - api_key=inputs.bugzilla_api_key, bugzilla_url=inputs.bugzilla_api_url + client = BugzillaClient( + BugzillaSettings( + api_url=inputs.bugzilla_api_url, api_key=inputs.bugzilla_api_key + ) ) bugzilla_config = build_sdk_server( "bugzilla", BugzillaContext(client=client), bugzilla.TOOLS @@ -82,7 +84,7 @@ def build_app(inputs: BrokerInputs) -> Starlette: @asynccontextmanager async def lifespan(app): - async with bugzilla_manager.run(), phabricator_manager.run(): + async with client, bugzilla_manager.run(), phabricator_manager.run(): log.info( "broker ready on %s:%d (bugzilla + phabricator read-only, " "phabricator conduit proxy)", diff --git a/agents/autowebcompat-intervention/pyproject.toml b/agents/autowebcompat-intervention/pyproject.toml index 4a2bdc0e03e..9f4428db411 100644 --- a/agents/autowebcompat-intervention/pyproject.toml +++ b/agents/autowebcompat-intervention/pyproject.toml @@ -9,7 +9,7 @@ dependencies = [ "autowebcompat-tools", "phabricator-client", "phabricator-proxy", - "bugsy", + "bugzilla-client", "claude-agent-sdk>=0.2.165", "mcp>=1.0.0", "starlette>=0.36.0", @@ -22,6 +22,7 @@ dev = ["pytest>=8.0.0", "pytest-asyncio>=0.23.0"] [tool.uv.sources] hackbot-runtime = { workspace = true } agent-tools = { workspace = true } +bugzilla-client = { workspace = true } autowebcompat-tools = { workspace = true } phabricator-client = { workspace = true } phabricator-proxy = { workspace = true } diff --git a/agents/autowebcompat-repro/hackbot_agents/autowebcompat_repro/broker.py b/agents/autowebcompat-repro/hackbot_agents/autowebcompat_repro/broker.py index 2a17f77d157..d601311a5e1 100644 --- a/agents/autowebcompat-repro/hackbot_agents/autowebcompat_repro/broker.py +++ b/agents/autowebcompat-repro/hackbot_agents/autowebcompat_repro/broker.py @@ -10,11 +10,11 @@ from contextlib import asynccontextmanager from typing import AsyncIterator -import bugsy import uvicorn from agent_tools import bugzilla from agent_tools.bugzilla import BugzillaContext from agent_tools.claude_sdk import build_sdk_server +from bugzilla_client import BugzillaClient, BugzillaSettings from mcp.server.streamable_http_manager import ( Receive, Scope, @@ -38,8 +38,10 @@ class BrokerInputs(BaseSettings): def build_app(inputs: BrokerInputs) -> Starlette: - client = bugsy.Bugsy( - api_key=inputs.bugzilla_api_key, bugzilla_url=inputs.bugzilla_api_url + client = BugzillaClient( + BugzillaSettings( + api_url=inputs.bugzilla_api_url, api_key=inputs.bugzilla_api_key + ) ) ctx = BugzillaContext(client=client) sdk_config = build_sdk_server("bugzilla", ctx, bugzilla.TOOLS) @@ -49,7 +51,7 @@ def build_app(inputs: BrokerInputs) -> Starlette: @asynccontextmanager async def lifespan(app: Starlette) -> AsyncIterator[None]: - async with manager.run(): + async with client, manager.run(): log.info( "bugzilla broker ready on %s:%d (read-only)", inputs.host, diff --git a/agents/autowebcompat-repro/pyproject.toml b/agents/autowebcompat-repro/pyproject.toml index 357422d7bb7..00e949a14ed 100644 --- a/agents/autowebcompat-repro/pyproject.toml +++ b/agents/autowebcompat-repro/pyproject.toml @@ -7,7 +7,7 @@ dependencies = [ "hackbot-runtime[claude-sdk]", "agent-tools[bugzilla]", "autowebcompat-tools", - "bugsy", + "bugzilla-client", "six", "claude-agent-sdk>=0.1.30", "mcp>=1.0.0", @@ -18,6 +18,7 @@ dependencies = [ [tool.uv.sources] hackbot-runtime = { workspace = true } agent-tools = { workspace = true } +bugzilla-client = { workspace = true } autowebcompat-tools = { workspace = true } [build-system] diff --git a/agents/bug-fix/hackbot_agents/bug_fix/broker.py b/agents/bug-fix/hackbot_agents/bug_fix/broker.py index 4dd2c26e037..42e44139b7f 100644 --- a/agents/bug-fix/hackbot_agents/bug_fix/broker.py +++ b/agents/bug-fix/hackbot_agents/bug_fix/broker.py @@ -19,13 +19,13 @@ import logging from contextlib import asynccontextmanager -import bugsy import uvicorn from agent_tools import bugzilla from agent_tools import phabricator as phabricator_tools from agent_tools.bugzilla import BugzillaContext from agent_tools.claude_sdk import build_sdk_server from agent_tools.phabricator import PhabricatorContext +from bugzilla_client import BugzillaClient, BugzillaSettings from mcp.server.streamable_http_manager import StreamableHTTPSessionManager from phabricator_client import PhabricatorClient, PhabricatorSettings from phabricator_proxy import create_app as conduit_proxy @@ -60,8 +60,10 @@ async def handler(scope, receive, send): def build_app(inputs: BrokerInputs) -> Starlette: - client = bugsy.Bugsy( - api_key=inputs.bugzilla_api_key, bugzilla_url=inputs.bugzilla_api_url + client = BugzillaClient( + BugzillaSettings( + api_url=inputs.bugzilla_api_url, api_key=inputs.bugzilla_api_key + ) ) bugzilla_config = build_sdk_server( "bugzilla", BugzillaContext(client=client), bugzilla.TOOLS @@ -82,7 +84,7 @@ def build_app(inputs: BrokerInputs) -> Starlette: @asynccontextmanager async def lifespan(app): - async with bugzilla_manager.run(), phabricator_manager.run(): + async with client, bugzilla_manager.run(), phabricator_manager.run(): log.info( "broker ready on %s:%d (bugzilla + phabricator read-only, " "phabricator conduit proxy)", diff --git a/agents/bug-fix/pyproject.toml b/agents/bug-fix/pyproject.toml index 25630529856..965fc73830b 100644 --- a/agents/bug-fix/pyproject.toml +++ b/agents/bug-fix/pyproject.toml @@ -8,7 +8,7 @@ dependencies = [ "agent-tools[bugzilla,firefox]", "phabricator-client", "phabricator-proxy", - "bugsy", + "bugzilla-client", "claude-agent-sdk>=0.1.30", "mcp>=1.0.0", "starlette>=0.36.0", @@ -24,6 +24,7 @@ a11y = ["pygobject>=3.52"] [tool.uv.sources] hackbot-runtime = { workspace = true } agent-tools = { workspace = true } +bugzilla-client = { workspace = true } phabricator-client = { workspace = true } phabricator-proxy = { workspace = true } diff --git a/agents/bug-fix/tests/test_broker.py b/agents/bug-fix/tests/test_broker.py index 322237c75e6..52d2316d36e 100644 --- a/agents/bug-fix/tests/test_broker.py +++ b/agents/bug-fix/tests/test_broker.py @@ -19,7 +19,7 @@ def _app() -> Starlette: return broker.build_app( broker.BrokerInputs( bugzilla_api_url="https://bugzilla.example.com/rest", - bugzilla_api_key="bz-key", + bugzilla_api_key="a" * 40, phabricator=PhabricatorSettings( url="https://phab.example.com", api_key=VALID_TOKEN ), diff --git a/agents/build-repair/evals/eval.py b/agents/build-repair/evals/eval.py index 921ab12932b..7134b0c17dc 100644 --- a/agents/build-repair/evals/eval.py +++ b/agents/build-repair/evals/eval.py @@ -24,13 +24,13 @@ from functools import cached_property from pathlib import Path -import bugsy import weave from agent_tools import bugzilla from agent_tools.bugzilla import BugzillaContext from agent_tools.claude_sdk import build_sdk_server from agent_tools.firefox import FirefoxContext from agent_tools.firefox.tools.build_firefox import build_firefox +from bugzilla_client import BugzillaClient, BugzillaSettings from hackbot_agents.build_repair.agent import run_build_repair from hackbot_agents.build_repair.config import ANALYSIS_MODEL, FIX_MODEL @@ -66,11 +66,13 @@ def _bugzilla_server(): mcp_url = _broker_mcp_url() if mcp_url: return {"type": "http", "url": mcp_url} - client = bugsy.Bugsy( - bugzilla_url=os.environ.get( - "BUGZILLA_API_URL", "https://bugzilla.mozilla.org/rest" - ), - api_key=os.environ.get("BUGZILLA_API_KEY"), + client = BugzillaClient( + BugzillaSettings( + api_url=os.environ.get( + "BUGZILLA_API_URL", "https://bugzilla.mozilla.org/rest" + ), + api_key=os.environ.get("BUGZILLA_API_KEY"), + ) ) return build_sdk_server("bugzilla", BugzillaContext(client=client), bugzilla.TOOLS) diff --git a/agents/build-repair/hackbot_agents/build_repair/broker.py b/agents/build-repair/hackbot_agents/build_repair/broker.py index 70b275808b2..931fd802bc6 100644 --- a/agents/build-repair/hackbot_agents/build_repair/broker.py +++ b/agents/build-repair/hackbot_agents/build_repair/broker.py @@ -9,13 +9,12 @@ import logging from contextlib import asynccontextmanager -import bugsy import uvicorn from agent_tools import bugzilla from agent_tools.bugzilla import BugzillaContext from agent_tools.claude_sdk import build_sdk_server +from bugzilla_client import BugzillaClient, BugzillaSettings from mcp.server.streamable_http_manager import StreamableHTTPSessionManager -from pydantic import field_validator from pydantic_settings import BaseSettings, SettingsConfigDict from starlette.applications import Starlette from starlette.routing import Mount @@ -31,21 +30,12 @@ class BrokerInputs(BaseSettings): model_config = SettingsConfigDict(extra="ignore") - @field_validator("bugzilla_api_url") - @classmethod - def _ensure_rest_base(cls, v: str) -> str: - """Bugsy expects the REST base (``.../rest``) and just appends the path. - - A bare host like ``https://bugzilla.mozilla.org`` makes every call hit - the HTML site and fail to parse as JSON, so normalize it here. - """ - v = v.rstrip("/") - return v if v.endswith("/rest") else f"{v}/rest" - def build_app(inputs: BrokerInputs) -> Starlette: - client = bugsy.Bugsy( - api_key=inputs.bugzilla_api_key, bugzilla_url=inputs.bugzilla_api_url + client = BugzillaClient( + BugzillaSettings( + api_url=inputs.bugzilla_api_url, api_key=inputs.bugzilla_api_key + ) ) ctx = BugzillaContext(client=client) sdk_config = build_sdk_server("bugzilla", ctx, bugzilla.TOOLS) @@ -59,7 +49,7 @@ async def lifespan(app): # clear log line instead of an opaque JSON-decode error on every tool # call. We stay up regardless: the agent then gets a structured error. try: - version = client.request("version").get("version") + version = (await client.request("GET", "version")).get("version") log.info( "bugzilla reachable at %s (version %s)", inputs.bugzilla_api_url, @@ -71,7 +61,7 @@ async def lifespan(app): "and BUGZILLA_API_KEY; tool calls will fail until this is fixed", inputs.bugzilla_api_url, ) - async with manager.run(): + async with client, manager.run(): log.info( "bugzilla broker ready on %s:%d (read-only)", inputs.host, diff --git a/agents/build-repair/pyproject.toml b/agents/build-repair/pyproject.toml index f64839e969b..75eca7a9dd4 100644 --- a/agents/build-repair/pyproject.toml +++ b/agents/build-repair/pyproject.toml @@ -6,7 +6,7 @@ requires-python = ">=3.14" dependencies = [ "hackbot-runtime[claude-sdk,phabricator]", "agent-tools[bugzilla,firefox]", - "bugsy", + "bugzilla-client", "claude-agent-sdk>=0.2.165", "mcp>=1.0.0", "starlette>=0.36.0", @@ -24,6 +24,7 @@ eval = [ [tool.uv.sources] hackbot-runtime = { workspace = true } agent-tools = { workspace = true } +bugzilla-client = { workspace = true } [build-system] requires = ["hatchling"] diff --git a/agents/frontend-triage/hackbot_agents/frontend_triage/broker.py b/agents/frontend-triage/hackbot_agents/frontend_triage/broker.py index f10e69a6378..e3c49cd9fb2 100644 --- a/agents/frontend-triage/hackbot_agents/frontend_triage/broker.py +++ b/agents/frontend-triage/hackbot_agents/frontend_triage/broker.py @@ -9,11 +9,11 @@ import logging from contextlib import asynccontextmanager -import bugsy import uvicorn from agent_tools import bugzilla from agent_tools.bugzilla import BugzillaContext from agent_tools.claude_sdk import build_sdk_server +from bugzilla_client import BugzillaClient, BugzillaSettings from mcp.server.streamable_http_manager import StreamableHTTPSessionManager from pydantic_settings import BaseSettings, SettingsConfigDict from starlette.applications import Starlette @@ -32,8 +32,10 @@ class BrokerInputs(BaseSettings): def build_app(inputs: BrokerInputs) -> Starlette: - client = bugsy.Bugsy( - api_key=inputs.bugzilla_api_key, bugzilla_url=inputs.bugzilla_api_url + client = BugzillaClient( + BugzillaSettings( + api_url=inputs.bugzilla_api_url, api_key=inputs.bugzilla_api_key + ) ) ctx = BugzillaContext(client=client) sdk_config = build_sdk_server("bugzilla", ctx, bugzilla.TOOLS) @@ -43,7 +45,7 @@ def build_app(inputs: BrokerInputs) -> Starlette: @asynccontextmanager async def lifespan(app): - async with manager.run(): + async with client, manager.run(): log.info( "bugzilla broker ready on %s:%d (read-only)", inputs.host, diff --git a/agents/frontend-triage/pyproject.toml b/agents/frontend-triage/pyproject.toml index 7dc9650ae21..411da11a122 100644 --- a/agents/frontend-triage/pyproject.toml +++ b/agents/frontend-triage/pyproject.toml @@ -6,7 +6,7 @@ requires-python = ">=3.14" dependencies = [ "hackbot-runtime[claude-sdk]", "agent-tools[bugzilla,searchfox,vcs]", - "bugsy", + "bugzilla-client", "claude-agent-sdk>=0.2.165", "mcp>=1.0.0", "starlette>=0.36.0", @@ -19,6 +19,7 @@ dev = ["pytest>=8.0.0", "pytest-asyncio>=0.23.0"] [tool.uv.sources] hackbot-runtime = { workspace = true } agent-tools = { workspace = true } +bugzilla-client = { workspace = true } [build-system] requires = ["hatchling"] diff --git a/agents/gecko-triage/hackbot_agents/gecko_triage/broker.py b/agents/gecko-triage/hackbot_agents/gecko_triage/broker.py index 68a5b65193b..e5b8e7e0af9 100644 --- a/agents/gecko-triage/hackbot_agents/gecko_triage/broker.py +++ b/agents/gecko-triage/hackbot_agents/gecko_triage/broker.py @@ -6,27 +6,21 @@ Bugzilla credentials. The bot account reads only public bugs, so the broker does not filter what it serves. -bugsy blocks while it waits for Bugzilla, so the broker runs each tool call in a worker -thread: one slow read does not hold the reads of the other subagents. Each request also -has a timeout, so a request that hangs ends. +Each Bugzilla request has a timeout, so a request that hangs ends. `download_attachment` is left out: it would write the file inside this container. The agent reads an attachment with its own `fetch_attachment` tool. """ -import asyncio -import dataclasses -import functools import logging from contextlib import asynccontextmanager -import bugsy import uvicorn from agent_tools import bugzilla from agent_tools.bugzilla import BugzillaContext from agent_tools.claude_sdk import build_sdk_server +from bugzilla_client import BugzillaClient, BugzillaSettings from mcp.server.streamable_http_manager import StreamableHTTPSessionManager from pydantic_settings import BaseSettings, SettingsConfigDict -from requests.adapters import HTTPAdapter from starlette.applications import Starlette from starlette.routing import Mount @@ -36,21 +30,7 @@ BUGZILLA_TIMEOUT = 60 -def in_thread(handler): - """``handler`` run in a worker thread, with the same signature and so the same schema.""" - - @functools.wraps(handler) - async def run(ctx, **args): - return await asyncio.to_thread(asyncio.run, handler(ctx, **args)) - - return run - - -TOOLS = [ - dataclasses.replace(t, handler=in_thread(t.handler)) - for t in bugzilla.TOOLS - if t.name != "download_attachment" -] +TOOLS = [t for t in bugzilla.TOOLS if t.name != "download_attachment"] class BrokerInputs(BaseSettings): @@ -62,27 +42,21 @@ class BrokerInputs(BaseSettings): model_config = SettingsConfigDict(extra="ignore") -class TimeoutAdapter(HTTPAdapter): - """Gives `BUGZILLA_TIMEOUT` to each Bugzilla request that has no timeout.""" - - def send(self, request, timeout=None, **kwargs): - return super().send(request, timeout=timeout or BUGZILLA_TIMEOUT, **kwargs) - - def build_app(inputs: BrokerInputs) -> Starlette: - client = bugsy.Bugsy( - api_key=inputs.bugzilla_api_key, bugzilla_url=inputs.bugzilla_api_url + client = BugzillaClient( + BugzillaSettings( + api_url=inputs.bugzilla_api_url, + api_key=inputs.bugzilla_api_key, + timeout_seconds=BUGZILLA_TIMEOUT, + ) ) - adapter = TimeoutAdapter() - client.session.mount("https://", adapter) - client.session.mount("http://", adapter) ctx = BugzillaContext(client=client) sdk_config = build_sdk_server("bugzilla", ctx, TOOLS) manager = StreamableHTTPSessionManager(app=sdk_config["instance"], stateless=True) @asynccontextmanager async def lifespan(app): - async with manager.run(): + async with client, manager.run(): log.info( "bugzilla broker ready on %s:%d (read-only)", inputs.host, inputs.port ) diff --git a/agents/gecko-triage/pyproject.toml b/agents/gecko-triage/pyproject.toml index 052aa61ebcc..3b677634a60 100644 --- a/agents/gecko-triage/pyproject.toml +++ b/agents/gecko-triage/pyproject.toml @@ -6,7 +6,7 @@ requires-python = ">=3.14" dependencies = [ "hackbot-runtime[claude-sdk]", "agent-tools[bugzilla,searchfox,vcs]", - "bugsy", + "bugzilla-client", "claude-agent-sdk>=0.2.165", "jinja2>=3.1", "mcp>=1.0.0", @@ -20,6 +20,7 @@ dev = ["pytest>=8.0.0", "pytest-asyncio>=0.23.0"] [tool.uv.sources] hackbot-runtime = { workspace = true } agent-tools = { workspace = true } +bugzilla-client = { workspace = true } [build-system] requires = ["hatchling"] diff --git a/agents/gecko-triage/tests/test_broker.py b/agents/gecko-triage/tests/test_broker.py index 84a896beee3..1200b3cd8e0 100644 --- a/agents/gecko-triage/tests/test_broker.py +++ b/agents/gecko-triage/tests/test_broker.py @@ -1,8 +1,5 @@ """Tests for the Bugzilla broker, which serves the agent-tools Bugzilla tools.""" -import asyncio -import threading - from agent_tools import bugzilla from hackbot_agents.gecko_triage import broker @@ -20,30 +17,27 @@ def fake_build(name, ctx, tools): served.update(name=name, ctx=ctx, tools=tools) return {"instance": object()} + settings = [] + real_settings = broker.BugzillaSettings + + def record_settings(**kwargs): + settings.append(real_settings(**kwargs)) + return settings[-1] + monkeypatch.setattr(broker, "build_sdk_server", fake_build) + monkeypatch.setattr(broker, "BugzillaSettings", record_settings) app = broker.build_app( broker.BrokerInputs( bugzilla_api_url="https://bugzilla.example.com/rest", - bugzilla_api_key="bz-key", + bugzilla_api_key="a" * 40, ) ) assert [r.path for r in app.routes] == ["/mcp"] assert served["name"] == "bugzilla" assert served["tools"] == broker.TOOLS - session = served["ctx"].client.session - for url in ("https://bugzilla.example.com/rest/bug", "http://localhost/rest"): - assert isinstance(session.get_adapter(url), broker.TimeoutAdapter), url - - -def test_a_request_with_no_timeout_gets_the_broker_timeout(monkeypatch): - sent = [] - monkeypatch.setattr( - broker.HTTPAdapter, "send", lambda self, request, **kw: sent.append(kw) - ) - adapter = broker.TimeoutAdapter() - adapter.send("request") - adapter.send("request", timeout=5) - assert [kw["timeout"] for kw in sent] == [broker.BUGZILLA_TIMEOUT, 5] + (used,) = settings + assert used.api_url == "https://bugzilla.example.com/rest" + assert used.timeout_seconds == broker.BUGZILLA_TIMEOUT def test_the_tools_keep_their_schema(): @@ -51,34 +45,3 @@ def test_the_tools_keep_their_schema(): for t in broker.TOOLS: assert t.input_schema == plain[t.name].input_schema, t.name assert t.description == plain[t.name].description, t.name - - -async def test_a_tool_call_runs_in_a_worker_thread(): - # bugsy blocks while it waits, so a call must not hold the broker's event loop. - seen = [] - - async def handler(ctx, bug_id: int): - seen.append( - (threading.current_thread() is threading.main_thread(), ctx, bug_id) - ) - return {"bug_id": bug_id} - - assert await broker.in_thread(handler)("ctx", bug_id=7) == {"bug_id": 7} - assert seen == [(False, "ctx", 7)] - - -async def test_a_slow_call_does_not_stop_another_call(): - gate = threading.Event() - - async def slow(ctx): - gate.wait(5) - return "slow" - - async def fast(ctx): - gate.set() - return "fast" - - results = await asyncio.gather( - broker.in_thread(slow)(None), broker.in_thread(fast)(None) - ) - assert results == ["slow", "fast"] diff --git a/libs/agent-tools/agent_tools/bugzilla.py b/libs/agent-tools/agent_tools/bugzilla.py index f08e52c4481..7c5ff0c1666 100644 --- a/libs/agent-tools/agent_tools/bugzilla.py +++ b/libs/agent-tools/agent_tools/bugzilla.py @@ -1,4 +1,4 @@ -"""Read-only Bugzilla tools backed by bugsy. +"""Read-only Bugzilla tools backed by ``bugzilla_client``. Framework-neutral: each tool is a ``@tool``-decorated handler whose first parameter is a :class:`BugzillaContext`. Handlers return plain data and surface @@ -7,12 +7,14 @@ """ import base64 +import functools import mimetypes +from collections.abc import Awaitable, Callable from dataclasses import dataclass from pathlib import PurePosixPath from typing import Annotated, Any -import bugsy +from bugzilla_client import BugzillaClient, BugzillaError from pydantic import Field from agent_tools.registry import ToolError, tool, tools_in @@ -175,63 +177,60 @@ def _type_not_allowed_error( @dataclass class BugzillaContext: - """Holds the live bugsy client. + """Holds the live Bugzilla client. Every tool receives the same instance, so they share auth and one TCP connection pool. """ - client: bugsy.Bugsy + client: BugzillaClient -def _bugsy_error(e: bugsy.BugsyException) -> ToolError: - """Turn a bugsy exception into a structured ToolError. +def _to_tool_error(e: Exception) -> ToolError: + """Turn a failed Bugzilla call into a structured ToolError. The payload is friendly and machine-parseable so the agent can decide what to do (skip the bug, try a different endpoint, ...) rather than just seeing - a stack trace. + a stack trace. The client raises ``BugzillaError`` for Bugzilla-level errors + and non-JSON answers; a network failure surfaces as an ``httpx`` error. """ - code = getattr(e, "code", None) - msg = getattr(e, "msg", str(e)) - if code == 101: - kind = "endpoint_not_exposed" - hint = "This Bugzilla proxy does not expose this endpoint." - elif code == 102: - kind = "access_denied" - hint = "Your API key cannot access this bug. Skip it." - else: - kind = "bugzilla_error" - hint = None - payload: dict[str, Any] = {"error": kind, "code": code, "message": msg} - if hint: - payload["hint"] = hint - return ToolError(msg, payload=payload) - - -def _request(ctx: BugzillaContext, path: str, params: dict[str, Any] | None = None): - """Issue a Bugzilla request, normalizing every failure into a ToolError. - - bugsy only raises ``BugsyException`` for Bugzilla-level errors; a bad proxy - URL, an auth redirect, or an empty body instead surfaces as a raw - ``JSONDecodeError``/connection error. Catching those here turns an opaque - "Expecting value: line 1 column 1" into an actionable message. - """ - try: - return ctx.client.request(path, params=params or {}) - except bugsy.BugsyException as e: - raise _bugsy_error(e) from e - except Exception as e: - raise ToolError( - f"Bugzilla request to '{path}' failed: {type(e).__name__}: {e}", - payload={ - "error": "bugzilla_request_failed", - "path": path, - "message": str(e), - }, - ) from e + if isinstance(e, BugzillaError): + if e.code == 101: + kind = "endpoint_not_exposed" + hint = "This Bugzilla proxy does not expose this endpoint." + elif e.code == 102: + kind = "access_denied" + hint = "Your API key cannot access this bug. Skip it." + else: + kind = "bugzilla_error" + hint = None + payload: dict[str, Any] = {"error": kind, "code": e.code, "message": e.message} + if hint: + payload["hint"] = hint + return ToolError(e.message, payload=payload) + return ToolError( + f"Bugzilla request failed: {type(e).__name__}: {e}", + payload={"error": "bugzilla_request_failed", "message": str(e)}, + ) + + +def _bugzilla_errors(fn: Callable[..., Awaitable]) -> Callable[..., Awaitable]: + """Let a tool call the client directly and still fail with a ToolError.""" + + @functools.wraps(fn) + async def wrapper(*args, **kwargs): + try: + return await fn(*args, **kwargs) + except ToolError: + raise + except Exception as e: + raise _to_tool_error(e) from e + + return wrapper @tool +@_bugzilla_errors async def search_bugs( ctx: BugzillaContext, params: Annotated[ @@ -255,12 +254,13 @@ async def search_bugs( component, status, resolution, priority, severity, assigned_to, whiteboard, include_fields, limit. """ - result = _request(ctx, "bug", params) + result = (await ctx.client.bugs.search(params)).data bugs = result.get("bugs", []) return {"count": len(bugs), "bugs": bugs} @tool +@_bugzilla_errors async def get_bugs( ctx: BugzillaContext, ids: Annotated[list[int], Field(description="Bug IDs to fetch.")], @@ -298,8 +298,7 @@ async def get_bugs( "creation_time,last_change_time,blocks,depends_on,see_also," "cf_crash_signature,url,version,op_sys,platform" ) - id_csv = ",".join(str(i) for i in ids) - result = _request(ctx, "bug", {"id": id_csv, "include_fields": include}) + result = (await ctx.client.bugs.get(ids, include_fields=include.split(","))).data bugs = result.get("bugs", []) returned = {b["id"] for b in bugs} inaccessible = [i for i in ids if i not in returned] @@ -307,22 +306,16 @@ async def get_bugs( payload = {"count": len(bugs), "bugs": bugs, "inaccessible": inaccessible} if include_comments and bugs: - # Bugzilla lets us fetch comments for many bugs in one call by hitting - # /bug/{first}/comment?ids=rest. One extra round trip total. - first, *rest = [b["id"] for b in bugs] - cparams = {"ids": ",".join(str(i) for i in rest)} if rest else {} + # Comments for all the bugs come back in one extra round trip total. try: - cres = ctx.client.request(f"bug/{first}/comment", params=cparams) + cres = (await ctx.client.comments.get(bug_ids=[b["id"] for b in bugs])).data comments_by_bug = { int(bid): data["comments"] for bid, data in cres.get("bugs", {}).items() } for b in bugs: b["comments"] = comments_by_bug.get(b["id"], []) - except bugsy.BugsyException as e: - payload["comments_error"] = { - "code": getattr(e, "code", None), - "message": getattr(e, "msg", str(e)), - } + except BugzillaError as e: + payload["comments_error"] = {"code": e.code, "message": e.message} except Exception as e: payload["comments_error"] = {"message": f"{type(e).__name__}: {e}"} @@ -330,6 +323,7 @@ async def get_bugs( @tool +@_bugzilla_errors async def get_bug_comments( ctx: BugzillaContext, bug_id: Annotated[int, Field(description="Bug ID.")], @@ -360,7 +354,7 @@ async def get_bug_comments( `total` is the number of comments. `next_start` is the `start` of the next page, and null on the last page. """ - result = _request(ctx, f"bug/{bug_id}/comment") + result = (await ctx.client.comments.get(bug_ids=[bug_id])).data comments = result.get("bugs", {}).get(str(bug_id), {}).get("comments", []) later = [c for c in comments if c.get("count", 0) >= start] page = later if limit is None else later[:limit] @@ -376,6 +370,7 @@ async def get_bug_comments( @tool +@_bugzilla_errors async def get_bug_history( ctx: BugzillaContext, bug_id: Annotated[int, Field(description="Bug ID.")], @@ -390,12 +385,13 @@ async def get_bug_history( and `removed`. """ params = {"new_since": new_since} if new_since else {} - result = _request(ctx, f"bug/{bug_id}/history", params) + result = await ctx.client.request("GET", f"bug/{bug_id}/history", params=params) history = (result.get("bugs") or [{}])[0].get("history") or [] return {"bug_id": bug_id, "count": len(history), "history": history} @tool +@_bugzilla_errors async def get_bug_attachments( ctx: BugzillaContext, bug_id: Annotated[int, Field(description="Bug ID.")], @@ -424,7 +420,7 @@ async def get_bug_attachments( refuses gets a 'data_error' and does not take the rest of the response with it. """ - result = _request(ctx, f"bug/{bug_id}/attachment", {"exclude_fields": "data"}) + result = (await ctx.client.attachments.get(bug_ids=[bug_id])).data atts = result.get("bugs", {}).get(str(bug_id), []) payload = {"bug_id": bug_id, "count": len(atts), "attachments": atts} if not include_data: @@ -460,9 +456,13 @@ async def get_bug_attachments( ) else: try: - one = _request(ctx, f"bug/attachment/{att['id']}") - except ToolError as e: - att["data_error"] = e.payload or {"message": str(e)} + one = ( + await ctx.client.attachments.get( + attachment_ids=[att["id"]], include_data=True + ) + ).data + except Exception as e: + att["data_error"] = _to_tool_error(e).payload errors += 1 continue fetched = one.get("attachments", {}).get(str(att["id"])) @@ -483,6 +483,7 @@ async def get_bug_attachments( @tool +@_bugzilla_errors async def download_attachment( ctx: BugzillaContext, attachment_id: Annotated[ @@ -511,7 +512,7 @@ async def download_attachment( """ # Metadata first, so a refused attachment's bytes never leave Bugzilla. One # extra round trip on the happy path buys that. - meta = _request(ctx, f"bug/attachment/{attachment_id}", {"exclude_fields": "data"}) + meta = (await ctx.client.attachments.get(attachment_ids=[attachment_id])).data att = meta.get("attachments", {}).get(str(attachment_id)) if att is None: @@ -524,7 +525,11 @@ async def download_attachment( if not allowed: raise _type_not_allowed_error(attachment_id, att, effective) - full = _request(ctx, f"bug/attachment/{attachment_id}") + full = ( + await ctx.client.attachments.get( + attachment_ids=[attachment_id], include_data=True + ) + ).data data = full.get("attachments", {}).get(str(attachment_id), {}).get("data") if data is None: raise ToolError( diff --git a/libs/agent-tools/pyproject.toml b/libs/agent-tools/pyproject.toml index 39daf14c02a..e2770c6502d 100644 --- a/libs/agent-tools/pyproject.toml +++ b/libs/agent-tools/pyproject.toml @@ -8,17 +8,15 @@ dependencies = [ ] [project.optional-dependencies] -bugzilla = [ - "bugsy", - # Workaround: bugsy imports six at runtime but doesn't declare it as a - # dependency (its setup.py only lists requests). - "six", -] +bugzilla = ["bugzilla-client"] firefox = ["grizzly-framework", "prefpicker"] claude-sdk = ["claude-agent-sdk>=0.1.30"] searchfox = ["searchfox>=0.20.3"] vcs = ["httpx"] +[tool.uv.sources] +bugzilla-client = { workspace = true } + [build-system] requires = ["hatchling"] build-backend = "hatchling.build" diff --git a/libs/agent-tools/tests/test_bugzilla.py b/libs/agent-tools/tests/test_bugzilla.py index 284fa9f1e53..25486cf4e7f 100644 --- a/libs/agent-tools/tests/test_bugzilla.py +++ b/libs/agent-tools/tests/test_bugzilla.py @@ -2,14 +2,54 @@ from unittest.mock import MagicMock -import bugsy +import httpx import pytest from agent_tools import bugzilla from agent_tools.bugzilla import BugzillaContext from agent_tools.claude_sdk import build_sdk_server from agent_tools.registry import ToolError +from bugzilla_client import BugzillaClient, BugzillaSettings from mcp.types import ListToolsRequest +_RealAsyncClient = httpx.AsyncClient + +# What Bugzilla answers when the API key cannot see a bug. +ACCESS_DENIED = httpx.Response( + 401, json={"error": True, "code": 102, "message": "nope"} +) + + +@pytest.fixture +async def bugzilla_ctx(monkeypatch): + """Build a context whose Bugzilla requests are answered by ``handler``. + + ``handler(path, params)`` gets the path relative to ``/rest/``. Returns the + context and the ``(path, params)`` pairs it sent, so a test can assert what + was and was not fetched. + """ + clients: list[BugzillaClient] = [] + + def make(handler): + calls = [] + + def record(request: httpx.Request) -> httpx.Response: + path = request.url.path.removeprefix("/rest/") + calls.append((path, dict(request.url.params))) + return handler(path, request.url.params) + + monkeypatch.setattr( + httpx, + "AsyncClient", + lambda **kw: _RealAsyncClient(transport=httpx.MockTransport(record), **kw), + ) + client = BugzillaClient(BugzillaSettings(api_key="a" * 40)) + clients.append(client) + return BugzillaContext(client=client), calls + + yield make + for client in clients: + await client.close() + async def _list(server): return ( @@ -35,54 +75,39 @@ async def test_exposes_read_only_tools(): } -async def test_search_bugs_returns_data(): - client = MagicMock() - client.request.return_value = {"bugs": [{"id": 1}, {"id": 2}]} - result = await bugzilla.search_bugs( - BugzillaContext(client=client), params={"id": "1,2"} +async def test_search_bugs_returns_data(bugzilla_ctx): + ctx, calls = bugzilla_ctx( + lambda path, params: httpx.Response(200, json={"bugs": [{"id": 1}, {"id": 2}]}) ) + result = await bugzilla.search_bugs(ctx, params={"id": "1,2"}) assert result == {"count": 2, "bugs": [{"id": 1}, {"id": 2}]} + assert calls == [("bug", {"id": "1,2"})] -async def test_search_bugs_raises_tool_error_on_bugsy_failure(): - import bugsy - - client = MagicMock() - err = bugsy.BugsyException("nope") - err.code = 102 - client.request.side_effect = err +async def test_search_bugs_raises_tool_error_on_bugzilla_failure(bugzilla_ctx): + ctx, _ = bugzilla_ctx(lambda path, params: ACCESS_DENIED) with pytest.raises(ToolError) as ei: - await bugzilla.search_bugs(BugzillaContext(client=client), params={}) + await bugzilla.search_bugs(ctx, params={}) assert ei.value.payload["error"] == "access_denied" -def _attachment_client(att, *, data="aGVsbG8="): - """A bugsy client that serves one attachment, with and without its data. +def _attachment_ctx(bugzilla_ctx, att, *, data="aGVsbG8="): + """A context whose Bugzilla serves one attachment, with and without its data. Mirrors Bugzilla: `exclude_fields=data` returns the metadata only, and the - unqualified request returns the same record plus base64 `data`. Records every - (path, params) pair so a test can assert what was and was not fetched. + unqualified request returns the same record plus base64 `data`. """ - client = MagicMock() - calls = [] - def request(path, params=None): - params = params or {} - calls.append((path, params)) - if path.endswith("/attachment"): - body = ( - dict(att) - if params.get("exclude_fields") == "data" - else {**att, "data": data} - ) - return {"bugs": {"1": [body]}} + def handler(path, params): if params.get("exclude_fields") == "data": - return {"attachments": {str(att["id"]): dict(att)}} - return {"attachments": {str(att["id"]): {**att, "data": data}}} + body = dict(att) + else: + body = {**att, "data": data} + if path.endswith("/attachment"): + return httpx.Response(200, json={"bugs": {"1": [body]}}) + return httpx.Response(200, json={"attachments": {str(att["id"]): body}}) - client.request.side_effect = request - client.calls = calls - return client + return bugzilla_ctx(handler) def _att(**overrides): @@ -90,26 +115,26 @@ def _att(**overrides): return {**base, **overrides} -async def test_download_attachment_writes_allowed_image(tmp_path): - client = _attachment_client(_att()) +async def test_download_attachment_writes_allowed_image(bugzilla_ctx, tmp_path): + ctx, calls = _attachment_ctx(bugzilla_ctx, _att()) dest = tmp_path / "shot.png" result = await bugzilla.download_attachment( - BugzillaContext(client=client), attachment_id=7, dest_path=str(dest) + ctx, attachment_id=7, dest_path=str(dest) ) assert dest.read_bytes() == b"hello" assert result["content_type"] == "image/png" assert result["size_bytes"] == 5 # Metadata is probed before the bytes are asked for. - assert client.calls[0] == ("bug/attachment/7", {"exclude_fields": "data"}) - assert client.calls[1] == ("bug/attachment/7", {}) + assert calls[0] == ("bug/attachment/7", {"exclude_fields": "data"}) + assert calls[1] == ("bug/attachment/7", {}) -async def test_download_attachment_writes_allowed_text(tmp_path): - client = _attachment_client(_att(file_name="update.log", content_type="text/x-log")) - dest = tmp_path / "update.log" - await bugzilla.download_attachment( - BugzillaContext(client=client), attachment_id=7, dest_path=str(dest) +async def test_download_attachment_writes_allowed_text(bugzilla_ctx, tmp_path): + ctx, _ = _attachment_ctx( + bugzilla_ctx, _att(file_name="update.log", content_type="text/x-log") ) + dest = tmp_path / "update.log" + await bugzilla.download_attachment(ctx, attachment_id=7, dest_path=str(dest)) assert dest.read_bytes() == b"hello" @@ -124,17 +149,17 @@ async def test_download_attachment_writes_allowed_text(tmp_path): ], ids=["mp4", "zip", "webm", "empty-type", "no-type"], ) -async def test_download_attachment_refuses_unreadable_types(tmp_path, att): - client = _attachment_client(att) +async def test_download_attachment_refuses_unreadable_types( + bugzilla_ctx, tmp_path, att +): + ctx, calls = _attachment_ctx(bugzilla_ctx, att) dest = tmp_path / "out.bin" with pytest.raises(ToolError) as ei: - await bugzilla.download_attachment( - BugzillaContext(client=client), attachment_id=7, dest_path=str(dest) - ) + await bugzilla.download_attachment(ctx, attachment_id=7, dest_path=str(dest)) assert ei.value.payload["error"] == "attachment_type_not_allowed" assert not dest.exists() # The refusal costs one metadata request; the bytes are never fetched. - assert client.calls == [("bug/attachment/7", {"exclude_fields": "data"})] + assert calls == [("bug/attachment/7", {"exclude_fields": "data"})] @pytest.mark.parametrize( @@ -148,13 +173,15 @@ async def test_download_attachment_refuses_unreadable_types(tmp_path, att): ("trace", False), ], ) -async def test_octet_stream_resolves_by_file_name(tmp_path, file_name, allowed): +async def test_octet_stream_resolves_by_file_name( + bugzilla_ctx, tmp_path, file_name, allowed +): """Bugzilla's fallback type covers both plain logs and untyped screencasts.""" - client = _attachment_client( - _att(file_name=file_name, content_type="application/octet-stream") + ctx, _ = _attachment_ctx( + bugzilla_ctx, + _att(file_name=file_name, content_type="application/octet-stream"), ) dest = tmp_path / "out.bin" - ctx = BugzillaContext(client=client) if allowed: await bugzilla.download_attachment(ctx, attachment_id=7, dest_path=str(dest)) assert dest.read_bytes() == b"hello" @@ -166,87 +193,75 @@ async def test_octet_stream_resolves_by_file_name(tmp_path, file_name, allowed): assert ei.value.payload["error"] == "attachment_type_not_allowed" -async def test_is_patch_overrides_an_odd_content_type(tmp_path): +async def test_is_patch_overrides_an_odd_content_type(bugzilla_ctx, tmp_path): """A patch is text even when the uploader typed it as something else.""" - client = _attachment_client( + ctx, _ = _attachment_ctx( + bugzilla_ctx, _att( file_name="fix.patch", content_type="application/octet-stream", is_patch=True, - ) + ), ) dest = tmp_path / "fix.patch" - await bugzilla.download_attachment( - BugzillaContext(client=client), attachment_id=7, dest_path=str(dest) - ) + await bugzilla.download_attachment(ctx, attachment_id=7, dest_path=str(dest)) assert dest.read_bytes() == b"hello" -async def test_content_type_parameters_and_case_are_ignored(tmp_path): - client = _attachment_client( - _att(file_name="steps.txt", content_type="TEXT/PLAIN; charset=UTF-8") +async def test_content_type_parameters_and_case_are_ignored(bugzilla_ctx, tmp_path): + ctx, _ = _attachment_ctx( + bugzilla_ctx, + _att(file_name="steps.txt", content_type="TEXT/PLAIN; charset=UTF-8"), ) dest = tmp_path / "steps.txt" - await bugzilla.download_attachment( - BugzillaContext(client=client), attachment_id=7, dest_path=str(dest) - ) + await bugzilla.download_attachment(ctx, attachment_id=7, dest_path=str(dest)) assert dest.read_bytes() == b"hello" -async def test_download_attachment_not_found(): - client = MagicMock() - client.request.return_value = {"attachments": {}} +async def test_download_attachment_not_found(bugzilla_ctx): + ctx, _ = bugzilla_ctx( + lambda path, params: httpx.Response(200, json={"attachments": {}}) + ) with pytest.raises(ToolError) as ei: - await bugzilla.download_attachment( - BugzillaContext(client=client), attachment_id=7, dest_path="/tmp/x" - ) + await bugzilla.download_attachment(ctx, attachment_id=7, dest_path="/tmp/x") assert ei.value.payload["error"] == "attachment_not_found" -async def test_get_bug_attachments_metadata_only_never_asks_for_data(): - client = _attachment_client(_att()) - result = await bugzilla.get_bug_attachments( - BugzillaContext(client=client), bug_id=1 - ) +async def test_get_bug_attachments_metadata_only_never_asks_for_data(bugzilla_ctx): + ctx, calls = _attachment_ctx(bugzilla_ctx, _att()) + result = await bugzilla.get_bug_attachments(ctx, bug_id=1) assert result["count"] == 1 assert "data" not in result["attachments"][0] - assert client.calls == [("bug/1/attachment", {"exclude_fields": "data"})] + assert calls == [("bug/1/attachment", {"exclude_fields": "data"})] -def _list_client(atts, *, data="aGVsbG8=", fail_ids=()): - """A client serving an attachment list, then per-attachment data on demand. +def _list_ctx(bugzilla_ctx, atts, *, data="aGVsbG8=", fail_ids=()): + """A context serving an attachment list, then per-attachment data on demand. - `fail_ids` makes those attachment IDs raise the way the proxy does for a bug + `fail_ids` makes those attachment IDs fail the way the proxy does for a bug the API key cannot reach. """ - client = MagicMock() - calls = [] - def request(path, params=None): - calls.append((path, params or {})) + def handler(path, params): if path == "bug/1/attachment": - return {"bugs": {"1": [dict(a) for a in atts]}} + return httpx.Response(200, json={"bugs": {"1": [dict(a) for a in atts]}}) att_id = path.rsplit("/", 1)[1] if int(att_id) in fail_ids: - err = bugsy.BugsyException("nope") - err.code = 102 - raise err + return ACCESS_DENIED source = next(a for a in atts if str(a["id"]) == att_id) - return {"attachments": {att_id: {**source, "data": data}}} + return httpx.Response( + 200, json={"attachments": {att_id: {**source, "data": data}}} + ) - client.request.side_effect = request - client.calls = calls - return client + return bugzilla_ctx(handler) -async def test_get_bug_attachments_inlines_text_and_refuses_video(): +async def test_get_bug_attachments_inlines_text_and_refuses_video(bugzilla_ctx): log = {"id": 7, "file_name": "update.log", "content_type": "text/plain"} mp4 = {"id": 8, "file_name": "screencast.mp4", "content_type": "video/mp4"} - client = _list_client([log, mp4]) + ctx, calls = _list_ctx(bugzilla_ctx, [log, mp4]) - result = await bugzilla.get_bug_attachments( - BugzillaContext(client=client), bug_id=1, include_data=True - ) + result = await bugzilla.get_bug_attachments(ctx, bug_id=1, include_data=True) by_id = {a["id"]: a for a in result["attachments"]} assert by_id[7]["data"] == "aGVsbG8=" @@ -254,13 +269,15 @@ async def test_get_bug_attachments_inlines_text_and_refuses_video(): assert "video/mp4" in by_id[8]["data_omitted"] assert (result["inlined_count"], result["omitted_count"]) == (1, 1) # The video is never fetched: one list call plus one fetch for the log. - assert client.calls == [ + assert calls == [ ("bug/1/attachment", {"exclude_fields": "data"}), ("bug/attachment/7", {}), ] -async def test_get_bug_attachments_does_not_inline_binary_it_would_still_download(): +async def test_get_bug_attachments_does_not_inline_binary_it_would_still_download( + bugzilla_ctx, +): """A tool result is text, so a base64 png is a long string, not an image block. download_attachment plus Read is the only path that reaches the model as an @@ -269,11 +286,9 @@ async def test_get_bug_attachments_does_not_inline_binary_it_would_still_downloa png = {"id": 7, "file_name": "shot.png", "content_type": "image/png"} pdf = {"id": 8, "file_name": "report.pdf", "content_type": "application/pdf"} svg = {"id": 9, "file_name": "case.svg", "content_type": "image/svg+xml"} - client = _list_client([png, pdf, svg]) + ctx, calls = _list_ctx(bugzilla_ctx, [png, pdf, svg]) - result = await bugzilla.get_bug_attachments( - BugzillaContext(client=client), bug_id=1, include_data=True - ) + result = await bugzilla.get_bug_attachments(ctx, bug_id=1, include_data=True) by_id = {a["id"]: a for a in result["attachments"]} for att_id in (7, 8): @@ -282,15 +297,17 @@ async def test_get_bug_attachments_does_not_inline_binary_it_would_still_downloa # SVG is markup, so the text is the content. assert by_id[9]["data"] == "aGVsbG8=" assert (result["inlined_count"], result["omitted_count"]) == (1, 2) - assert ("bug/attachment/7", {}) not in client.calls - assert ("bug/attachment/8", {}) not in client.calls + assert ("bug/attachment/7", {}) not in calls + assert ("bug/attachment/8", {}) not in calls # Still downloadable to disk, where size does not cost context. assert bugzilla.attachment_type_allowed(png) == (True, "image/png") assert bugzilla.attachment_type_allowed(pdf) == (True, "application/pdf") -async def test_get_bug_attachments_skips_text_over_the_inline_size_limit(): +async def test_get_bug_attachments_skips_text_over_the_inline_size_limit( + bugzilla_ctx, +): big = { "id": 7, "file_name": "huge.log", @@ -303,29 +320,25 @@ async def test_get_bug_attachments_skips_text_over_the_inline_size_limit(): "content_type": "text/plain", "size": bugzilla.MAX_INLINE_BYTES, } - client = _list_client([big, small]) + ctx, calls = _list_ctx(bugzilla_ctx, [big, small]) - result = await bugzilla.get_bug_attachments( - BugzillaContext(client=client), bug_id=1, include_data=True - ) + result = await bugzilla.get_bug_attachments(ctx, bug_id=1, include_data=True) by_id = {a["id"]: a for a in result["attachments"]} assert "data" not in by_id[7] assert "inline limit" in by_id[7]["data_omitted"] assert by_id[8]["data"] == "aGVsbG8=" - assert ("bug/attachment/7", {}) not in client.calls + assert ("bug/attachment/7", {}) not in calls -async def test_get_bug_attachments_caps_the_number_it_inlines(): +async def test_get_bug_attachments_caps_the_number_it_inlines(bugzilla_ctx): atts = [ {"id": i, "file_name": f"{i}.log", "content_type": "text/plain"} for i in range(1, bugzilla.MAX_INLINE_ATTACHMENTS + 4) ] - client = _list_client(atts) + ctx, _ = _list_ctx(bugzilla_ctx, atts) - result = await bugzilla.get_bug_attachments( - BugzillaContext(client=client), bug_id=1, include_data=True - ) + result = await bugzilla.get_bug_attachments(ctx, bug_id=1, include_data=True) assert result["inlined_count"] == bugzilla.MAX_INLINE_ATTACHMENTS assert result["omitted_count"] == 3 @@ -335,7 +348,9 @@ async def test_get_bug_attachments_caps_the_number_it_inlines(): assert all("only the first" in a["data_omitted"] for a in over) -async def test_get_bug_attachments_one_failure_does_not_discard_the_rest(): +async def test_get_bug_attachments_one_failure_does_not_discard_the_rest( + bugzilla_ctx, +): """Before the per-attachment loop this was one request that could not fail partway. A raise from the loop would throw away everything already fetched, so an @@ -344,11 +359,9 @@ async def test_get_bug_attachments_one_failure_does_not_discard_the_rest(): a = {"id": 7, "file_name": "a.log", "content_type": "text/plain"} b = {"id": 8, "file_name": "b.log", "content_type": "text/plain"} c = {"id": 9, "file_name": "c.log", "content_type": "text/plain"} - client = _list_client([a, b, c], fail_ids=(8,)) + ctx, _ = _list_ctx(bugzilla_ctx, [a, b, c], fail_ids=(8,)) - result = await bugzilla.get_bug_attachments( - BugzillaContext(client=client), bug_id=1, include_data=True - ) + result = await bugzilla.get_bug_attachments(ctx, bug_id=1, include_data=True) by_id = {x["id"]: x for x in result["attachments"]} assert by_id[7]["data"] == "aGVsbG8=" @@ -386,10 +399,13 @@ def boom(*args, **kwargs): THREAD = [{"id": 50 + n, "count": n, "text": f"c{n}"} for n in (0, 1, 3, 4, 5)] -def _comments_client(): - client = MagicMock() - client.request.return_value = {"bugs": {"1": {"comments": THREAD}}} - return client +def _comments_ctx(bugzilla_ctx): + ctx, _ = bugzilla_ctx( + lambda path, params: httpx.Response( + 200, json={"bugs": {"1": {"comments": THREAD}}} + ) + ) + return ctx @pytest.mark.parametrize( @@ -404,17 +420,17 @@ def _comments_client(): ], ) async def test_get_bug_comments_pages_by_comment_number( - start, limit, expected, next_start + bugzilla_ctx, start, limit, expected, next_start ): - ctx = BugzillaContext(client=_comments_client()) + ctx = _comments_ctx(bugzilla_ctx) res = await bugzilla.get_bug_comments(ctx, 1, start=start, limit=limit) assert [c["count"] for c in res["comments"]] == expected assert (res["total"], res["start"], res["count"]) == (5, start, len(expected)) assert res["next_start"] == next_start -async def test_get_bug_comments_with_no_page_returns_every_comment(): - res = await bugzilla.get_bug_comments(BugzillaContext(client=_comments_client()), 1) +async def test_get_bug_comments_with_no_page_returns_every_comment(bugzilla_ctx): + res = await bugzilla.get_bug_comments(_comments_ctx(bugzilla_ctx), 1) assert res["count"] == res["total"] == 5 assert res["comments"] == THREAD @@ -432,26 +448,26 @@ async def test_get_bug_comments_takes_page_bounds(): assert props["limit"]["anyOf"][0]["minimum"] == 1 -async def test_get_bug_history_returns_the_entries(): +async def test_get_bug_history_returns_the_entries(bugzilla_ctx): entry = { "when": "2026-10-13T18:01:21Z", "who": "dev@example.com", "changes": [{"field_name": "status", "added": "NEW", "removed": "UNCONFIRMED"}], } - client = MagicMock() - client.request.return_value = {"bugs": [{"id": 1, "history": [entry]}]} - res = await bugzilla.get_bug_history( - BugzillaContext(client=client), 1, new_since="2026-10-01T00:00:00Z" + ctx, calls = bugzilla_ctx( + lambda path, params: httpx.Response( + 200, json={"bugs": [{"id": 1, "history": [entry]}]} + ) ) + res = await bugzilla.get_bug_history(ctx, 1, new_since="2026-10-01T00:00:00Z") assert res == {"bug_id": 1, "count": 1, "history": [entry]} - client.request.assert_called_once_with( - "bug/1/history", params={"new_since": "2026-10-01T00:00:00Z"} - ) + assert calls == [("bug/1/history", {"new_since": "2026-10-01T00:00:00Z"})] -async def test_get_bug_history_with_no_history_is_empty(): - client = MagicMock() - client.request.return_value = {"bugs": []} - res = await bugzilla.get_bug_history(BugzillaContext(client=client), 1) +async def test_get_bug_history_with_no_history_is_empty(bugzilla_ctx): + ctx, calls = bugzilla_ctx( + lambda path, params: httpx.Response(200, json={"bugs": []}) + ) + res = await bugzilla.get_bug_history(ctx, 1) assert res == {"bug_id": 1, "count": 0, "history": []} - client.request.assert_called_once_with("bug/1/history", params={}) + assert calls == [("bug/1/history", {})] diff --git a/uv.lock b/uv.lock index 50cbd80c892..f6059b7ce1e 100644 --- a/uv.lock +++ b/uv.lock @@ -73,8 +73,7 @@ dependencies = [ [package.optional-dependencies] bugzilla = [ - { name = "bugsy" }, - { name = "six" }, + { name = "bugzilla-client" }, ] claude-sdk = [ { name = "claude-agent-sdk" }, @@ -92,14 +91,13 @@ vcs = [ [package.metadata] requires-dist = [ - { name = "bugsy", marker = "extra == 'bugzilla'" }, + { name = "bugzilla-client", marker = "extra == 'bugzilla'", editable = "libs/bugzilla-client" }, { name = "claude-agent-sdk", marker = "extra == 'claude-sdk'", specifier = ">=0.1.30" }, { name = "grizzly-framework", marker = "extra == 'firefox'" }, { name = "httpx", marker = "extra == 'vcs'" }, { name = "prefpicker", marker = "extra == 'firefox'" }, { name = "pydantic", specifier = ">=2.6.0" }, { name = "searchfox", marker = "extra == 'searchfox'", specifier = ">=0.20.3" }, - { name = "six", marker = "extra == 'bugzilla'" }, ] provides-extras = ["bugzilla", "firefox", "claude-sdk", "searchfox", "vcs"] @@ -875,18 +873,6 @@ requires-dist = [ ] provides-extras = ["dev", "llms-txt"] -[[package]] -name = "bugsy" -version = "0.12.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "requests" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/e5/d0/610e2f68f515238f98f920d9fe0a9b4bbc56436e6cfc64c5b64dc20b1459/bugsy-0.12.0.tar.gz", hash = "sha256:2d49af1cb4a2841e3d677ac535b054c51f457a5d124ad106c43a8fc3847fb26e", size = 17841, upload-time = "2020-07-13T18:47:24.272Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/50/e6/a99aa6ab1ae7842011ca6d50d159a5e5a500717d13fc2ae42f39131741e3/bugsy-0.12.0-py2.py3-none-any.whl", hash = "sha256:b5df82ff0e708cca73a517bfa80494a43b1b97267d5778a5cba62f7a9d04e9da", size = 27223, upload-time = "2020-07-13T18:47:23.232Z" }, -] - [[package]] name = "bugzilla-client" version = "0.1.0" @@ -2373,7 +2359,7 @@ source = { editable = "agents/autowebcompat-diagnosis" } dependencies = [ { name = "agent-tools", extra = ["bugzilla"] }, { name = "autowebcompat-tools" }, - { name = "bugsy" }, + { name = "bugzilla-client" }, { name = "claude-agent-sdk" }, { name = "hackbot-runtime", extra = ["claude-sdk"] }, { name = "mcp" }, @@ -2386,7 +2372,7 @@ dependencies = [ requires-dist = [ { name = "agent-tools", extras = ["bugzilla"], editable = "libs/agent-tools" }, { name = "autowebcompat-tools", editable = "libs/autowebcompat-tools" }, - { name = "bugsy" }, + { name = "bugzilla-client", editable = "libs/bugzilla-client" }, { name = "claude-agent-sdk", specifier = ">=0.1.30" }, { name = "hackbot-runtime", extras = ["claude-sdk"], editable = "libs/hackbot-runtime" }, { name = "mcp", specifier = ">=1.0.0" }, @@ -2401,7 +2387,7 @@ source = { editable = "agents/autowebcompat-intervention" } dependencies = [ { name = "agent-tools", extra = ["bugzilla", "firefox"] }, { name = "autowebcompat-tools" }, - { name = "bugsy" }, + { name = "bugzilla-client" }, { name = "claude-agent-sdk" }, { name = "hackbot-runtime", extra = ["claude-sdk", "phabricator"] }, { name = "mcp" }, @@ -2421,7 +2407,7 @@ dev = [ requires-dist = [ { name = "agent-tools", extras = ["bugzilla", "firefox"], editable = "libs/agent-tools" }, { name = "autowebcompat-tools", editable = "libs/autowebcompat-tools" }, - { name = "bugsy" }, + { name = "bugzilla-client", editable = "libs/bugzilla-client" }, { name = "claude-agent-sdk", specifier = ">=0.2.165" }, { name = "hackbot-runtime", extras = ["claude-sdk", "phabricator"], editable = "libs/hackbot-runtime" }, { name = "mcp", specifier = ">=1.0.0" }, @@ -2440,7 +2426,7 @@ source = { editable = "agents/autowebcompat-repro" } dependencies = [ { name = "agent-tools", extra = ["bugzilla"] }, { name = "autowebcompat-tools" }, - { name = "bugsy" }, + { name = "bugzilla-client" }, { name = "claude-agent-sdk" }, { name = "hackbot-runtime", extra = ["claude-sdk"] }, { name = "mcp" }, @@ -2453,7 +2439,7 @@ dependencies = [ requires-dist = [ { name = "agent-tools", extras = ["bugzilla"], editable = "libs/agent-tools" }, { name = "autowebcompat-tools", editable = "libs/autowebcompat-tools" }, - { name = "bugsy" }, + { name = "bugzilla-client", editable = "libs/bugzilla-client" }, { name = "claude-agent-sdk", specifier = ">=0.1.30" }, { name = "hackbot-runtime", extras = ["claude-sdk"], editable = "libs/hackbot-runtime" }, { name = "mcp", specifier = ">=1.0.0" }, @@ -2467,7 +2453,7 @@ name = "hackbot-agent-bug-fix" source = { editable = "agents/bug-fix" } dependencies = [ { name = "agent-tools", extra = ["bugzilla", "firefox"] }, - { name = "bugsy" }, + { name = "bugzilla-client" }, { name = "claude-agent-sdk" }, { name = "hackbot-runtime", extra = ["claude-sdk", "phabricator"] }, { name = "mcp" }, @@ -2489,7 +2475,7 @@ dev = [ [package.metadata] requires-dist = [ { name = "agent-tools", extras = ["bugzilla", "firefox"], editable = "libs/agent-tools" }, - { name = "bugsy" }, + { name = "bugzilla-client", editable = "libs/bugzilla-client" }, { name = "claude-agent-sdk", specifier = ">=0.1.30" }, { name = "hackbot-runtime", extras = ["claude-sdk", "phabricator"], editable = "libs/hackbot-runtime" }, { name = "mcp", specifier = ">=1.0.0" }, @@ -2508,7 +2494,7 @@ name = "hackbot-agent-build-repair" source = { editable = "agents/build-repair" } dependencies = [ { name = "agent-tools", extra = ["bugzilla", "firefox"] }, - { name = "bugsy" }, + { name = "bugzilla-client" }, { name = "claude-agent-sdk" }, { name = "hackbot-runtime", extra = ["claude-sdk", "phabricator"] }, { name = "mcp" }, @@ -2527,7 +2513,7 @@ eval = [ [package.metadata] requires-dist = [ { name = "agent-tools", extras = ["bugzilla", "firefox"], editable = "libs/agent-tools" }, - { name = "bugsy" }, + { name = "bugzilla-client", editable = "libs/bugzilla-client" }, { name = "claude-agent-sdk", specifier = ">=0.2.165" }, { name = "hackbot-runtime", extras = ["claude-sdk", "phabricator"], editable = "libs/hackbot-runtime" }, { name = "mcp", specifier = ">=1.0.0" }, @@ -2574,7 +2560,7 @@ name = "hackbot-agent-frontend-triage" source = { editable = "agents/frontend-triage" } dependencies = [ { name = "agent-tools", extra = ["bugzilla", "searchfox", "vcs"] }, - { name = "bugsy" }, + { name = "bugzilla-client" }, { name = "claude-agent-sdk" }, { name = "hackbot-runtime", extra = ["claude-sdk"] }, { name = "mcp" }, @@ -2591,7 +2577,7 @@ dev = [ [package.metadata] requires-dist = [ { name = "agent-tools", extras = ["bugzilla", "searchfox", "vcs"], editable = "libs/agent-tools" }, - { name = "bugsy" }, + { name = "bugzilla-client", editable = "libs/bugzilla-client" }, { name = "claude-agent-sdk", specifier = ">=0.2.165" }, { name = "hackbot-runtime", extras = ["claude-sdk"], editable = "libs/hackbot-runtime" }, { name = "mcp", specifier = ">=1.0.0" }, @@ -2608,7 +2594,7 @@ version = "0.1.0" source = { editable = "agents/gecko-triage" } dependencies = [ { name = "agent-tools", extra = ["bugzilla", "searchfox", "vcs"] }, - { name = "bugsy" }, + { name = "bugzilla-client" }, { name = "claude-agent-sdk" }, { name = "hackbot-runtime", extra = ["claude-sdk"] }, { name = "jinja2" }, @@ -2626,7 +2612,7 @@ dev = [ [package.metadata] requires-dist = [ { name = "agent-tools", extras = ["bugzilla", "searchfox", "vcs"], editable = "libs/agent-tools" }, - { name = "bugsy" }, + { name = "bugzilla-client", editable = "libs/bugzilla-client" }, { name = "claude-agent-sdk", specifier = ">=0.2.165" }, { name = "hackbot-runtime", extras = ["claude-sdk"], editable = "libs/hackbot-runtime" }, { name = "jinja2", specifier = ">=3.1" },