Skip to content
Closed
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: 49 additions & 2 deletions src/google/adk/a2a/executor/a2a_agent_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import inspect
import logging
import os
from typing import Awaitable
from typing import Callable

Expand Down Expand Up @@ -43,6 +44,44 @@
from .utils import _enqueue_canceled_task_event
from .utils import _require_request_context
from .utils import execute_after_agent_interceptors

#: Env var that puts exception text back into the failure message sent to the peer.
#: Off by default, and meant for local debugging only: enabling it on a
#: network-reachable deployment restores the disclosure the opaque id exists to
#: prevent.
_DEBUG_ERRORS_ENV_VAR = 'ADK_DEBUG_ERRORS'

#: Length of the correlation id, matching ``newErrorId()`` in adk-java.
_ERROR_ID_LENGTH = 12

#: Fixed summary the peer receives. It deliberately carries no throwable text.
_FAILURE_SUMMARY = 'Agent execution failed.'


def _new_error_id() -> str:
"""Returns a short opaque id correlating a peer-visible failure with the log."""
return platform_uuid.new_uuid().replace('-', '')[:_ERROR_ID_LENGTH]


def _debug_errors_enabled() -> bool:
"""Whether exception text should be echoed to the peer. Local debugging only."""
value = os.environ.get(_DEBUG_ERRORS_ENV_VAR, '')
return value.strip().lower() in ('1', 'true', 'yes', 'on')


def failure_text(error: Exception, error_id: str) -> str:
"""Builds the failure text handed back to the remote peer.

The peer is not trusted with the throwable: exception text routinely names
absolute filesystem paths, module locations, configuration values and echoed
request payloads, none of which the caller needs and all of which are useful
reconnaissance. Set ``ADK_DEBUG_ERRORS=1`` to restore the old behaviour while
debugging locally.
"""
text = f'{_FAILURE_SUMMARY} (error_id: {error_id})'
if _debug_errors_enabled():
text = f'{text} {error}'
return text
from .utils import execute_after_event_interceptors
from .utils import execute_before_agent_interceptors

Expand Down Expand Up @@ -152,7 +191,15 @@ async def execute(
try:
await self._handle_request(context, event_queue)
except Exception as e:
logger.error('Error handling A2A request: %s', e, exc_info=True)
# Logged in full here, under a short opaque id. The peer receives only that
# id, never the throwable text - see failure_text().
error_id = _new_error_id()
logger.error(
'Error handling A2A request [error_id=%s]: %s',
error_id,
e,
exc_info=True,
)
# Publish failure event
try:
await event_queue.enqueue_event(
Expand All @@ -164,7 +211,7 @@ async def execute(
message=Message(
message_id=platform_uuid.new_uuid(),
role=_compat.ROLE_AGENT,
parts=[_compat.make_text_part(str(e))],
parts=[_compat.make_text_part(failure_text(e, error_id))],
),
),
final=True,
Expand Down
26 changes: 25 additions & 1 deletion src/google/adk/models/lite_llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -1012,6 +1012,14 @@ class FunctionChunk(BaseModel):
name: Optional[str]
args: Optional[str]
index: Optional[int] = 0
# Signature-bearing fields: Gemini thinking models attach a thought_signature to
# each function call, and on the OpenAI-compatible route it rides in
# extra_content.google.thought_signature (Vertex also uses
# provider_specific_fields). The streamed delta carries them, so they must be
# captured here or the reassembled tool call loses the signature and the
# follow-up request is rejected.
extra_content: Optional[dict] = None
provider_specific_fields: Optional[dict] = None


class TextChunk(BaseModel):
Expand Down Expand Up @@ -2710,6 +2718,8 @@ def _has_meaningful_signal(message: Message | Delta | None) -> bool:
name=func_name,
args=func_args,
index=func_index,
extra_content=tool_call.get("extra_content"),
provider_specific_fields=tool_call.get("provider_specific_fields"),
), finish_reason

if finish_reason and not (message_content or tool_calls or reasoning_parts):
Expand Down Expand Up @@ -3817,6 +3827,8 @@ def _finalize_tool_call_response(
arguments=args,
),
index=index,
extra_content=func_data.get("extra_content"),
provider_specific_fields=func_data.get("provider_specific_fields"),
)
)

Expand Down Expand Up @@ -3927,7 +3939,13 @@ def _reset_stream_buffers() -> None:
if isinstance(chunk, FunctionChunk):
index = chunk.index or fallback_index
if index not in function_calls:
function_calls[index] = {"name": "", "args_parts": [], "id": None}
function_calls[index] = {
"name": "",
"args_parts": [],
"id": None,
"extra_content": None,
"provider_specific_fields": None,
}

if chunk.name:
function_calls[index]["name"] += chunk.name
Expand All @@ -3950,6 +3968,12 @@ def _reset_stream_buffers() -> None:
function_calls[index]["id"] = (
chunk.id or function_calls[index]["id"] or str(index)
)
if chunk.extra_content:
function_calls[index]["extra_content"] = chunk.extra_content
if chunk.provider_specific_fields:
function_calls[index]["provider_specific_fields"] = (
chunk.provider_specific_fields
)

partial_args = None
if chunk.args:
Expand Down
11 changes: 10 additions & 1 deletion src/google/adk/tools/_automatic_function_calling_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,16 @@ def build_function_declaration(
)
setattr(new_func, '__signature__', new_sig)
new_func.__doc__ = original.__doc__
new_func.__annotations__ = original.__annotations__
# Only carry over annotations for parameters that survive into new_sig. Copying the
# original mapping wholesale leaves annotations for the ignored parameters in place,
# and typing.get_type_hints() then tries to resolve them - so a context parameter
# annotated with a TYPE_CHECKING-only import raises NameError even though the
# parameter is not part of the declaration.
new_func.__annotations__ = {
name: annotation
for name, annotation in original.__annotations__.items()
if name not in ignore_params
}
return from_function_with_options(new_func, variant)


Expand Down
54 changes: 54 additions & 0 deletions tests/unittests/a2a/executor/test_a2a_agent_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
# limitations under the License.

import asyncio
import os
import re
from unittest.mock import AsyncMock
from unittest.mock import Mock
from unittest.mock import patch
Expand Down Expand Up @@ -90,6 +92,15 @@ def _final_events(call_args_list):
return [e for e in events if getattr(e, "final", False)]


def _part_text(part) -> str:
"""Reads the text out of a Part on both A2A v1 (flat) and 0.3.x (union)."""
direct = getattr(part, 'text', None)
if direct:
return direct
root = getattr(part, 'root', None)
return getattr(root, 'text', '') or ''


class TestA2aAgentExecutor:
"""Test suite for A2aAgentExecutor class."""

Expand Down Expand Up @@ -289,6 +300,49 @@ def test_check_new_version_extension_activation_is_version_aware(self):
_NEW_A2A_ADK_INTEGRATION_EXTENSION
)

@pytest.mark.asyncio
async def test_failure_event_does_not_leak_exception_text(self):
"""The remote peer must not receive the throwable's message."""
secret = (
'Runner error: /home/victim/.config/adk/credentials.json (No such file)'
)
self.executor._handle_request = AsyncMock(side_effect=RuntimeError(secret))

await self.executor.execute(self.mock_context, self.mock_event_queue)

events = [c.args[0] for c in self.mock_event_queue.enqueue_event.call_args_list]
statuses = [
e.status
for e in events
if getattr(e, 'status', None) is not None
]
assert statuses, 'a failed status event should reach the peer'
parts = statuses[-1].message.parts
text = ''.join(_part_text(p) for p in parts)

assert re.fullmatch(
r'Agent execution failed\. \(error_id: [0-9a-f]{12}\)', text
), text
assert secret not in text
assert '/home/victim' not in text

@pytest.mark.asyncio
async def test_failure_event_leaks_when_debug_errors_enabled(self):
"""ADK_DEBUG_ERRORS restores exception text, for local debugging only."""
secret = 'boom at /home/victim/secret'
self.executor._handle_request = AsyncMock(side_effect=RuntimeError(secret))

with patch.dict(os.environ, {'ADK_DEBUG_ERRORS': '1'}):
await self.executor.execute(self.mock_context, self.mock_event_queue)

events = [c.args[0] for c in self.mock_event_queue.enqueue_event.call_args_list]
statuses = [
e.status for e in events if getattr(e, 'status', None) is not None
]
parts = statuses[-1].message.parts
text = ''.join(_part_text(p) for p in parts)
assert secret in text

@pytest.mark.asyncio
async def test_execute_no_message_error(self):
"""Test execution fails when no message is provided."""
Expand Down
9 changes: 9 additions & 0 deletions tests/unittests/code_executors/test_gke_code_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,15 @@ def mock_k8s_clients():
mock_core_v1 = MagicMock(spec=client.CoreV1Api)
mock_client_class.BatchV1Api.return_value = mock_batch_v1
mock_client_class.CoreV1Api.return_value = mock_core_v1
# _add_owner_reference copies these four fields into a V1OwnerReference, and
# kubernetes 37 validates their types with pydantic. An unconfigured MagicMock
# returns a MagicMock for each, which no longer validates as a string, so give
# the created Job the string fields a real cluster would return.
mock_batch_v1.create_namespaced_job.return_value = client.V1Job(
api_version="batch/v1",
kind="Job",
metadata=client.V1ObjectMeta(name="test-job-name", uid="test-job-uid"),
)
yield {
"batch_v1": mock_batch_v1,
"core_v1": mock_core_v1,
Expand Down
100 changes: 100 additions & 0 deletions tests/unittests/models/test_litellm_stream_thought_signature.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Streaming must keep the thought_signature Gemini attaches to a tool call.

Gemini thinking models attach a thought_signature to each function call. On the
OpenAI-compatible route it rides in extra_content.google.thought_signature (Vertex
also uses provider_specific_fields). If the streaming reassembly drops it, the tool
call ADK stores carries no signature and Gemini rejects the follow-up request:

Function call is missing a thought_signature in functionCall parts.
"""

from litellm.types.utils import ChatCompletionDeltaToolCall
from litellm.types.utils import Delta
from litellm.types.utils import ModelResponseStream
from litellm.types.utils import StreamingChoices

from google.adk.models.lite_llm import _model_response_to_chunk
from google.adk.models.lite_llm import FunctionChunk

_SIGNATURE = "b3BhcXVlLXNpZ25hdHVyZQ=="


def _streamed_tool_call_response(**tool_call_extras):
"""One streamed chunk carrying a complete tool call."""
tool_call = ChatCompletionDeltaToolCall(
index=0,
id="call_1",
type="function",
function={"name": "get_weather", "arguments": '{"city": "Paris"}'},
**tool_call_extras,
)
return ModelResponseStream(
model="test_model",
choices=[
StreamingChoices(
finish_reason=None,
delta=Delta(role="assistant", tool_calls=[tool_call]),
)
],
)


def _function_chunks(response):
return [
chunk
for chunk, _ in _model_response_to_chunk(response)
if isinstance(chunk, FunctionChunk)
]


def test_streaming_keeps_extra_content_thought_signature():
"""The OpenAI-compatible route carries the signature in extra_content.google."""
response = _streamed_tool_call_response(
extra_content={"google": {"thought_signature": _SIGNATURE}}
)

chunks = _function_chunks(response)

assert len(chunks) == 1
assert chunks[0].name == "get_weather"
# The regression: this was discarded while the streamed call was reassembled.
assert chunks[0].extra_content == {"google": {"thought_signature": _SIGNATURE}}


def test_streaming_keeps_provider_specific_fields_signature():
"""The Vertex route carries it in provider_specific_fields instead."""
response = _streamed_tool_call_response(
provider_specific_fields={"thought_signature": _SIGNATURE}
)

chunks = _function_chunks(response)

assert len(chunks) == 1
assert chunks[0].provider_specific_fields == {
"thought_signature": _SIGNATURE
}


def test_streaming_without_signature_still_works():
"""A plain tool call keeps working; the new fields stay None."""
response = _streamed_tool_call_response()

chunks = _function_chunks(response)

assert len(chunks) == 1
assert chunks[0].extra_content is None
assert chunks[0].provider_specific_fields is None
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

from __future__ import annotations

import os
from typing import Any
from typing import Dict
from typing import Optional
Expand All @@ -23,6 +24,7 @@
from google.adk.utils.variant_utils import GoogleLLMVariant
from google.genai import types
import pydantic
from unittest.mock import patch


def test_string_annotation_none_return_vertex():
Expand Down Expand Up @@ -284,3 +286,30 @@ def function_with_optional_list(
assert all(isinstance(item, ItemModel) for item in processed_args['items'])
assert processed_args['items'][0].quantity == 10
assert processed_args['items'][1].quantity == 5

def test_context_param_imported_only_under_type_checking_legacy_path():
"""A context parameter annotated via TYPE_CHECKING must not break the legacy path.

build_function_declaration drops the ignored parameters from the signature. When it
copied every original annotation onto the new function, typing.get_type_hints() then
tried to resolve the removed parameter's annotation too - so a context parameter
typed by a TYPE_CHECKING-only import raised NameError even though it is not part of
the declaration. This is the legacy-path counterpart of the JSON-schema fix.
"""

def test_function(city: str, tool_context: ToolContext) -> str: # noqa: F821
"""A test function whose context parameter is imported only for type checking."""
return f'Sunny in {city}'

# The JSON-schema path is on by default; disable it so this exercises the legacy
# declaration builder, which is where the bug lived.
with patch.dict(os.environ, {'ADK_DISABLE_JSON_SCHEMA_FOR_FUNC_DECL': '1'}):
# signature is (func, ignore_params=None, variant=GEMINI_API)
declaration = _automatic_function_calling_util.build_function_declaration(
test_function,
ignore_params=['tool_context'],
)

assert sorted(declaration.parameters.properties) == ['city']
assert declaration.parameters.properties['city'].type == 'STRING'
assert declaration.parameters.required == ['city']
Loading