Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions src/google/adk/a2a/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,13 @@
from a2a.types import TaskStatusUpdateEvent
from google.protobuf.json_format import MessageToDict
from google.protobuf.json_format import ParseDict
import httpx

from ..utils.context_utils import Aclosing

if TYPE_CHECKING:
from a2a.client import Client as A2AClient

# Re-exported: callers construct factories via ``_compat.A2AClientFactory``.
A2AClientFactory = _ClientFactory

Expand Down Expand Up @@ -662,6 +666,8 @@ def get_skill_security(
# ``ClientCallContext`` moved from ``a2a.client.middleware`` to ``a2a.client.client``
# ``A2AClientHTTPError`` is gone; use ``A2AClientError`` (carries status_code attr)
from a2a.client.errors import A2AClientError as _A2AClientError
from a2a.utils.errors import MethodNotFoundError as _MethodNotFoundError
from a2a.utils.errors import UnsupportedOperationError as _UnsupportedOperationError

A2A_HTTP_ERRORS = (_A2AClientError,)
else:
Expand All @@ -671,6 +677,9 @@ def get_skill_security(
)

A2A_HTTP_ERRORS = (A2AClientHTTPError,)
_LegacyJSONRPCError = _dynamic_type(
"a2a.client.errors", "A2AClientJSONRPCError"
)


# -----------------------------------------------------------------------------
Expand Down Expand Up @@ -868,6 +877,48 @@ async def send_message(
yield item


async def get_task(
client: A2AClient, *, task_id: str, context: Any = None
) -> Task:
"""Reads a task using the request type supported by the installed SDK."""
request_type = _dynamic_type(
"a2a.types", "GetTaskRequest" if IS_A2A_V1 else "TaskQueryParams"
)
return await client.get_task(request_type(id=task_id), context=context)


def is_get_task_unsupported(error: Exception) -> bool:
"""Returns whether the peer explicitly rejected the task lookup method."""
if not IS_A2A_V1:
# JSON-RPC method not found and A2A unsupported operation.
return isinstance(error, _LegacyJSONRPCError) and error.error.code in (
-32601,
-32004,
)
if isinstance(error, _UnsupportedOperationError):
return True
if not isinstance(error, _MethodNotFoundError):
return False

cause = error.__cause__
if not isinstance(cause, httpx.HTTPStatusError):
return True

# The REST client also maps a plain HTTP 404 to MethodNotFoundError.
try:
payload = cause.response.json()
except ValueError:
return False
status = payload.get("error") if isinstance(payload, dict) else None
details = status.get("details") if isinstance(status, dict) else None
return isinstance(details, list) and any(
isinstance(detail, dict)
and detail.get("@type") == "type.googleapis.com/google.rpc.ErrorInfo"
and detail.get("reason") == "METHOD_NOT_FOUND"
for detail in details
)


# -----------------------------------------------------------------------------
# Client config builder
# -----------------------------------------------------------------------------
Expand Down
111 changes: 111 additions & 0 deletions src/google/adk/a2a/agent/_remote_a2a_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -1974,6 +1974,109 @@ async def _handle_a2a_response_v2(
branch=ctx.branch,
)

async def _read_completed_peer_task(
self,
ctx: InvocationContext,
client: A2AClient,
request: A2AMessage,
parameters: ParametersConfig,
) -> Optional[Event]:
"""Reads a paused delegation's result if the peer finished out of band."""
if (
self.mode != AgentMode.TASK
or not request.task_id
or request.task_id
!= self._get_resumable_task_id(ctx, request.context_id)
):
return None

try:
task = await _compat.get_task(
client,
task_id=request.task_id,
context=parameters.client_call_context,
)
except Exception as error:
if _compat.is_get_task_unsupported(error):
return None
raise
if task.id != request.task_id or task.context_id != request.context_id:
raise A2AClientError("Peer returned a different task or context")
if task.status.state != _compat.TS_COMPLETED:
return None

if _compat.metadata_get(task.metadata, _NEW_A2A_ADK_INTEGRATION_EXTENSION):
event = await self._handle_a2a_response_v2((task, None), ctx)
else:
event = await self._handle_a2a_response((task, None), ctx)
completed_response = (
next(
(
response
for response in reversed(event.get_function_responses())
if response.name == FINISH_TASK_TOOL_NAME
and response.response
and response.response.get("result")
== FINISH_TASK_SUCCESS_RESULT
),
None,
)
if event is not None
else None
)
if completed_response is None:
return None
completed_id = completed_response.id

def output_args(source: Optional[Event]) -> Optional[dict[str, Any]]:
if source is None:
return None
return next(
(
dict(call.args or {})
for call in reversed(source.get_function_calls())
if call.name == FINISH_TASK_TOOL_NAME and call.id == completed_id
),
None,
)

args = output_args(event)
if args is None:
# A unary task snapshot can put only the response in its artifacts.
for message in reversed(task.history or []):
if message.role != _compat.ROLE_AGENT:
continue
args = output_args(
convert_a2a_message_to_event(
message, self.name, ctx, self._a2a_part_converter
)
)
if args is not None:
break
if args is None:
raise A2AClientError(
"Completed peer task has no matching finish_task call"
)

wrapper_key = get_output_wrapper_key(self.output_schema)
output = args[wrapper_key] if wrapper_key and wrapper_key in args else args
result = _create_finish_task_event(ctx, self.name, output=output)
result.custom_metadata = {
A2A_METADATA_PREFIX + "operation": "get_task",
A2A_METADATA_PREFIX + "task_id": task.id,
A2A_METADATA_PREFIX + "context_id": task.context_id,
A2A_METADATA_PREFIX + "request": {"id": task.id},
A2A_METADATA_PREFIX
+ "response": {
"id": task.id,
"contextId": task.context_id,
"status": {
"state": _compat.a2a_to_dict(task.status).get("state"),
},
},
}
return result

async def _run_async_impl(
self, ctx: InvocationContext
) -> AsyncGenerator[Event, None]:
Expand Down Expand Up @@ -2072,6 +2175,14 @@ async def _run_async_impl(
ctx, a2a_request
)

completed_event = await self._read_completed_peer_task(
ctx, a2a_client, a2a_request, parameters
)
if completed_event is not None:
should_release_task_control = True
yield completed_event
return

# TODO: Add support for requested_extension and
# message_send_configuration once they are supported by the A2A client.
# A single stateful normalizer per stream so incremental
Expand Down
Loading
Loading