Skip to content

Commit a9e1e54

Browse files
committed
Merge remote-tracking branch 'upstream/main' into fix/1331-failed-timestamp
2 parents a5b7d92 + 09c9347 commit a9e1e54

25 files changed

Lines changed: 946 additions & 60 deletions

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

Lines changed: 35 additions & 3 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:

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

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from a2a.client.transports.base import ClientTransport
1515
from a2a.client.transports.http_helpers import (
1616
get_http_args,
17+
handle_http_exceptions,
1718
send_http_request,
1819
send_http_stream_request,
1920
)
@@ -299,14 +300,24 @@ async def delete_task_push_notification_config(
299300
if 'tenant' in params:
300301
del params['tenant']
301302

302-
await self._execute_request(
303-
'DELETE',
303+
path = self._get_path(
304304
f'/tasks/{_quote_id(request.task_id)}'
305305
f'/pushNotificationConfigs/{_quote_id(request.id)}',
306306
request.tenant,
307-
context=context,
307+
)
308+
http_request = self.httpx_client.build_request(
309+
'DELETE',
310+
f'{self.url}{path}',
308311
params=params,
312+
**get_http_args(context),
309313
)
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()
310321

311322
async def subscribe(
312323
self,
@@ -407,8 +418,22 @@ async def _send_stream_request(
407418
**http_kwargs,
408419
):
409420
event: StreamResponse = parse_lenient(sse_data, StreamResponse())
421+
if event.WhichOneof('payload') is None:
422+
self._raise_in_band_error(sse_data)
410423
yield event
411424

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+
412437
async def _send_request(self, request: httpx.Request) -> dict[str, Any]:
413438
return await send_http_request(
414439
self.httpx_client, request, self._handle_http_error

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

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -574,7 +574,9 @@ def oauth2_flows(cls, flows: types.OAuthFlows) -> a2a_pb2.OAuthFlows:
574574
token_url=flows.password.token_url,
575575
),
576576
)
577-
raise ValueError('Unknown oauth flow definition')
577+
# No v0.3 flow is set, e.g. for a v1.0 device code flow, which v0.3
578+
# does not have.
579+
return a2a_pb2.OAuthFlows()
578580

579581
@classmethod
580582
def skill(cls, skill: types.AgentSkill) -> a2a_pb2.AgentSkill:
@@ -1058,13 +1060,15 @@ def oauth2_flows(cls, flows: a2a_pb2.OAuthFlows) -> types.OAuthFlows:
10581060
scopes=dict(flows.implicit.scopes.items()),
10591061
),
10601062
)
1061-
return types.OAuthFlows(
1062-
password=types.PasswordOAuthFlow(
1063-
refresh_url=flows.password.refresh_url,
1064-
scopes=dict(flows.password.scopes.items()),
1065-
token_url=flows.password.token_url,
1066-
),
1067-
)
1063+
if flows.HasField('password'):
1064+
return types.OAuthFlows(
1065+
password=types.PasswordOAuthFlow(
1066+
refresh_url=flows.password.refresh_url,
1067+
scopes=dict(flows.password.scopes.items()),
1068+
token_url=flows.password.token_url,
1069+
),
1070+
)
1071+
return types.OAuthFlows()
10681072

10691073
@classmethod
10701074
def stream_response(

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,12 @@ def routes(self) -> dict[tuple[str, str], Callable[[Request], Any]]:
148148
): functools.partial(
149149
self._handle_request, self.handler.get_push_notification
150150
),
151+
(
152+
'/v1/tasks/{id}/pushNotificationConfigs/{push_id}',
153+
'DELETE',
154+
): functools.partial(
155+
self._handle_request, self.handler.delete_push_notification
156+
),
151157
(
152158
'/v1/tasks/{id}/pushNotificationConfigs',
153159
'POST',

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

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,36 @@ async def get_push_notification(
194194
)
195195
return MessageToDict(pb2_v03_config)
196196

197+
@validate_version(constants.PROTOCOL_VERSION_0_3)
198+
async def delete_push_notification(
199+
self,
200+
request: Request,
201+
context: ServerCallContext,
202+
) -> dict[str, Any]:
203+
"""Handles the 'tasks/pushNotificationConfig/delete' REST method.
204+
205+
Args:
206+
request: The incoming `Request` object.
207+
context: Context provided by the server.
208+
209+
Returns:
210+
An empty `dict`, the JSON form of `google.protobuf.Empty`.
211+
"""
212+
task_id = request.path_params['id']
213+
push_id = request.path_params['push_id']
214+
215+
rpc_req = types_v03.DeleteTaskPushNotificationConfigRequest(
216+
id='',
217+
params=types_v03.DeleteTaskPushNotificationConfigParams(
218+
id=task_id, push_notification_config_id=push_id
219+
),
220+
)
221+
222+
await self.handler03.on_delete_task_push_notification_config(
223+
rpc_req, context
224+
)
225+
return {}
226+
197227
@validate_version(constants.PROTOCOL_VERSION_0_3)
198228
async def set_push_notification(
199229
self,

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

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from collections.abc import AsyncGenerator
66
from typing import Any, NoReturn
7+
from urllib.parse import quote
78

89
import httpx
910

@@ -58,6 +59,11 @@
5859
}
5960

6061

62+
def _quote_id(value: str) -> str:
63+
"""Percent-encodes an id so it stays a single URL path segment."""
64+
return quote(value, safe='')
65+
66+
6167
@trace_class(kind=SpanKind.CLIENT)
6268
class CompatRestTransport(ClientTransport):
6369
"""A backward compatible REST transport for A2A v0.3."""
@@ -101,7 +107,7 @@ async def send_message(
101107
'POST',
102108
'/v1/message:send',
103109
context=context,
104-
json=MessageToDict(req_proto, preserving_proto_field_name=True),
110+
json=MessageToDict(req_proto),
105111
)
106112

107113
resp_proto = ParseDict(
@@ -146,7 +152,7 @@ async def send_message_streaming(
146152
'POST',
147153
'/v1/message:stream',
148154
context=context,
149-
json=MessageToDict(req_proto, preserving_proto_field_name=True),
155+
json=MessageToDict(req_proto),
150156
):
151157
yield event
152158

@@ -163,7 +169,7 @@ async def get_task(
163169

164170
response_data = await self._execute_request(
165171
'GET',
166-
f'/v1/tasks/{request.id}',
172+
f'/v1/tasks/{_quote_id(request.id)}',
167173
context=context,
168174
params=params,
169175
)
@@ -192,7 +198,7 @@ async def cancel_task(
192198
"""Requests the agent to cancel a specific task."""
193199
response_data = await self._execute_request(
194200
'POST',
195-
f'/v1/tasks/{request.id}:cancel',
201+
f'/v1/tasks/{_quote_id(request.id)}:cancel',
196202
context=context,
197203
)
198204
resp_proto = ParseDict(
@@ -221,9 +227,9 @@ async def create_task_push_notification_config(
221227
)
222228
response_data = await self._execute_request(
223229
'POST',
224-
f'/v1/tasks/{request.task_id}/pushNotificationConfigs',
230+
f'/v1/tasks/{_quote_id(request.task_id)}/pushNotificationConfigs',
225231
context=context,
226-
json=MessageToDict(req_proto, preserving_proto_field_name=True),
232+
json=MessageToDict(req_proto),
227233
)
228234
resp_proto = ParseDict(
229235
response_data,
@@ -243,7 +249,8 @@ async def get_task_push_notification_config(
243249
"""Retrieves the push notification configuration for a specific task."""
244250
response_data = await self._execute_request(
245251
'GET',
246-
f'/v1/tasks/{request.task_id}/pushNotificationConfigs/{request.id}',
252+
f'/v1/tasks/{_quote_id(request.task_id)}'
253+
f'/pushNotificationConfigs/{_quote_id(request.id)}',
247254
context=context,
248255
)
249256
resp_proto = ParseDict(
@@ -264,7 +271,7 @@ async def list_task_push_notification_configs(
264271
"""Lists push notification configurations for a specific task."""
265272
response_data = await self._execute_request(
266273
'GET',
267-
f'/v1/tasks/{request.task_id}/pushNotificationConfigs',
274+
f'/v1/tasks/{_quote_id(request.task_id)}/pushNotificationConfigs',
268275
context=context,
269276
)
270277
resp_proto = ParseDict(
@@ -285,8 +292,10 @@ async def delete_task_push_notification_config(
285292
context: ClientCallContext | None = None,
286293
) -> None:
287294
"""Deletes the push notification configuration for a specific task."""
288-
raise NotImplementedError(
289-
'delete_task_push_notification_config not supported in v0.3 REST'
295+
await self._execute_request(
296+
'DELETE',
297+
f'/v1/tasks/{request.task_id}/pushNotificationConfigs/{request.id}',
298+
context=context,
290299
)
291300

292301
async def subscribe(
@@ -308,7 +317,7 @@ async def subscribe(
308317
try:
309318
async for event in self._send_stream_request(
310319
subscribe_method,
311-
f'/v1/tasks/{request.id}:subscribe',
320+
f'/v1/tasks/{_quote_id(request.id)}:subscribe',
312321
context=context,
313322
):
314323
yield event

‎src/a2a/server/request_handlers/default_request_handler.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,9 @@ async def _setup_message_execution(
316316
)
317317

318318
task = task_manager.update_with_message(params.message, task)
319+
# Agents must infer the contextId from the task when the message
320+
# names only a taskId.
321+
context_id = context_id or task.context_id
319322
elif params.message.task_id:
320323
raise TaskNotFoundError(
321324
message=f'Task {params.message.task_id} was specified but does not exist'
@@ -325,7 +328,7 @@ async def _setup_message_execution(
325328
request_context = await self._request_context_builder.build(
326329
params=params,
327330
task_id=task.id if task else None,
328-
context_id=params.message.context_id,
331+
context_id=context_id,
329332
task=task,
330333
context=context,
331334
)

‎src/a2a/server/request_handlers/default_request_handler_v2.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,6 +432,9 @@ async def _setup_active_task(
432432
f'context {task.context_id} of task {original_task_id}'
433433
)
434434
)
435+
# Agents must infer the contextId from the task when the message
436+
# names only a taskId.
437+
original_context_id = original_context_id or task.context_id
435438

436439
# Build context to resolve or generate missing IDs
437440
request_context = await self._request_context_builder.build(

‎src/a2a/server/tasks/database_task_store.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -345,7 +345,7 @@ def _after_cursor(self, cursor: ListTasksCursor) -> Any:
345345
)
346346
try:
347347
cursor_timestamp = _ns_to_datetime(cursor.timestamp_ns)
348-
except OverflowError as e:
348+
except (OverflowError, ValueError) as e:
349349
raise InvalidParamsError('Invalid page token') from e
350350
return or_(
351351
timestamp_col < cursor_timestamp,

‎src/a2a/utils/proto_utils.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def parse_lenient(
7070
7171
Raises:
7272
ParseError: If the data is not valid ProtoJSON, including bytes that
73-
are not valid UTF-8.
73+
are not valid UTF-8 and decoded values that are not objects.
7474
"""
7575
if isinstance(data, bytes):
7676
try:
@@ -79,6 +79,14 @@ def parse_lenient(
7979
raise ParseError(f'Failed to load JSON: {e}.') from e
8080
if isinstance(data, str):
8181
return Parse(data, message, ignore_unknown_fields=True)
82+
# A message is a JSON object. With ignore_unknown_fields, ParseDict reads
83+
# an empty list as an empty message (it iterates the value as if it were
84+
# the object's keys), and raises TypeError for null or a number.
85+
if not isinstance(data, dict):
86+
raise ParseError(
87+
f'Expected a JSON object for {message.DESCRIPTOR.name}, '
88+
f'got {type(data).__name__}.'
89+
)
8290
return ParseDict(data, message, ignore_unknown_fields=True)
8391

8492

0 commit comments

Comments
 (0)