Skip to content

Commit 6e1cb06

Browse files
authored
Merge branch 'main' into fix/a2a-1409-stale-interrupted-snapshot
2 parents 029706a + caab6a2 commit 6e1cb06

31 files changed

Lines changed: 1319 additions & 95 deletions

‎.github/CODEOWNERS‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,5 @@
44
# For syntax help see:
55
# https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners#codeowners-syntax
66

7-
* @a2aproject/google-a2a-eng
7+
* @a2aproject/google-a2a-python
88
src/a2a/types.py @a2a-bot

‎src/a2a/client/transports/http_helpers.py‎

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import json
2+
import re
23

34
from collections.abc import AsyncGenerator, Callable, Iterator
45
from contextlib import contextmanager
@@ -65,6 +66,39 @@ async def send_http_request(
6566
return response.json()
6667

6768

69+
_SSE_LINE_END = re.compile(r'\r\n|\r|\n')
70+
71+
72+
async def _aiter_sse_lines(
73+
response: httpx.Response,
74+
) -> AsyncGenerator[str, None]:
75+
"""Yields lines ended only by CRLF, LF or CR, unlike `aiter_lines()`.
76+
77+
The unfinished line is kept as a list of pieces and joined once, and
78+
only the new chunk is scanned, so a long `data:` line that spans many
79+
chunks costs linear rather than quadratic time.
80+
"""
81+
pieces: list[str] = []
82+
held_cr = False
83+
async for chunk in response.aiter_text():
84+
text = '\r' + chunk if held_cr else chunk
85+
# Hold a trailing CR back: the next chunk may start with its LF.
86+
held_cr = text.endswith('\r')
87+
*lines, rest = _SSE_LINE_END.split(text[:-1] if held_cr else text)
88+
if lines:
89+
lines[0] = ''.join(pieces) + lines[0]
90+
pieces = []
91+
for line in lines:
92+
yield line
93+
if rest:
94+
pieces.append(rest)
95+
tail = ''.join(pieces)
96+
# A held CR at end of stream still ends a line, even an empty one. That
97+
# blank line is what dispatches the last event, so yield it too.
98+
if held_cr or tail:
99+
yield tail
100+
101+
68102
async def parse_sse_stream(
69103
response: httpx.Response,
70104
) -> AsyncGenerator[tuple[str, str], None]:
@@ -75,9 +109,7 @@ async def parse_sse_stream(
75109
event_name = 'message'
76110
payload_chunks: list[str] = []
77111

78-
async for line in response.aiter_lines():
79-
raw_line = line.rstrip('\r\n')
80-
112+
async for raw_line in _aiter_sse_lines(response):
81113
# Empty line denotes the completion of the current event block
82114
if not raw_line:
83115
if payload_chunks:
@@ -142,8 +174,9 @@ async def send_http_stream_request(
142174
raise e
143175

144176
# If the response is not a stream, read it standardly (e.g., upfront JSON-RPC error payload)
145-
if 'text/event-stream' not in response.headers.get(
146-
'content-type', ''
177+
if (
178+
'text/event-stream'
179+
not in response.headers.get('content-type', '').lower()
147180
):
148181
content = await response.aread()
149182
yield content.decode('utf-8')

‎src/a2a/client/transports/rest.py‎

Lines changed: 43 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from collections.abc import AsyncGenerator
55
from typing import Any, NoReturn
6+
from urllib.parse import quote
67

78
import httpx
89

@@ -13,6 +14,7 @@
1314
from a2a.client.transports.base import ClientTransport
1415
from a2a.client.transports.http_helpers import (
1516
get_http_args,
17+
handle_http_exceptions,
1618
send_http_request,
1719
send_http_stream_request,
1820
)
@@ -89,6 +91,11 @@ def _parse_rest_error(
8991
return None
9092

9193

94+
def _quote_id(value: str) -> str:
95+
"""Percent-encodes an id so it stays a single URL path segment."""
96+
return quote(value, safe='')
97+
98+
9299
@trace_class(kind=SpanKind.CLIENT)
93100
class RestTransport(ClientTransport):
94101
"""A REST transport for the A2A client."""
@@ -158,7 +165,7 @@ async def get_task(
158165

159166
response_data = await self._execute_request(
160167
'GET',
161-
f'/tasks/{request.id}',
168+
f'/tasks/{_quote_id(request.id)}',
162169
request.tenant,
163170
context=context,
164171
params=params,
@@ -198,7 +205,7 @@ async def cancel_task(
198205
"""Requests the agent to cancel a specific task."""
199206
response_data = await self._execute_request(
200207
'POST',
201-
f'/tasks/{request.id}:cancel',
208+
f'/tasks/{_quote_id(request.id)}:cancel',
202209
request.tenant,
203210
context=context,
204211
json=MessageToDict(request),
@@ -215,7 +222,7 @@ async def create_task_push_notification_config(
215222
"""Sets or updates the push notification configuration for a specific task."""
216223
response_data = await self._execute_request(
217224
'POST',
218-
f'/tasks/{request.task_id}/pushNotificationConfigs',
225+
f'/tasks/{_quote_id(request.task_id)}/pushNotificationConfigs',
219226
request.tenant,
220227
context=context,
221228
json=MessageToDict(request),
@@ -242,7 +249,8 @@ async def get_task_push_notification_config(
242249

243250
response_data = await self._execute_request(
244251
'GET',
245-
f'/tasks/{request.task_id}/pushNotificationConfigs/{request.id}',
252+
f'/tasks/{_quote_id(request.task_id)}'
253+
f'/pushNotificationConfigs/{_quote_id(request.id)}',
246254
request.tenant,
247255
context=context,
248256
params=params,
@@ -267,7 +275,7 @@ async def list_task_push_notification_configs(
267275

268276
response_data = await self._execute_request(
269277
'GET',
270-
f'/tasks/{request.task_id}/pushNotificationConfigs',
278+
f'/tasks/{_quote_id(request.task_id)}/pushNotificationConfigs',
271279
request.tenant,
272280
context=context,
273281
params=params,
@@ -292,13 +300,24 @@ async def delete_task_push_notification_config(
292300
if 'tenant' in params:
293301
del params['tenant']
294302

295-
await self._execute_request(
296-
'DELETE',
297-
f'/tasks/{request.task_id}/pushNotificationConfigs/{request.id}',
303+
path = self._get_path(
304+
f'/tasks/{_quote_id(request.task_id)}'
305+
f'/pushNotificationConfigs/{_quote_id(request.id)}',
298306
request.tenant,
299-
context=context,
307+
)
308+
http_request = self.httpx_client.build_request(
309+
'DELETE',
310+
f'{self.url}{path}',
300311
params=params,
312+
**get_http_args(context),
301313
)
314+
if self.httpx_client.is_closed:
315+
raise A2AClientError('HTTP client is closed')
316+
# The body is not read: servers confirm the deletion with `{}`,
317+
# with 204 No Content, or with a 200 that has no body.
318+
with handle_http_exceptions(self._handle_http_error):
319+
response = await self.httpx_client.send(http_request)
320+
response.raise_for_status()
302321

303322
async def subscribe(
304323
self,
@@ -309,7 +328,7 @@ async def subscribe(
309328
"""Reconnects to get task updates."""
310329
async for event in self._send_stream_request(
311330
'POST',
312-
f'/tasks/{request.id}:subscribe',
331+
f'/tasks/{_quote_id(request.id)}:subscribe',
313332
request.tenant,
314333
context=context,
315334
):
@@ -399,8 +418,22 @@ async def _send_stream_request(
399418
**http_kwargs,
400419
):
401420
event: StreamResponse = parse_lenient(sse_data, StreamResponse())
421+
if event.WhichOneof('payload') is None:
422+
self._raise_in_band_error(sse_data)
402423
yield event
403424

425+
def _raise_in_band_error(self, sse_data: str) -> None:
426+
"""Raises the error carried by a data event, if it carries one.
427+
428+
The HTTP+JSON binding defines no SSE event type for errors, so a
429+
server may send the ``google.rpc.Status`` body as an ordinary data
430+
event instead of an ``event: error`` one. ``StreamResponse`` has no
431+
``error`` field, so that body parses to an event with no payload.
432+
"""
433+
payload = json.loads(sse_data)
434+
if isinstance(payload, dict) and 'error' in payload:
435+
self._handle_sse_error(sse_data)
436+
404437
async def _send_request(self, request: httpx.Request) -> dict[str, Any]:
405438
return await send_http_request(
406439
self.httpx_client, request, self._handle_http_error

‎src/a2a/client/transports/tenant_decorator.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import copy
2+
13
from collections.abc import AsyncGenerator
24

35
from a2a.client.client import ClientCallContext
@@ -44,6 +46,7 @@ async def send_message(
4446
context: ClientCallContext | None = None,
4547
) -> SendMessageResponse:
4648
"""Sends a streaming message request to the agent and yields responses as they arrive."""
49+
request = copy.deepcopy(request)
4750
request.tenant = self._resolve_tenant(request.tenant)
4851
return await self._base.send_message(request, context=context)
4952

@@ -54,6 +57,7 @@ async def send_message_streaming(
5457
context: ClientCallContext | None = None,
5558
) -> AsyncGenerator[StreamResponse]:
5659
"""Sends a streaming message request to the agent and yields responses."""
60+
request = copy.deepcopy(request)
5761
request.tenant = self._resolve_tenant(request.tenant)
5862
async for event in self._base.send_message_streaming(
5963
request, context=context
@@ -67,6 +71,7 @@ async def get_task(
6771
context: ClientCallContext | None = None,
6872
) -> Task:
6973
"""Retrieves the current state and history of a specific task."""
74+
request = copy.deepcopy(request)
7075
request.tenant = self._resolve_tenant(request.tenant)
7176
return await self._base.get_task(request, context=context)
7277

@@ -77,6 +82,7 @@ async def list_tasks(
7782
context: ClientCallContext | None = None,
7883
) -> ListTasksResponse:
7984
"""Retrieves tasks for an agent."""
85+
request = copy.deepcopy(request)
8086
request.tenant = self._resolve_tenant(request.tenant)
8187
return await self._base.list_tasks(request, context=context)
8288

@@ -87,6 +93,7 @@ async def cancel_task(
8793
context: ClientCallContext | None = None,
8894
) -> Task:
8995
"""Requests the agent to cancel a specific task."""
96+
request = copy.deepcopy(request)
9097
request.tenant = self._resolve_tenant(request.tenant)
9198
return await self._base.cancel_task(request, context=context)
9299

@@ -97,6 +104,7 @@ async def create_task_push_notification_config(
97104
context: ClientCallContext | None = None,
98105
) -> TaskPushNotificationConfig:
99106
"""Sets or updates the push notification configuration for a specific task."""
107+
request = copy.deepcopy(request)
100108
request.tenant = self._resolve_tenant(request.tenant)
101109
return await self._base.create_task_push_notification_config(
102110
request, context=context
@@ -109,6 +117,7 @@ async def get_task_push_notification_config(
109117
context: ClientCallContext | None = None,
110118
) -> TaskPushNotificationConfig:
111119
"""Retrieves the push notification configuration for a specific task."""
120+
request = copy.deepcopy(request)
112121
request.tenant = self._resolve_tenant(request.tenant)
113122
return await self._base.get_task_push_notification_config(
114123
request, context=context
@@ -121,6 +130,7 @@ async def list_task_push_notification_configs(
121130
context: ClientCallContext | None = None,
122131
) -> ListTaskPushNotificationConfigsResponse:
123132
"""Lists push notification configurations for a specific task."""
133+
request = copy.deepcopy(request)
124134
request.tenant = self._resolve_tenant(request.tenant)
125135
return await self._base.list_task_push_notification_configs(
126136
request, context=context
@@ -133,6 +143,7 @@ async def delete_task_push_notification_config(
133143
context: ClientCallContext | None = None,
134144
) -> None:
135145
"""Deletes the push notification configuration for a specific task."""
146+
request = copy.deepcopy(request)
136147
request.tenant = self._resolve_tenant(request.tenant)
137148
await self._base.delete_task_push_notification_config(
138149
request, context=context
@@ -145,6 +156,7 @@ async def subscribe(
145156
context: ClientCallContext | None = None,
146157
) -> AsyncGenerator[StreamResponse]:
147158
"""Reconnects to get task updates."""
159+
request = copy.deepcopy(request)
148160
request.tenant = self._resolve_tenant(request.tenant)
149161
async for event in self._base.subscribe(request, context=context):
150162
yield event
@@ -156,6 +168,7 @@ async def get_extended_agent_card(
156168
context: ClientCallContext | None = None,
157169
) -> AgentCard:
158170
"""Retrieves the Extended AgentCard."""
171+
request = copy.deepcopy(request)
159172
request.tenant = self._resolve_tenant(request.tenant)
160173
return await self._base.get_extended_agent_card(
161174
request,

‎src/a2a/compat/v0_3/grpc_transport.py‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22

33
from collections.abc import AsyncGenerator, Callable
44
from functools import wraps
5-
from typing import Any, NoReturn
5+
from typing import Any, NoReturn, cast
66

77
from a2a.client.errors import A2AClientError, A2AClientTimeoutError
8-
from a2a.utils.errors import JSON_RPC_ERROR_CODE_MAP
8+
from a2a.utils.errors import A2A_REASON_TO_ERROR, JSON_RPC_ERROR_CODE_MAP
99

1010

1111
try:
@@ -18,6 +18,10 @@
1818
) from e
1919

2020

21+
from google.rpc import ( # type: ignore[reportMissingModuleSource]
22+
error_details_pb2,
23+
)
24+
2125
from a2a.client.client import ClientCallContext, ClientConfig
2226
from a2a.client.optionals import Channel
2327
from a2a.client.transports.base import ClientTransport
@@ -33,6 +37,7 @@
3337
from a2a.compat.v0_3.extension_headers import add_legacy_extension_header
3438
from a2a.types import a2a_pb2
3539
from a2a.utils.constants import PROTOCOL_VERSION_0_3, VERSION_HEADER
40+
from a2a.utils.grpc_status import status_from_call
3641
from a2a.utils.telemetry import SpanKind, trace_class
3742

3843

@@ -53,6 +58,18 @@ def _map_grpc_error(e: grpc.aio.AioRpcError) -> NoReturn:
5358
exception_cls = _A2A_ERROR_NAME_TO_CLS.get(error_type_name)
5459
if exception_cls:
5560
raise exception_cls(error_message) from e
61+
62+
# Other v0.3 servers (a2a-go) name the error in ErrorInfo.reason instead.
63+
status = status_from_call(cast('grpc.Call', e))
64+
if status is not None:
65+
for detail in status.details:
66+
# `.DESCRIPTOR` is typed as a py/C union; `.Is` wants a Descriptor.
67+
if detail.Is(error_details_pb2.ErrorInfo.DESCRIPTOR): # ty: ignore[invalid-argument-type]
68+
error_info = error_details_pb2.ErrorInfo()
69+
detail.Unpack(error_info)
70+
exception_cls = A2A_REASON_TO_ERROR.get(error_info.reason)
71+
if error_info.domain == 'a2a-protocol.org' and exception_cls:
72+
raise exception_cls(status.message) from e
5673
raise A2AClientError(f'gRPC Error {e.code().name}: {e.details()}') from e
5774

5875

0 commit comments

Comments
 (0)