From b56faefd01ccd24b77651711d3136b9273ce40b4 Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Fri, 20 Nov 2026 21:39:18 -0800 Subject: [PATCH 1/2] feat: add an optional A2A adapter for remote specialist tools Add an optional Python extra for A2A with no changes to existing dependency versions or the native bridge. --- examples/a2a/README.md | 52 +++++ examples/a2a/manager.py | 126 ++++++++++++ pyproject.toml | 4 + src/agents/extensions/a2a.py | 193 ++++++++++++++++++ tests/test_a2a.py | 380 +++++++++++++++++++++++++++++++++++ uv.lock | 126 +++++++++++- 6 files changed, 880 insertions(+), 1 deletion(-) create mode 100644 examples/a2a/README.md create mode 100644 examples/a2a/manager.py create mode 100644 src/agents/extensions/a2a.py create mode 100644 tests/test_a2a.py diff --git a/examples/a2a/README.md b/examples/a2a/README.md new file mode 100644 index 0000000000..5233644a12 --- /dev/null +++ b/examples/a2a/README.md @@ -0,0 +1,52 @@ +# Call a registered remote specialist + +[manager.py](manager.py) defines two ordinary function tools. The manager looks up names with `find_specialists`. It asks a yes/no question with `ask_specialist`. The verdict returns to the manager under the original tool call ID. Neither tool hands off control of the run. + +## Try it without an API key + +From a source checkout, run the [loopback example tests](../../tests/test_a2a.py). + +```sh +make sync +uv run --no-sync pytest -q tests/test_a2a.py +``` + +The scripted manager filters 500 names and calls two services on separate ports. One uses a stored card. The other requires separate credentials for discovery and task calls. The recovery test drops a reply after commit, closes both databases and restarts the receiver. The application retrieves the original verdict by call ID without a second send. + +## Configure the manager + +Install the `a2a` extra from this checkout with `pip install '.[a2a]'`. The adapter uses the official Python SDK's [A2A 1.0](https://a2a-protocol.org/v1.0.0/specification/) message types. + +1. Load approved names and URLs from application configuration for the authenticated owner. Construct an `agents.extensions.a2a.A2ASpecialist` for each name. Supply `rpc_url` and either UTF-8 Agent Card JSON as `card` bytes or an exact `card_url`. Keep names and URLs free of secrets. +2. For bearer authentication, supply separate zero-argument `card_token` and `rpc_token` functions. Omit a supplier only for an anonymous route. Each function must check the current grant and return a token for its URL. Both must be non-blocking. The receiver must authenticate the caller and enforce ownership on every task read. +3. Construct a `Registry` with the owner, a stable run ID, the authorized name mapping, a dedicated SQLite connection and a trusted `lookup_receipt` function. Keep the grants fixed during each invocation. Reload them after restart. Protect both databases, including question digests and receipts. +4. Add both tools to the manager's `Agent.tools`. Pass the registry as `context` to `Runner.run`. The model sees only the prefix, name and question arguments. Search returns at most ten names. Every registered name is callable, including names outside the search results. + +Only use application-approved destinations. Both URLs require HTTPS and the same origin. HTTP is available on `127.0.0.1` and `::1` for development. The card must list the exact RPC URL with binding `JSONRPC`, version `1.0` and no tenant. Each operation checks this before requesting RPC credentials. Card metadata cannot select endpoints or credentials. The adapter follows no redirects and uses no environment proxies or shared cookies. The application owns DNS and network access policy. + +## Requests, results and failures + +`await specialist.send(text, message_id=unique_id)` makes one non-streaming `SendMessage` request with one user text part. `await specialist.get(task_id=..., context_id=...)` makes one `GetTask` request and checks both IDs. Both methods check the JSON-RPC response ID and return a private `a2a.types.Task`. Direct message responses are unsupported. Inspect the task state before using an artifact. Treat all peer fields as untrusted, including text that might repeat credentials. Avoid logging raw tasks, HTTP traffic or exception locals. + +The maximum encoded request is 64 KiB. Each card and RPC response has a 1 MiB limit. Compressed responses are unsupported. The default `timeout` is ten seconds across discovery and RPC. `A2AError.kind` distinguishes request, authorization, timeout, transport, protocol and remote errors. Local cancellation propagates as `asyncio.CancelledError`. A timeout, disconnect or cancellation may leave remote work running. The adapter never retries, polls or sends `CancelTask`. Remote cancellation requires separate authorization and cannot guarantee rollback. + +## Recover a lost acknowledgement + +The example requires a cooperating receiver. Its business effect is one immutable verdict. The receiver commits that verdict and its receipt together under a unique message ID. A2A alone provides no receipt lookup by message ID or guarantee against replay. + +The manager reserves the owner, run and tool call ID in SQLite before sending. It binds the reservation to the name, approved endpoint, question digest and a new message ID. The reservation survives failure even if the request never reached the service. A new run or call ID permits a new send. + +A failed run may leave the application without the question the model generated. The journal stores only its digest. On restart, reopen the same database and restore the registry for the authenticated owner and original run. To find the saved call IDs and specialist names, query the journal. + +```python +calls = registry.db.execute( + "SELECT call_id, name FROM calls WHERE owner=? AND run_id=?", + (registry.owner, registry.run_id), +).fetchall() +``` + +For the call you need to reconcile, use `verdict = await registry.recover(call_id)`. This application method never creates a reservation, sends a question or resumes the manager. If the manager repeats an existing call with identical arguments, `ask` uses the same read path. + +Both paths check the current grant for the saved name and endpoint. The trusted lookup must return the receiver's immutable `Receipt` for that owner, endpoint, message ID and question digest. Recovery then reads the task with `GetTask`. The example checks both task and context IDs, the completed state and a single text verdict matching the receipt. Only `yes` or `no` passes verification. + +Missing or conflicting evidence leaves the call unresolved. Removed grants, changed endpoints or different arguments for the same call ID block reuse. Tool failures stop the run for application handling. Never delete a reservation or generate a replacement call to resolve an uncertain outcome. diff --git a/examples/a2a/manager.py b/examples/a2a/manager.py new file mode 100644 index 0000000000..407c5f9358 --- /dev/null +++ b/examples/a2a/manager.py @@ -0,0 +1,126 @@ +"""A manager tool for specialists that return a single yes/no verdict.""" + +import hashlib +import sqlite3 +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from itertools import islice +from uuid import uuid4 + +from a2a.types import a2a_pb2 as a2a + +from agents.decorators import tool +from agents.extensions.a2a import A2ASpecialist +from agents.tool_context import ToolContext + + +class UnresolvedCall(Exception): + """The manager has no verified result. Do not submit the question again.""" + + +@dataclass(frozen=True) +class Receipt: + """A receiver-owned record read over a trusted channel, never supplied by the model.""" + + owner: str + endpoint: str + message_id: str + digest: str + task_id: str + context_id: str + verdict: str + + +@dataclass(frozen=True) +class Registry: + """Current grants and a trusted receipt lookup for one authenticated owner and run.""" + + owner: str + run_id: str + specialists: Mapping[str, A2ASpecialist] + db: sqlite3.Connection + lookup_receipt: Callable[[str, str, str], Receipt | None] + + def __post_init__(self) -> None: + self.db.execute( + """CREATE TABLE IF NOT EXISTS calls ( + owner TEXT, run_id TEXT, call_id TEXT, name TEXT, endpoint TEXT, + digest TEXT, message_id TEXT UNIQUE, PRIMARY KEY (owner, run_id, call_id) + )""" + ) + + async def ask(self, call_id: str, name: str, question: str) -> str: + specialist = self.specialists.get(name) + if specialist is None or not self.owner or not self.run_id or not call_id: + raise PermissionError("No grant for this invocation") + + key = (self.owner, self.run_id, call_id) + binding = (name, specialist.rpc_url, hashlib.sha256(question.encode()).hexdigest()) + message_id = uuid4().hex + # Commit before network I/O. Only the worker that inserted this row may send. + with self.db: + created = self.db.execute( + "INSERT INTO calls VALUES (?, ?, ?, ?, ?, ?, ?) " + "ON CONFLICT(owner, run_id, call_id) DO NOTHING", + (*key, *binding, message_id), + ).rowcount + task = await specialist.send(question, message_id=message_id) if created else None + return await self._result(call_id, expected=binding, task=task) + + async def recover(self, call_id: str) -> str: + """Read a reserved call for this owner and run without sending a new message.""" + return await self._result(call_id) + + async def _result( + self, + call_id: str, + *, + expected: tuple[str, str, str] | None = None, + task: a2a.Task | None = None, + ) -> str: + row = self.db.execute( + "SELECT name, endpoint, digest, message_id FROM calls " + "WHERE owner=? AND run_id=? AND call_id=?", + (self.owner, self.run_id, call_id), + ).fetchone() + if row is None: + raise UnresolvedCall("No reservation for this invocation") + name, endpoint, digest, message_id = row + specialist = self.specialists.get(name) + if specialist is None or specialist.rpc_url != endpoint: + raise PermissionError("No grant for this invocation") + if expected is not None and (name, endpoint, digest) != expected: + raise PermissionError("Invocation binding changed") + + receipt = self.lookup_receipt(self.owner, specialist.rpc_url, message_id) + if receipt is None or ( + receipt.owner, + receipt.endpoint, + receipt.message_id, + receipt.digest, + ) != (self.owner, specialist.rpc_url, message_id, digest): + raise UnresolvedCall("No matching receipt") + if task is None: + task = await specialist.get(task_id=receipt.task_id, context_id=receipt.context_id) + if task.id != receipt.task_id or task.context_id != receipt.context_id: + raise UnresolvedCall("Task does not match the receipt") + if task.status.state != a2a.TASK_STATE_COMPLETED: + raise UnresolvedCall("Task has no completed result") + if len(task.artifacts) == 1 and len(task.artifacts[0].parts) == 1: + verdict = task.artifacts[0].parts[0].text + if verdict == receipt.verdict and verdict in ("yes", "no"): + return receipt.verdict + raise UnresolvedCall("Unexpected verdict") + + +@tool +async def find_specialists(ctx: ToolContext[Registry], prefix: str) -> list[str]: + """List up to ten registered names starting with the given prefix.""" + names = (name for name in ctx.context.specialists if name.startswith(prefix)) + return list(islice(names, 10)) + + +@tool(failure_error_function=None) +async def ask_specialist(ctx: ToolContext[Registry], name: str, question: str) -> str: + """Ask a registered specialist a yes/no question and return its verdict.""" + return await ctx.context.ask(ctx.tool_call_id, name, question) diff --git a/pyproject.toml b/pyproject.toml index 95171ab7d4..f5a2c56593 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -42,6 +42,10 @@ Homepage = "https://openai.github.io/openai-agents-python/" Repository = "https://github.com/openai/openai-agents-python" [project.optional-dependencies] +a2a = [ + "a2a-sdk>=1.3,<2", + "protobuf>=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*", +] opentelemetry = ["opentelemetry-api>=1.45.0,<2"] # Protobuf exclusions retain patched 5.x and 6.x releases (GHSA-7gcm-g887-7qv7). voice = ["numpy>=2.2.0, <3; python_version>='3.10'", "websockets>=15.0, <18"] diff --git a/src/agents/extensions/a2a.py b/src/agents/extensions/a2a.py new file mode 100644 index 0000000000..65f24b313e --- /dev/null +++ b/src/agents/extensions/a2a.py @@ -0,0 +1,193 @@ +"""Bounded, non-streaming A2A 1.0 task calls. Requires the `a2a` extra.""" + +from __future__ import annotations + +import asyncio +import json +import math +from collections.abc import Callable +from dataclasses import dataclass, field +from typing import Literal +from uuid import uuid4 + +import httpx2 +from a2a.types import a2a_pb2 as a2a +from google.protobuf.json_format import MessageToDict, ParseDict + +__all__ = ["A2AError", "A2ASpecialist"] + +_REQUEST_BYTES = 65_536 +_RESPONSE_BYTES = 1_048_576 + + +class A2AError(Exception): + """A local call failure. A failed send may already have created a remote task.""" + + def __init__( + self, + kind: Literal["request", "authorization", "timeout", "transport", "protocol", "remote"], + ) -> None: + self.kind = kind + super().__init__(f"A2A {kind} error") + + +def _origin(value: str) -> tuple[str, str, int | None]: + url = httpx2.URL(value) + if ( + not url.host + or url.userinfo + or "?" in value + or "#" in value + or not ( + url.scheme == "https" or (url.scheme == "http" and url.host in {"127.0.0.1", "::1"}) + ) + ): + raise ValueError("Use an approved HTTPS or loopback URL without credentials or parameters") + + return url.scheme, url.host, url.port + + +async def _fetch(url: str, token: Callable[[], str] | None, body: bytes | None = None) -> bytes: + headers = {"Accept-Encoding": "identity", "A2A-Version": "1.0"} + if body is not None: + headers["Content-Type"] = "application/json" + if token is not None: + try: + bearer = token() + if not bearer or not all(0x21 <= ord(c) <= 0x7E for c in bearer): + raise ValueError + except Exception: + raise A2AError("authorization") from None + headers["Authorization"] = f"Bearer {bearer}" + + # Keep cookies, redirects and ambient proxy settings out of both requests. + async with httpx2.AsyncClient(trust_env=False, follow_redirects=False, timeout=None) as client: + async with client.stream( + "GET" if body is None else "POST", url, content=body, headers=headers + ) as response: + if response.status_code in (401, 403): + raise A2AError("authorization") + if response.status_code != 200: + raise A2AError("remote") + if response.headers.get("content-encoding", "identity").lower() != "identity": + raise A2AError("protocol") + data = bytearray() + async for chunk in response.aiter_raw(): + if len(data) + len(chunk) > _RESPONSE_BYTES: + raise A2AError("protocol") + data.extend(chunk) + return bytes(data) + + +@dataclass(frozen=True, kw_only=True) +class A2ASpecialist: + """One trusted RPC URL and either stored card JSON or a trusted card URL. + + Token suppliers must be local, non-blocking and scoped to their respective URLs. + Treat every field of the returned Task as private, untrusted peer data. + """ + + rpc_url: str + card: bytes | None = field(default=None, repr=False) + card_url: str | None = None + rpc_token: Callable[[], str] | None = field(default=None, repr=False) + card_token: Callable[[], str] | None = field(default=None, repr=False) + timeout: float = 10.0 + + def __post_init__(self) -> None: + origin = _origin(self.rpc_url) + if (self.card is None) == (self.card_url is None): + raise ValueError("Provide exactly one of card and card_url") + if self.card_url is not None: + if _origin(self.card_url) != origin: + raise ValueError("The card and RPC URLs must share an origin") + elif self.card_token is not None: + raise ValueError("card_token requires card_url") + if not math.isfinite(self.timeout) or self.timeout <= 0: + raise ValueError("timeout must be positive and finite") + + async def send(self, text: str, *, message_id: str) -> a2a.Task: + """Send one user message. The caller owns the unique ID and any replay policy.""" + if not text or not message_id or len(text) + len(message_id) > _REQUEST_BYTES: + raise A2AError("request") + request = a2a.SendMessageRequest( + message=a2a.Message( + message_id=message_id, role=a2a.ROLE_USER, parts=[a2a.Part(text=text)] + ), + configuration=a2a.SendMessageConfiguration( + accepted_output_modes=["text/plain"], history_length=0 + ), + ) + return await self._call(request) + + async def get(self, *, task_id: str, context_id: str) -> a2a.Task: + """Read an existing task and require both identifiers to match.""" + if not task_id or not context_id or len(task_id) > _REQUEST_BYTES: + raise A2AError("request") + task = await self._call(a2a.GetTaskRequest(id=task_id, history_length=0)) + if task.id != task_id or task.context_id != context_id: + del task + raise A2AError("protocol") + return task + + async def _call(self, request: a2a.SendMessageRequest | a2a.GetTaskRequest) -> a2a.Task: + try: + return await asyncio.wait_for(self._exchange(request), self.timeout) + except asyncio.CancelledError as exc: + raise exc.with_traceback(None) from None + except asyncio.TimeoutError: + failure = A2AError("timeout") + except A2AError as exc: + failure = A2AError(exc.kind) + except httpx2.HTTPError: + failure = A2AError("transport") + except Exception: + failure = A2AError("protocol") + # Discard private dependency exceptions and their request/response frames. + raise failure + + async def _exchange(self, request: a2a.SendMessageRequest | a2a.GetTaskRequest) -> a2a.Task: + sending = isinstance(request, a2a.SendMessageRequest) + rpc_id = uuid4().hex + body = json.dumps( + { + "jsonrpc": "2.0", + "id": rpc_id, + "method": "SendMessage" if sending else "GetTask", + "params": MessageToDict(request), + }, + ensure_ascii=False, + ).encode() + if len(body) > _REQUEST_BYTES: + raise A2AError("request") + + raw = self.card + if raw is None: + assert self.card_url is not None + raw = await _fetch(self.card_url, self.card_token) + if len(raw) > _RESPONSE_BYTES: + raise A2AError("protocol") + card = ParseDict(json.loads(raw), a2a.AgentCard()) + if not any( + interface.url == self.rpc_url + and interface.protocol_binding == "JSONRPC" + and interface.protocol_version == "1.0" + and not interface.tenant + for interface in card.supported_interfaces + ): + raise A2AError("protocol") + + reply = json.loads(await _fetch(self.rpc_url, self.rpc_token, body)) + if reply.get("jsonrpc") != "2.0" or reply.get("id") != rpc_id: + raise A2AError("protocol") + if "error" in reply: + raise A2AError("remote") + result = reply["result"] + task = ( + ParseDict(result, a2a.SendMessageResponse()).task + if sending + else ParseDict(result, a2a.Task()) + ) + if not task.id or not task.context_id or not task.status.state: + raise A2AError("protocol") + return task diff --git a/tests/test_a2a.py b/tests/test_a2a.py new file mode 100644 index 0000000000..38c71afcb2 --- /dev/null +++ b/tests/test_a2a.py @@ -0,0 +1,380 @@ +"""Loopback wire peers let us drop a reply after commit and control disconnects.""" + +import asyncio +import hashlib +import json +import sqlite3 +from contextlib import closing +from dataclasses import replace +from pathlib import Path +from uuid import uuid4 + +import pytest +from aiohttp import web +from aiohttp.test_utils import TestServer + +from agents import Agent, RunConfig, Runner, UserError +from agents.testing import ScriptedModel +from tests.test_responses import get_function_tool_call, get_text_message + +pytest.importorskip("a2a") + +from agents.extensions.a2a import A2AError, A2ASpecialist +from examples.a2a.manager import Receipt, Registry, UnresolvedCall, ask_specialist, find_specialists + + +def card(url): + return { + "name": "synthetic", + "description": "Synthetic verdicts", + "version": "1", + "capabilities": {}, + "defaultInputModes": ["text/plain"], + "defaultOutputModes": ["text/plain"], + "skills": [], + "supportedInterfaces": [ + {"url": url, "protocolBinding": "JSONRPC", "protocolVersion": "1.0"} + ], + } + + +class Receiver: + """The committed verdict is the business effect. Reads never recompute it.""" + + def __init__(self, db: sqlite3.Connection, verdict: str, *, drop=False): + self.db = db + self.verdict = verdict + self.drop = drop + self.methods: list[str] = [] + self.db.execute( + "CREATE TABLE IF NOT EXISTS effects (" + "owner TEXT, endpoint TEXT, message_id TEXT PRIMARY KEY, digest TEXT, " + "task_id TEXT UNIQUE, context_id TEXT, verdict TEXT)" + ) + self.app = web.Application() + self.app.router.add_get("/card", self.discover) + self.app.router.add_post("/rpc", self.rpc) + + def lookup(self, owner, endpoint, message_id): + row = self.db.execute( + "SELECT * FROM effects WHERE owner=? AND endpoint=? AND message_id=?", + (owner, endpoint, message_id), + ).fetchone() + return Receipt(*row) if row else None + + async def discover(self, request): + assert request.headers["Authorization"] == "Bearer synthetic-card" + self.methods.append("card") + response = web.json_response(card(str(request.url.with_path("/rpc")))) + response.set_cookie("card-only", "synthetic") + return response + + async def rpc(self, request): + assert "Cookie" not in request.headers + assert request.headers["A2A-Version"] == "1.0" + if request.headers.get("Authorization") != "Bearer synthetic-rpc": + raise web.HTTPUnauthorized() + owner = "synthetic-owner" + body = await request.json() + assert body["jsonrpc"] == "2.0" + method = body["method"] + self.methods.append(method) + if method == "SendMessage": + message = body["params"]["message"] + assert message["role"] == "ROLE_USER" + question = message["parts"][0]["text"] + task_id = uuid4().hex + with self.db: + self.db.execute( + "INSERT INTO effects VALUES (?, ?, ?, ?, ?, ?, ?)", + ( + owner, + str(request.url), + message["messageId"], + hashlib.sha256(question.encode()).hexdigest(), + task_id, + uuid4().hex, + self.verdict, + ), + ) + if self.drop: + request.transport.close() + return web.Response() + else: + assert method == "GetTask" + task_id = body["params"]["id"] + + context_id, verdict = self.db.execute( + "SELECT context_id, verdict FROM effects WHERE task_id=? AND owner=? AND endpoint=?", + (task_id, owner, str(request.url)), + ).fetchone() + task = { + "id": task_id, + "contextId": context_id, + "status": {"state": "TASK_STATE_COMPLETED"}, + "artifacts": [{"artifactId": "verdict", "parts": [{"text": verdict}]}], + } + return web.json_response( + { + "jsonrpc": "2.0", + "id": body["id"], + "result": {"task": task} if method == "SendMessage" else task, + } + ) + + +def stored(url: str) -> A2ASpecialist: + return A2ASpecialist( + rpc_url=url, card=json.dumps(card(url)).encode(), rpc_token=lambda: "synthetic-rpc" + ) + + +def ask(name: str, call_id: str, question: str = "Ready?"): + return get_function_tool_call( + "ask_specialist", json.dumps({"name": name, "question": question}), call_id=call_id + ) + + +async def run_manager(registry, turns): + agent = Agent( + name="manager", + tools=[find_specialists, ask_specialist], + model=ScriptedModel([*turns, [get_text_message("Manager finished")]]), + ) + result = await Runner.run( + agent, "Check readiness", context=registry, run_config=RunConfig(tracing_disabled=True) + ) + assert result.last_agent is agent + assert result.final_output == "Manager finished" + return { + item["call_id"]: item["output"] + for item in result.to_input_list() + if item.get("type") == "function_call_output" + } + + +@pytest.mark.asyncio +async def test_manager_filters_500_names_and_calls_two_hosts(tmp_path: Path): + with ( + closing(sqlite3.connect(tmp_path / "east")) as east_db, + closing(sqlite3.connect(tmp_path / "west")) as west_db, + closing(sqlite3.connect(tmp_path / "manager")) as db, + ): + east, west = Receiver(east_db, "yes"), Receiver(west_db, "no") + async with TestServer(east.app) as a, TestServer(west.app) as b: + names = {f"other-{i}": stored(f"http://127.0.0.1:1/{i}") for i in range(498)} + names["weather-east"] = stored(str(a.make_url("/rpc"))) + names["weather-west"] = A2ASpecialist( + card_url=str(b.make_url("/card")), + card_token=lambda: "synthetic-card", + rpc_url=str(b.make_url("/rpc")), + rpc_token=lambda: "synthetic-rpc", + ) + + def lookup(owner, url, message): + return east.lookup(owner, url, message) or west.lookup(owner, url, message) + + registry = Registry("synthetic-owner", "run", names, db, lookup) + outputs = await run_manager( + registry, + [ + [ + get_function_tool_call( + "find_specialists", '{"prefix":"weather-"}', call_id="list" + ) + ], + [ask("weather-west", "one"), ask("weather-east", "two")], + ], + ) + assert "weather-west" in str(outputs["list"]) and "weather-east" in str(outputs["list"]) + assert "other-" not in str(outputs["list"]) + assert outputs["one"] == "no" and outputs["two"] == "yes" + assert east.methods == ["SendMessage"] + assert west.methods == ["card", "SendMessage"] + assert await run_manager(registry, [[ask("weather-east", "two")]]) == {"two": "yes"} + assert east.methods == ["SendMessage", "GetTask"] + + +@pytest.mark.asyncio +async def test_lost_ack_restart_verifies_receipt_and_projects_original_result(tmp_path: Path): + def registry(db, peer, url): + return Registry("synthetic-owner", "run", {"east": stored(url)}, db, peer.lookup) + + with ( + closing(sqlite3.connect(tmp_path / "receiver")) as remote, + closing(sqlite3.connect(tmp_path / "manager")) as db, + ): + peer = Receiver(remote, "yes", drop=True) + async with TestServer(peer.app) as server: + port = server.port + url = str(server.make_url("/rpc")) + with pytest.raises(UserError) as err: + await run_manager( + registry(db, peer, url), [[ask("east", uuid4().hex, f"Is {uuid4()} ready?")]] + ) + cause = err.value.__cause__ + assert isinstance(cause, A2AError) and cause.kind == "transport" + assert cause.__context__ is None + assert peer.methods == ["SendMessage"] + + with ( + closing(sqlite3.connect(tmp_path / "receiver")) as remote, + closing(sqlite3.connect(tmp_path / "manager")) as db, + ): + peer = Receiver(remote, "no") + async with TestServer(peer.app, port=port): + restored = registry(db, peer, url) + (call_id,) = db.execute( + "SELECT call_id FROM calls WHERE owner=? AND run_id=?", + (restored.owner, restored.run_id), + ).fetchone() + with pytest.raises(PermissionError): + await restored.ask(call_id, "east", "Different?") + with pytest.raises(PermissionError): + await replace(restored, specialists={}).recover(call_id) + with pytest.raises(PermissionError): + await replace(restored, specialists={"east": stored(url + "/other")}).recover( + call_id + ) + with pytest.raises(UnresolvedCall): + await replace(restored, owner="foreign").recover(call_id) + with pytest.raises(UnresolvedCall): + await restored.recover("missing") + receipt = Receipt(*remote.execute("SELECT * FROM effects").fetchone()) + for invalid in ( + None, + replace(receipt, owner="foreign"), + replace(receipt, digest="wrong"), + ): + with pytest.raises(UnresolvedCall): + await replace( + restored, lookup_receipt=lambda *args, value=invalid: value + ).recover(call_id) + assert peer.methods == [] + assert await restored.recover(call_id) == "yes" + assert peer.methods == ["GetTask"] + assert remote.execute("SELECT count(*) FROM effects").fetchone() == (1,) + assert db.execute("SELECT count(*) FROM calls").fetchone() == (1,) + with pytest.raises(UnresolvedCall, match="verdict"): + await replace( + restored, lookup_receipt=lambda *_: replace(receipt, verdict="no") + ).recover(call_id) + with pytest.raises(A2AError, match="protocol"): + await stored(url).get(task_id=receipt.task_id, context_id="wrong") + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "fault", + ["redirect-card", "redirect-rpc", "foreign", "large", "encoded", "rpc-id", "private-error"], +) +async def test_untrusted_responses_never_reroute_or_expose_credentials(fault): + calls = [] + + def rpc_token(): + calls.append("grant") + return "synthetic-rpc" + + async def handle(request): + calls.append(request.path) + if request.path == "/card": + assert request.headers["Authorization"] == "Bearer synthetic-card" + if fault == "redirect-card": + raise web.HTTPTemporaryRedirect("/unapproved") + if fault == "large": + return web.Response(body=b" " * 1_048_576 + json.dumps(card(url)).encode()) + if fault == "encoded": + return web.Response(headers={"Content-Encoding": "gzip"}) + return web.json_response(card(url + "/other" if fault == "foreign" else url)) + if fault == "redirect-rpc": + raise web.HTTPTemporaryRedirect("/unapproved") + body = await request.json() + return web.json_response( + { + "jsonrpc": "2.0", + "id": "wrong" if fault == "rpc-id" else body["id"], + "error": {"code": -32603, "message": "synthetic-rpc"}, + } + ) + + app = web.Application() + app.router.add_route("*", "/{path:.*}", handle) + async with TestServer(app) as server: + url = str(server.make_url("/rpc")) + client = A2ASpecialist( + rpc_url=url, + card_url=str(server.make_url("/card")), + card_token=lambda: "synthetic-card", + rpc_token=rpc_token, + ) + with pytest.raises(A2AError) as err: + await client.send("Ready?", message_id="request") + assert err.value.kind == ( + "remote" if fault.startswith("redirect") or fault == "private-error" else "protocol" + ) + assert "synthetic" not in str(err.value) + assert err.value.__context__ is None and err.value.__cause__ is None + assert calls == ( + ["/card", "grant", "/rpc"] + if fault in ("redirect-rpc", "rpc-id", "private-error") + else ["/card"] + ) + + +@pytest.mark.asyncio +async def test_timeout_and_local_cancellation_do_not_replay_or_cancel_remote_work(tmp_path): + started = asyncio.Event() + release = asyncio.Event() + methods = [] + + async def hold(request): + methods.append((await request.json())["method"]) + started.set() + await release.wait() + return web.Response() + + app = web.Application() + app.router.add_post("/rpc", hold) + async with TestServer(app) as server: + endpoint = stored(str(server.make_url("/rpc"))) + with closing(sqlite3.connect(tmp_path / "manager")) as db: + registry = Registry("owner", "run", {"east": endpoint}, db, lambda *_: None) + first = asyncio.create_task(registry.ask("call", "east", "Ready?")) + try: + await asyncio.wait_for(started.wait(), 5) + with pytest.raises(UnresolvedCall): + await registry.ask("call", "east", "Ready?") + first.cancel() + with pytest.raises(asyncio.CancelledError): + await first + with pytest.raises(UnresolvedCall): + await registry.ask("call", "east", "Ready?") + assert methods == ["SendMessage"] + with pytest.raises(A2AError, match="timeout"): + await replace(endpoint, timeout=0.05).get(task_id="task", context_id="context") + assert "CancelTask" not in methods + finally: + release.set() + first.cancel() + await asyncio.gather(first, return_exceptions=True) + + +@pytest.mark.asyncio +async def test_invalid_endpoint_and_oversize_request_fail_locally(): + with pytest.raises(ValueError): + stored("http://specialist.example/rpc") + endpoint = stored("https://specialist.example/rpc") + with pytest.raises(A2AError, match="request"): + await endpoint.send("é" * 40000, message_id="message") + + +@pytest.mark.asyncio +async def test_unavailable_grant_fails_without_retaining_supplier_error(): + def deny(): + raise PermissionError("synthetic-private-detail") + + specialist = replace(stored("http://127.0.0.1:1/rpc"), rpc_token=deny) + with pytest.raises(A2AError) as err: + await specialist.send("Ready?", message_id="one") + assert err.value.kind == "authorization" + assert err.value.__context__ is None and err.value.__cause__ is None diff --git a/uv.lock b/uv.lock index 8ca8cdb761..6ad6cf77c0 100644 --- a/uv.lock +++ b/uv.lock @@ -15,6 +15,25 @@ exclude-newer-span = "P7D" [options.exclude-newer-package] openai = false +[[package]] +name = "a2a-sdk" +version = "1.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "culsans", marker = "python_full_version < '3.13'" }, + { name = "google-api-core" }, + { name = "googleapis-common-protos" }, + { name = "httpx" }, + { name = "json-rpc" }, + { name = "packaging" }, + { name = "protobuf" }, + { name = "pydantic" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b8/4d/975373c77f1c390f808e5079495db28982a3118e9bee813a2dcae10e878c/a2a_sdk-1.3.0.tar.gz", hash = "sha256:73694717de50f36aaebd57b8fc6636ecaa825eb0d4437984fa2cd17f703a6808", size = 439840, upload-time = "2026-10-27T10:07:04.845Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a8/c8/262490a338e07b269ed80f9b26d101532f7af4585238a9973a5f223ff3f4/a2a_sdk-1.3.0-py3-none-any.whl", hash = "sha256:b94a73b5dc7ff1afe5f11d324480f83386a64d02b8a6b719baf013595284cc6c", size = 282393, upload-time = "2026-10-27T10:07:02.914Z" }, +] + [[package]] name = "aiofiles" version = "24.1.0" @@ -224,6 +243,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/1a/99/84ba7273339d0f3dfa57901b846489d2e5c2cd731470167757f1935fffbd/aiohttp_retry-2.9.1-py3-none-any.whl", hash = "sha256:66d2759d1921838256a05a3f80ad7e724936f083e35be5abb5e16eed6be6dc54", size = 9981, upload-time = "2024-11-06T10:44:52.917Z" }, ] +[[package]] +name = "aiologic" +version = "0.17.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "sniffio" }, + { name = "typing-extensions" }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f1/7a/d51f2fde1e8ae8a83431f8e97b7a71e9358cdb1d4d2ce6be387fa44d68de/aiologic-0.17.1.tar.gz", hash = "sha256:2e1b93b9e88ced318c2a63ad7b382688f40cbfe40e3d42258d49dc9c5aea179d", size = 252354, upload-time = "2026-06-27T20:41:33.25Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5b/d3/2d310b1b839014034dba0cba685e492df8a5c7ad32c19cab7e979eed6554/aiologic-0.17.1-py3-none-any.whl", hash = "sha256:c66b319830fedb7ca3d2b2125fa6f5b653f89418c2a27ea76f259ec5f00943c0", size = 161331, upload-time = "2026-06-27T20:41:31.877Z" }, +] + [[package]] name = "aiosignal" version = "1.4.0" @@ -950,6 +983,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/71/44/711e61f7d014be825ef79b285b047292d1bf893732ac1bc030a351fb517f/cryptography-50.0.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:693c99b49bd37d0d096e4334c10232c77248c415b98d35236094cdf96d57258b", size = 3824006, upload-time = "2026-08-25T19:45:37.281Z" }, ] +[[package]] +name = "culsans" +version = "0.11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiologic" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d9/e3/49afa1bc180e0d28008ec6bcdf82a4072d1c7a41032b5b759b60814ca4b0/culsans-0.11.0.tar.gz", hash = "sha256:0b43d0d05dce6106293d114c86e3fb4bfc63088cfe8ff08ed3fe36891447fe33", size = 107546, upload-time = "2025-12-31T23:15:38.196Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e0/5d/9fb19fb38f6d6120422064279ea5532e22b84aa2be8831d49607194feda3/culsans-0.11.0-py3-none-any.whl", hash = "sha256:278d118f63fc75b9db11b664b436a1b83cc30d9577127848ba41420e66eb5a47", size = 21811, upload-time = "2025-12-31T23:15:37.189Z" }, +] + [[package]] name = "dapr" version = "1.19.0" @@ -1437,6 +1483,36 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f7/ec/67fbef5d497f86283db54c22eec6f6140243aae73265799baaaa19cd17fb/ghp_import-2.1.0-py3-none-any.whl", hash = "sha256:8337dd7b50877f163d4c0289bc1f1c7f127550241988d568c1db512c4324a619", size = 11034, upload-time = "2022-05-02T15:47:14.552Z" }, ] +[[package]] +name = "google-api-core" +version = "2.44.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "google-auth" }, + { name = "googleapis-common-protos" }, + { name = "opentelemetry-api" }, + { name = "proto-plus" }, + { name = "protobuf" }, + { name = "requests" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/72/ef/63d89cb580f3a42c51db53b3d151352aa61b9c87ea8cfdd8d24ee6caa09d/google_api_core-2.44.0.tar.gz", hash = "sha256:5ab9a396965c1227d7dea4581e562b7018aa2bca96d2de0be5eb70dc9c8ab3a1", size = 288859, upload-time = "2026-11-05T18:39:43.265Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c9/73/4068d4b123d206f42e44d476b6ed4de773d81efc4e88101ff82e318b9a7a/google_api_core-2.44.0-py3-none-any.whl", hash = "sha256:8cb9ad8af28de9bc75121686d69b697ce0937e21fad2ad80c9a7e89f22b26e1f", size = 225627, upload-time = "2026-11-05T18:39:01.342Z" }, +] + +[[package]] +name = "google-auth" +version = "2.62.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cryptography" }, + { name = "pyasn1-modules" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/4a/d4/87353e950d653d87360176363d51f316e8e368e1ddbb7ba7aa5503c30c3e/google_auth-2.62.2.tar.gz", hash = "sha256:046c61a72d3a847d6df6417a7f0d5cf054e3b82bbcb54fb1e69d47880964049c", size = 404543, upload-time = "2026-11-10T15:50:55.102Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/d4/0f8481baa50f75db3bb19a0df79fe19615e66eccfc3afb0b946dcb8791b3/google_auth-2.62.2-py3-none-any.whl", hash = "sha256:e9bcdb0679b6a4369ac327c5c59f06d92f7b4cd2624e7100294c14632f55a36b", size = 270150, upload-time = "2026-11-10T15:50:53.408Z" }, +] + [[package]] name = "googleapis-common-protos" version = "1.70.0" @@ -1989,6 +2065,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/14/2f/967ba146e6d58cf6a652da73885f52fc68001525b4197effc174321d70b4/jmespath-1.1.0-py3-none-any.whl", hash = "sha256:a5663118de4908c91729bea0acadca56526eb2698e83de10cd116ae0f4e97c64", size = 20419, upload-time = "2026-01-22T16:35:24.919Z" }, ] +[[package]] +name = "json-rpc" +version = "1.15.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/6d/9e/59f4a5b7855ced7346ebf40a2e9a8942863f644378d956f68bcef2c88b90/json-rpc-1.15.0.tar.gz", hash = "sha256:e6441d56c1dcd54241c937d0a2dcd193bdf0bdc539b5316524713f554b7f85b9", size = 28854, upload-time = "2023-06-11T09:45:49.078Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/94/9e/820c4b086ad01ba7d77369fb8b11470a01fac9b4977f02e18659cf378b6b/json_rpc-1.15.0-py2.py3-none-any.whl", hash = "sha256:4a4668bbbe7116feb4abbd0f54e64a4adcf4b8f648f19ffa0848ad0f6606a9bf", size = 39450, upload-time = "2023-06-11T09:45:47.136Z" }, +] + [[package]] name = "jsonschema" version = "4.25.0" @@ -2801,6 +2886,10 @@ dependencies = [ ] [package.optional-dependencies] +a2a = [ + { name = "a2a-sdk" }, + { name = "protobuf" }, +] any-llm = [ { name = "any-llm-sdk", marker = "python_full_version >= '3.11'" }, { name = "pygments", marker = "python_full_version >= '3.11'" }, @@ -2931,6 +3020,7 @@ dev = [ [package.metadata] requires-dist = [ + { name = "a2a-sdk", marker = "extra == 'a2a'", specifier = ">=1.3,<2" }, { name = "aiohttp", marker = "extra == 'blaxel'", specifier = ">=3.14.3,<4" }, { name = "aiohttp", marker = "extra == 'cloudflare'", specifier = ">=3.14.3,<4" }, { name = "aiohttp", marker = "extra == 'dapr'", specifier = ">=3.14.3,<4" }, @@ -2963,6 +3053,7 @@ requires-dist = [ { name = "numpy", marker = "python_full_version >= '3.10' and extra == 'voice'", specifier = ">=2.2.0,<3" }, { name = "openai", specifier = ">=3.0.0,<4" }, { name = "opentelemetry-api", marker = "extra == 'opentelemetry'", specifier = ">=1.45.0,<2" }, + { name = "protobuf", marker = "extra == 'a2a'", specifier = ">=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*" }, { name = "protobuf", marker = "extra == 'dapr'", specifier = ">=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*" }, { name = "protobuf", marker = "extra == 'daytona'", specifier = ">=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*" }, { name = "protobuf", marker = "extra == 'e2b'", specifier = ">=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*" }, @@ -2989,7 +3080,7 @@ requires-dist = [ { name = "websockets", marker = "extra == 'realtime'", specifier = ">=15.0,<18" }, { name = "websockets", marker = "extra == 'voice'", specifier = ">=15.0,<18" }, ] -provides-extras = ["opentelemetry", "voice", "viz", "litellm", "any-llm", "realtime", "sqlalchemy", "encrypt", "redis", "dapr", "mongodb", "docker", "blaxel", "daytona", "cloudflare", "e2b", "modal", "vercel", "s3", "temporal"] +provides-extras = ["a2a", "opentelemetry", "voice", "viz", "litellm", "any-llm", "realtime", "sqlalchemy", "encrypt", "redis", "dapr", "mongodb", "docker", "blaxel", "daytona", "cloudflare", "e2b", "modal", "vercel", "s3", "temporal"] [package.metadata.requires-dev] dev = [ @@ -3348,6 +3439,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/cc/35/cc0aaecf278bb4575b8555f2b137de5ab821595ddae9da9d3cd1da4072c7/propcache-0.3.2-py3-none-any.whl", hash = "sha256:98f1ec44fb675f5052cccc8e609c46ed23a35a1cfd18545ad4e29002d858a43f", size = 12663, upload-time = "2025-06-09T22:56:04.484Z" }, ] +[[package]] +name = "proto-plus" +version = "1.29.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "protobuf" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/46/70/783e33ffbb4466cc154a94f79b869b92a451e2bd45605054e68ff68b7af6/proto_plus-1.29.0.tar.gz", hash = "sha256:cfb4e62ad7e13dd18f346cabbda00cab39930d36a05791fd81ddb074d6ee884f", size = 58592, upload-time = "2026-09-29T19:26:15.963Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b1/05/a3ef5b1161498e7b5a2a60288a9cf41b9149e94555423a43ec536737ac1a/proto_plus-1.29.0-py3-none-any.whl", hash = "sha256:8acd070469a7aaf43f440b022ef9757c8cac1a9f866e933f59ae98669ddc6c8b", size = 50786, upload-time = "2026-09-29T19:25:50.409Z" }, +] + [[package]] name = "protobuf" version = "6.33.6" @@ -3363,6 +3466,27 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c4/72/02445137af02769918a93807b2b7890047c32bfb9f90371cbc12688819eb/protobuf-6.33.6-py3-none-any.whl", hash = "sha256:77179e006c476e69bf8e8ce866640091ec42e1beb80b213c3900006ecfba6901", size = 170656, upload-time = "2026-03-18T19:04:59.826Z" }, ] +[[package]] +name = "pyasn1" +version = "0.6.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/88/7e/3c0da41061a2021cac7cd524fd57092adbe5b515e8bf9005702e366802e2/pyasn1-0.6.5.tar.gz", hash = "sha256:6b11616a6bcf3a40e635f082bb232fa57b5e0dd7f517bd7ddd69ec3794508a47", size = 155152, upload-time = "2026-10-27T06:32:49.125Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/19/1f/3eefd5c84c35cae44549ce1c7f7e58f7945b34f5a6bce07a135438522073/pyasn1-0.6.5-py3-none-any.whl", hash = "sha256:4017b0fce125096b8573b39c989fdb1a4b19cf761e683398184550fea0e66587", size = 84807, upload-time = "2026-10-27T06:32:48.045Z" }, +] + +[[package]] +name = "pyasn1-modules" +version = "0.4.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyasn1" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e9/e6/78ebbb10a8c8e4b61a59249394a4a594c1a7af95593dc933a349c8d00964/pyasn1_modules-0.4.2.tar.gz", hash = "sha256:677091de870a80aae844b1ca6134f54652fa2c8c5a52aa396440ac3106e941e6", size = 307892, upload-time = "2025-03-28T02:41:22.17Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/47/8d/d529b5d697919ba8c11ad626e835d4039be708a35b0d22de83a269a6682c/pyasn1_modules-0.4.2-py3-none-any.whl", hash = "sha256:29253a9207ce32b64c3ac6600edc75368f98473906e8fd1043bd6b5b1de2c14a", size = 181259, upload-time = "2025-03-28T02:41:19.028Z" }, +] + [[package]] name = "pycparser" version = "2.22" From b0804fa37c790c7acb5b31143e86c448dbc8c065 Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Mon, 23 Nov 2026 21:59:13 -0800 Subject: [PATCH 2/2] List currently authorized reservations in the task recovery example --- examples/a2a/README.md | 9 ++++----- examples/a2a/manager.py | 13 +++++++++++++ tests/test_a2a.py | 27 +++++++++++++++------------ 3 files changed, 32 insertions(+), 17 deletions(-) diff --git a/examples/a2a/README.md b/examples/a2a/README.md index f8c8a8590e..8ccdc19eb0 100644 --- a/examples/a2a/README.md +++ b/examples/a2a/README.md @@ -55,15 +55,14 @@ The example requires a cooperating receiver. Its business effect is one immutabl The manager reserves the owner, run and tool call ID in SQLite before sending. It binds the reservation to the name, approved endpoint, question digest and a new message ID. The reservation survives failure even if the request never reached the service. A new run or call ID permits a new send. -A failed run may leave the application without the question the model generated. The journal stores only its digest. On restart, reopen the same database and restore the registry for the authenticated owner and original run. To find the saved call IDs and specialist names, query the journal. +A failed run may leave the application without the question the model generated. The journal stores only its digest. On restart, reopen the same database and restore the registry for the authenticated owner and original run. List the call IDs and specialist names your current grants allow. ```python -calls = registry.db.execute( - "SELECT call_id, name FROM calls WHERE owner=? AND run_id=?", - (registry.owner, registry.run_id), -).fetchall() +calls = registry.reserved_calls() # (call_id, name) pairs ``` +Completed calls also have reservations. Listing them makes no network requests and does not verify their outcomes. + For the call you need to reconcile, use `verdict = await registry.recover(call_id)`. This application method never creates a reservation, sends a question or resumes the manager. If the manager repeats an existing call with identical arguments, `ask` uses the same read path. Both paths check the current grant for the saved name and endpoint. The trusted lookup must return the receiver's immutable `Receipt` for that owner, endpoint, message ID and question digest. Recovery then reads the task with `GetTask`. The example checks both task and context IDs, the completed state and a single text verdict matching the receipt. Only `yes` or `no` passes verification. diff --git a/examples/a2a/manager.py b/examples/a2a/manager.py index b668284cbf..9994c1b7d9 100644 --- a/examples/a2a/manager.py +++ b/examples/a2a/manager.py @@ -67,6 +67,19 @@ async def ask(self, call_id: str, name: str, question: str) -> str: task = await specialist.send_message(question, message_id=message_id) if created else None return await self._result(call_id, expected=binding, task=task) + def reserved_calls(self) -> list[tuple[str, str]]: + """List authorized (call ID, name) pairs for this run, including completed calls.""" + rows = self.db.execute( + "SELECT call_id, name, endpoint FROM calls WHERE owner=? AND run_id=?", + (self.owner, self.run_id), + ) + return [ + (call_id, name) + for call_id, name, endpoint in rows + if (specialist := self.specialists.get(name)) is not None + and specialist.rpc_url == endpoint + ] + async def recover(self, call_id: str) -> str: """Read a reserved call for this owner and run without sending a new message.""" return await self._result(call_id) diff --git a/tests/test_a2a.py b/tests/test_a2a.py index 16733db2d4..4088fa9125 100644 --- a/tests/test_a2a.py +++ b/tests/test_a2a.py @@ -226,6 +226,8 @@ def lookup(owner, url, message): assert "weather-west" in str(outputs["list"]) and "weather-east" in str(outputs["list"]) assert "other-" not in str(outputs["list"]) assert outputs["one"] == "no" and outputs["two"] == "yes" + east_only = replace(registry, specialists={"weather-east": names["weather-east"]}) + assert east_only.reserved_calls() == [("two", "weather-east")] assert east.methods == ["SendMessage"] assert west.methods == ["card", "SendMessage"] assert await run_manager(registry, [[ask("weather-east", "two")]]) == {"two": "yes"} @@ -261,20 +263,21 @@ def registry(db, peer, url): peer = Receiver(remote, "no") async with TestServer(peer.app, port=port): restored = registry(db, peer, url) - (call_id,) = db.execute( - "SELECT call_id FROM calls WHERE owner=? AND run_id=?", - (restored.owner, restored.run_id), - ).fetchone() + [(call_id, name)] = restored.reserved_calls() + assert name == "east" with pytest.raises(PermissionError): await restored.ask(call_id, "east", "Different?") - with pytest.raises(PermissionError): - await replace(restored, specialists={}).recover(call_id) - with pytest.raises(PermissionError): - await replace(restored, specialists={"east": stored(url + "/other")}).recover( - call_id - ) - with pytest.raises(UnresolvedCall): - await replace(restored, owner="foreign").recover(call_id) + for denied in ( + replace(restored, specialists={}), + replace(restored, specialists={"east": stored(url + "/other")}), + ): + assert denied.reserved_calls() == [] + with pytest.raises(PermissionError): + await denied.recover(call_id) + for other in (replace(restored, owner="foreign"), replace(restored, run_id="other")): + assert other.reserved_calls() == [] + with pytest.raises(UnresolvedCall): + await other.recover(call_id) with pytest.raises(UnresolvedCall): await restored.recover("missing") receipt = Receipt(*remote.execute("SELECT * FROM effects").fetchone())