diff --git a/pyproject.toml b/pyproject.toml index 88c881d7d..46bd24f2f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -18,7 +18,7 @@ authors = [ dependencies = [ "async-timeout>=5,<6; python_version < '3.11'", # asyncio.timeout backport "pydantic-settings==2.10.1", # Config management - "a2a-sdk>=0.3.7,<1.0.0", # For Google Agent2Agent protocol + "a2a-sdk[http-server]>=1.4.0,<1.5.0", # For Google Agent2Agent protocol "deprecated==1.2.18", "google-adk>=2.7.0,<2.15.0", # For basic agent architecture # litellm and sqlalchemy are required by code paths veadk always uses @@ -55,7 +55,7 @@ dependencies = [ "python-docx>=1.1.0,<2", # Read and write Word documents in document_parse/doc_generate "openpyxl>=3.1.0,<4", # Read and write Excel workbooks in document_parse/doc_generate "vikingdb-python-sdk>=0.1.32", # For Viking DB - "agentkit-sdk-python>=0.8.5", + "agentkit-sdk-python>=0.9.3", "websockets>=15,<16", # Stream temporary AgentKit Sandbox conversations "openviking-sdk>=0.1.9", "python-frontmatter==1.1.0", @@ -136,7 +136,7 @@ harness = [ "headroom", ] harness-sidecar = [ - "agentkit-sdk-python>=0.8.5", + "agentkit-sdk-python>=0.9.3", ] cli = [] sandbox = [ diff --git a/tests/a2a/test_a2a_sdk_14.py b/tests/a2a/test_a2a_sdk_14.py new file mode 100644 index 000000000..2e10440ec --- /dev/null +++ b/tests/a2a/test_a2a_sdk_14.py @@ -0,0 +1,946 @@ +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. +# +# 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. + +"""Unit and contract tests for the a2a-sdk 1.4.0 migration.""" + +from __future__ import annotations + +import asyncio +import inspect +import json +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch + +import httpx +import pytest +from a2a.types import ( + AgentCard, + AgentCapabilities, + AgentInterface, + AgentSkill, + ListTasksRequest, + Message, + Part, + Role, + StreamResponse, + Task, + TaskStatus, + TaskStatusUpdateEvent, + TaskState, +) +from fastapi.testclient import TestClient +from google.adk.agents import BaseAgent +from google.adk.events import Event +from google.genai import types + +from veadk.a2a.agent_card import get_agent_card +from veadk.a2a.hub.a2a_hub_client import A2AHubClient +from veadk.a2a.remote_ve_agent import ( + RemoteVeAgent, + _convert_agent_card_dict_to_obj, + _rewrite_interface_urls, +) +from veadk.a2a.utils.agent_to_a2a import ( + _augment_agent_card, + _load_agent_card, + to_a2a, +) +from veadk.a2a.ve_a2a_server import ( + A2AServerConfig, + VeA2AServer, + _resolve_public_url, + init_app, +) +from veadk.a2a.ve_task_store import VeTaskStore +from veadk.cloud.cloud_app import CloudApp, CloudMessage, CloudPart, get_message_id + + +class EchoAgent(BaseAgent): + async def _run_async_impl(self, context): + yield Event( + author=self.name, + content=types.Content(role="model", parts=[types.Part(text="pong")]), + ) + + +class FakeExecutor: + def __init__(self, **kwargs): + self.kwargs = kwargs + + +class FakeRunner: + def __init__(self, **kwargs): + self.kwargs = kwargs + + +def _agent(name="agent", description="description"): + return SimpleNamespace(name=name, description=description) + + +def _card(url="https://example.com", versions=("0.3", "1.0")): + return AgentCard( + name="card", + description="card", + version="1.0.0", + capabilities=AgentCapabilities(), + default_input_modes=["text"], + default_output_modes=["text"], + skills=[AgentSkill(id="0", name="chat", description="chat", tags=["chat"])], + supported_interfaces=[ + AgentInterface( + url=url, protocol_binding="JSONRPC", protocol_version=version + ) + for version in versions + ], + ) + + +# --------------------------------------------------------------------------- +# agent_card +# --------------------------------------------------------------------------- + + +def test_get_agent_card_is_dual_stack_by_default(): + card = get_agent_card(_agent(), "https://example.com/") + assert [i.protocol_version for i in card.supported_interfaces] == ["0.3", "1.0"] + assert card.supported_interfaces[0].url == "https://example.com" + assert card.skills[0].id == "0" + + +def test_get_agent_card_can_disable_v0_3(): + card = get_agent_card(_agent(), "https://example.com", compat_v0_3=False) + assert [i.protocol_version for i in card.supported_interfaces] == ["1.0"] + + +def test_get_agent_card_warns_on_bind_address(caplog): + with caplog.at_level("WARNING"): + card = get_agent_card(_agent(), "0.0.0.0:8000") + assert card.supported_interfaces[0].url == "0.0.0.0:8000" + assert "bind address" in caplog.text + + +# --------------------------------------------------------------------------- +# ve_a2a_server +# --------------------------------------------------------------------------- + + +def test_resolve_public_url_prefers_server_url(): + assert _resolve_public_url("https://direct.example") == "https://direct.example" + + +def test_resolve_public_url_falls_back_to_veadk_env(monkeypatch): + monkeypatch.setenv("VEADK_A2A_PUBLIC_URL", "https://env.example/") + monkeypatch.delenv("A2A_PUBLIC_URL", raising=False) + assert _resolve_public_url("0.0.0.0") == "https://env.example" + + +def test_resolve_public_url_falls_back_to_legacy_env(monkeypatch): + monkeypatch.delenv("VEADK_A2A_PUBLIC_URL", raising=False) + monkeypatch.setenv("A2A_PUBLIC_URL", "https://legacy.example/") + assert _resolve_public_url("0.0.0.0") == "https://legacy.example" + + +def test_resolve_public_url_warns_when_unavailable(monkeypatch, caplog): + monkeypatch.delenv("VEADK_A2A_PUBLIC_URL", raising=False) + monkeypatch.delenv("A2A_PUBLIC_URL", raising=False) + with caplog.at_level("WARNING"): + assert _resolve_public_url("0.0.0.0") == "0.0.0.0" + assert "empty or 0.0.0.0" in caplog.text + + +def _patch_server_dependencies(monkeypatch): + monkeypatch.setattr("veadk.a2a.ve_a2a_server.A2aAgentExecutor", FakeExecutor) + monkeypatch.setattr("veadk.a2a.ve_a2a_server.Runner", FakeRunner) + + +def test_ve_a2a_server_serves_both_card_paths(monkeypatch): + _patch_server_dependencies(monkeypatch) + server = VeA2AServer( + agent=_agent(), + url="https://example.com", + app_name="app", + short_term_memory=object(), + ) + client = TestClient(server.build()) + assert client.get("/.well-known/agent-card.json").status_code == 200 + assert client.get("/.well-known/agent.json").status_code == 200 + + +def test_ve_a2a_server_can_disable_v0_3(monkeypatch): + _patch_server_dependencies(monkeypatch) + server = VeA2AServer( + agent=_agent(), + url="https://example.com", + app_name="app", + short_term_memory=object(), + config=A2AServerConfig(compat_v0_3=False), + ) + client = TestClient(server.build()) + assert client.get("/.well-known/agent-card.json").status_code == 200 + assert client.get("/.well-known/agent.json").status_code == 404 + + +def test_ve_a2a_server_can_enable_openapi(monkeypatch): + _patch_server_dependencies(monkeypatch) + server = VeA2AServer( + agent=_agent(), + url="https://example.com", + app_name="app", + short_term_memory=object(), + config=A2AServerConfig(docs_enabled=True), + ) + client = TestClient(server.build()) + response = client.get("/openapi.json") + assert response.status_code == 200 + assert "/.well-known/agent-card.json" in response.json()["paths"] + + +def test_init_app_uses_env_public_url(monkeypatch): + captured = {} + + class FakeServer: + def __init__(self, **kwargs): + captured.update(kwargs) + + def build(self): + return "app" + + monkeypatch.setattr("veadk.a2a.ve_a2a_server.VeA2AServer", FakeServer) + monkeypatch.setenv("VEADK_A2A_PUBLIC_URL", "https://env.example") + app = init_app("0.0.0.0", "app", _agent(), object()) + assert app == "app" + assert captured["url"] == "https://env.example" + + +# --------------------------------------------------------------------------- +# ve_task_store +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_ve_task_store_implements_all_abstract_methods(): + store = VeTaskStore() + assert await store.save(object(), None) is None + assert await store.get("missing", None) is None + assert await store.list(ListTasksRequest(), None) is not None + assert await store.delete("missing", None) is None + + +@pytest.mark.asyncio +async def test_ve_task_store_allows_omitted_context(): + store = VeTaskStore() + assert await store.save(object()) is None + assert await store.get("missing") is None + assert await store.delete("missing") is None + assert await store.list(ListTasksRequest()) is not None + + +# --------------------------------------------------------------------------- +# agent_to_a2a +# --------------------------------------------------------------------------- + + +def test_augment_agent_card_adds_v0_3_to_v1_only_card(): + card = _card(versions=("1.0",)) + augmented = _augment_agent_card(card, "https://fallback.example") + assert [i.protocol_version for i in augmented.supported_interfaces] == [ + "0.3", + "1.0", + ] + assert augmented.supported_interfaces[0].url == "https://example.com" + # The caller's card is not mutated. + assert [i.protocol_version for i in card.supported_interfaces] == ["1.0"] + + +def test_augment_agent_card_adds_v1_to_v0_3_only_card(): + card = _card(versions=("0.3",)) + augmented = _augment_agent_card(card, "https://fallback.example") + assert [i.protocol_version for i in augmented.supported_interfaces] == [ + "0.3", + "1.0", + ] + + +def test_augment_agent_card_keeps_existing_both(): + card = _card(versions=("0.3", "1.0")) + augmented = _augment_agent_card(card, "https://fallback.example") + assert [i.protocol_version for i in augmented.supported_interfaces] == [ + "0.3", + "1.0", + ] + + +def test_load_agent_card_from_path(tmp_path): + path = tmp_path / "card.json" + path.write_text( + json.dumps( + { + "name": "legacy", + "description": "legacy", + "version": "1", + "url": "https://legacy.example", + "preferredTransport": "JSONRPC", + "protocolVersion": "0.3", + "capabilities": {}, + "skills": [], + } + ) + ) + card = _load_agent_card(str(path)) + assert card.supported_interfaces[0].protocol_version == "0.3" + + +def test_load_agent_card_passes_through_object(): + card = _card() + assert _load_agent_card(card) is card + + +def test_to_a2a_serves_dual_stack_card(): + app = to_a2a(EchoAgent(name="echo"), host="127.0.0.1", port=8000) + with TestClient(app) as client: + card = client.get("/.well-known/agent-card.json") + assert card.status_code == 200 + body = card.json() + assert {i["protocolVersion"] for i in body["supportedInterfaces"]} == { + "0.3", + "1.0", + } + assert body["url"] == "http://127.0.0.1:8000" + assert client.get("/.well-known/agent.json").status_code == 200 + + +def test_to_a2a_accepts_custom_v0_3_card(tmp_path): + path = tmp_path / "card.json" + path.write_text( + json.dumps( + { + "name": "custom", + "description": "custom", + "version": "1.2.3", + "url": "https://custom.example/a2a", + "preferredTransport": "JSONRPC", + "protocolVersion": "0.3", + "capabilities": {}, + "skills": [], + } + ) + ) + app = to_a2a( + EchoAgent(name="echo"), host="127.0.0.1", port=8000, agent_card=str(path) + ) + with TestClient(app) as client: + body = client.get("/.well-known/agent-card.json").json() + assert body["version"] == "1.2.3" + assert {i["protocolVersion"] for i in body["supportedInterfaces"]} == { + "0.3", + "1.0", + } + + +# --------------------------------------------------------------------------- +# CloudMessage / CloudApp +# --------------------------------------------------------------------------- + + +def _message(text="pong", role=Role.ROLE_AGENT): + return Message(message_id="m-1", role=role, parts=[Part(text=text)]) + + +def test_cloud_message_supports_root_and_flat_access(): + message = CloudMessage.from_message(_message("pong")) + assert message.parts[0].root.text == "pong" + assert message.parts[0].text == "pong" + assert message.messageId == "m-1" + assert message.message_id == "m-1" + assert str(message) == "pong" + + +def test_cloud_message_role_is_user(): + message = CloudMessage.from_message(_message("hi", Role.ROLE_USER)) + assert message.role == "user" + + +@pytest.mark.asyncio +async def test_cloud_message_from_stream_returns_message(): + async def stream(): + yield StreamResponse(message=_message("pong")) + + result = await CloudMessage.from_stream(stream()) + assert result is not None + assert result.text == "pong" + + +@pytest.mark.asyncio +async def test_cloud_message_from_stream_extracts_task_history(): + task = Task( + id="t-1", + context_id="c-1", + status={"state": TaskState.TASK_STATE_COMPLETED}, + history=[_message("user", Role.ROLE_USER), _message("agent")], + ) + + async def stream(): + yield StreamResponse(task=task) + + result = await CloudMessage.from_stream(stream()) + assert result is not None + assert result.text == "agent" + + +@pytest.mark.asyncio +async def test_cloud_message_from_stream_returns_none_without_agent_history(): + task = Task( + id="t-1", + context_id="c-1", + status={"state": TaskState.TASK_STATE_COMPLETED}, + history=[_message("user", Role.ROLE_USER)], + ) + + async def stream(): + yield StreamResponse(task=task) + + assert await CloudMessage.from_stream(stream()) is None + + +@pytest.mark.asyncio +async def test_cloud_message_from_stream_returns_none_on_empty_stream(): + async def stream(): + return + yield # pragma: no cover + + assert await CloudMessage.from_stream(stream()) is None + + +def test_get_message_id_supports_both_api_shapes(): + assert get_message_id(CloudMessage(message_id="abc")) == "abc" + assert get_message_id(Message(message_id="def")) == "def" + + +@pytest.mark.asyncio +async def test_cloud_app_default_mode_does_not_fetch_card(monkeypatch): + captured = {} + + class FakeFactory: + def __init__(self, config): + self.config = config + + def create(self, card): + captured["card"] = card + return "client" + + resolver = MagicMock() + resolver.get_agent_card = AsyncMock(side_effect=AssertionError("should not fetch")) + monkeypatch.setattr("veadk.cloud.cloud_app.ClientFactory", FakeFactory) + monkeypatch.setattr("veadk.cloud.cloud_app.A2ACardResolver", lambda **kw: resolver) + + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1") + client = await app._get_a2a_client() + await app.aclose() + + assert client == "client" + assert [i.protocol_version for i in captured["card"].supported_interfaces] == [ + "0.3" + ] + + +@pytest.mark.asyncio +async def test_cloud_app_card_mode_fetches_card(monkeypatch): + card = _card() + captured = {} + + class FakeFactory: + def __init__(self, config): + self.config = config + + def create(self, resolved_card): + captured["card"] = resolved_card + return "client" + + resolver = MagicMock() + resolver.get_agent_card = AsyncMock(return_value=card) + monkeypatch.setattr("veadk.cloud.cloud_app.ClientFactory", FakeFactory) + monkeypatch.setattr("veadk.cloud.cloud_app.A2ACardResolver", lambda **kw: resolver) + + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1", use_agent_card=True) + client = await app._get_a2a_client() + await app.aclose() + + assert client == "client" + assert captured["card"] is card + resolver.get_agent_card.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_cloud_app_message_send_returns_cloud_message(monkeypatch): + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1") + + async def stream(*args, **kwargs): + yield StreamResponse(message=_message("pong")) + + client = MagicMock() + client.send_message = stream + monkeypatch.setattr(app, "_get_a2a_client", AsyncMock(return_value=client)) + + result = await app.message_send("ping", "s", "u") + await app.aclose() + + assert result is not None + assert result.parts[0].root.text == "pong" + + +@pytest.mark.asyncio +async def test_cloud_app_message_send_passes_timeout(monkeypatch): + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1") + captured = {} + + async def stream(*args, **kwargs): + captured["context"] = kwargs.get("context") + yield StreamResponse(message=_message("pong")) + + client = MagicMock() + client.send_message = stream + monkeypatch.setattr(app, "_get_a2a_client", AsyncMock(return_value=client)) + + await app.message_send("ping", "s", "u", timeout=12.5) + await app.aclose() + + assert captured["context"].timeout == 12.5 + + +@pytest.mark.asyncio +async def test_cloud_app_message_send_returns_none_on_error(monkeypatch): + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1") + monkeypatch.setattr( + app, "_get_a2a_client", AsyncMock(side_effect=RuntimeError("boom")) + ) + assert await app.message_send("ping", "s", "u") is None + await app.aclose() + + +@pytest.mark.asyncio +async def test_cloud_app_context_manager_closes_client(): + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1") + async with app as entered: + assert entered is app + assert app.httpx_client.is_closed + + +# --------------------------------------------------------------------------- +# RemoteVeAgent +# --------------------------------------------------------------------------- + + +def test_convert_agent_card_dict_parses_v0_3_card(): + card = _convert_agent_card_dict_to_obj( + { + "name": "legacy", + "description": "legacy", + "version": "1", + "url": "https://legacy.example", + "preferredTransport": "JSONRPC", + "protocolVersion": "0.3", + "capabilities": {}, + "skills": [], + } + ) + assert card.supported_interfaces[0].protocol_version == "0.3" + + +def test_rewrite_interface_urls_preserves_caller_query(): + card = _card(url="http://card.example/a2a") + rewritten = _rewrite_interface_urls(card, "https://caller.example/base?token=1") + assert rewritten.supported_interfaces[0].url == ( + "https://caller.example/a2a?token=1" + ) + + +def test_rewrite_interface_urls_leaves_non_http_interfaces(): + card = AgentCard( + name="x", + description="x", + version="1", + skills=[], + supported_interfaces=[ + AgentInterface(url="grpc://card.example:443", protocol_binding="GRPC") + ], + ) + rewritten = _rewrite_interface_urls(card, "https://caller.example") + assert rewritten.supported_interfaces[0].url == "grpc://card.example:443" + + +# --------------------------------------------------------------------------- +# A2AHubClient +# --------------------------------------------------------------------------- + + +def test_a2a_hub_client_registers_card_as_camel_case_dict(): + with ( + patch( + "veadk.a2a.hub.a2a_hub_client.requests.get", + return_value=MagicMock(status_code=200), + ), + patch( + "veadk.a2a.hub.a2a_hub_client.requests.post", + return_value=MagicMock(status_code=200), + ) as post, + ): + client = A2AHubClient("hub.example", 8000) + client.register_agent("group", "agent", _card()) + payload = post.call_args.kwargs["json"]["agent_card"] + assert payload["supportedInterfaces"][0]["protocolVersion"] == "0.3" + assert payload["url"] == "https://example.com" + + +# --------------------------------------------------------------------------- +# auth_processor changed lines +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_auth_processor_updates_task_with_working_state(): + from veadk.integrations.ve_identity.auth_processor import AuthRequestProcessor + from veadk.integrations.ve_identity.models import AuthRequestConfig + + oauth2 = SimpleNamespace( + auth_uri="https://auth.example", + __pydantic_fields__={"access_token": None}, + __dict__={"access_token": None}, + ) + auth_config = SimpleNamespace( + exchanged_auth_credential=SimpleNamespace(oauth2=oauth2, resource_ref=None), + model_dump=MagicMock(return_value={"exchanged_auth_credential": {}}), + ) + poller = SimpleNamespace( + poll_for_auth=AsyncMock(return_value=SimpleNamespace(access_token="token")) + ) + config = AuthRequestConfig( + oauth2_auth_poller=lambda uri, request_dict: poller, + identity_client=MagicMock(), + ) + processor = AuthRequestProcessor(config=config) + task_updater = AsyncMock() + + result = await processor.process_auth_request("event-1", auth_config, task_updater) + + assert result is not None + task_updater.update_status.assert_awaited_once() + state = task_updater.update_status.await_args.args[0] + message = task_updater.update_status.await_args.kwargs["message"] + assert state == TaskState.TASK_STATE_WORKING + assert message.parts[0].text == "Authorization received, continuing..." + + +# --------------------------------------------------------------------------- +# extra branch coverage for changed lines +# --------------------------------------------------------------------------- + + +def test_get_agent_card_accepts_empty_url(): + card = get_agent_card(_agent(), "") + assert [interface.url for interface in card.supported_interfaces] == ["", ""] + + +def test_runner_run_async_signature_is_introspectable(): + """ADK 2.14.x's A2A executor calls inspect.signature on the bound method.""" + from veadk import Runner + + runner = Runner(agent=EchoAgent(name="echo"), app_name="app", user_id="u") + params = inspect.signature(runner.run_async).parameters + assert any( + parameter.kind == inspect.Parameter.VAR_KEYWORD for parameter in params.values() + ) + + +@pytest.mark.asyncio +async def test_runner_run_async_interceptor_executes(): + from google.adk.sessions import InMemorySessionService + from google.genai import types + + from veadk import Runner + + sessions = InMemorySessionService() + await sessions.create_session(app_name="app", user_id="u", session_id="s") + runner = Runner( + agent=EchoAgent(name="echo"), + app_name="app", + session_service=sessions, + user_id="u", + ) + events = [ + event + async for event in runner.run_async( + user_id="u", + session_id="s", + new_message=types.Content(role="user", parts=[types.Part(text="ping")]), + ) + ] + assert events[-1].content.parts[0].text == "pong" + + +def test_cloud_part_str_returns_text(): + assert str(CloudPart(text="hello")) == "hello" + + +@pytest.mark.asyncio +async def test_cloud_app_close_alias_closes_client(): + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1") + await app.close() + assert app.httpx_client.is_closed + + +def test_rewrite_interface_urls_skips_empty_interface_url(): + card = _card() + card.supported_interfaces[0].url = "" + rewritten = _rewrite_interface_urls(card, "https://caller.example/base?token=1") + assert rewritten.supported_interfaces[0].url == "" + + +def test_remote_ve_agent_rewrites_fetched_card_interfaces(monkeypatch): + payload = { + "name": "remote", + "description": "d", + "version": "1", + "supportedInterfaces": [ + {"url": "", "protocolBinding": "JSONRPC", "protocolVersion": "0.3"}, + { + "url": "http://card.example/a2a", + "protocolBinding": "JSONRPC", + "protocolVersion": "1.0", + }, + ], + "capabilities": {"streaming": False}, + "defaultInputModes": ["text"], + "defaultOutputModes": ["text"], + "skills": [], + } + monkeypatch.setattr( + "veadk.a2a.remote_ve_agent.requests.get", + lambda *args, **kwargs: MagicMock(json=lambda: payload), + ) + agent = RemoteVeAgent(name="remote", url="https://caller.example/base?token=1") + try: + interfaces = agent._agent_card.supported_interfaces + assert interfaces[0].url == "" + assert interfaces[1].url == "https://caller.example/a2a?token=1" + finally: + asyncio.run(agent._httpx_client.aclose()) + + +@pytest.mark.asyncio +async def test_ve_agent_executor_enqueues_final_output(monkeypatch): + from veadk.a2a.ve_agent_executor import VeAgentExecutor + + monkeypatch.setattr("veadk.a2a.ve_agent_executor.Runner", FakeRunner) + executor = VeAgentExecutor( + app_name="app", agent=_agent(), short_term_memory=object() + ) + executor.runner = SimpleNamespace(user_id="", run=AsyncMock(return_value="final")) + context = SimpleNamespace( + metadata={"user_id": "u", "session_id": "s"}, get_user_input=lambda: "hi" + ) + queue = SimpleNamespace(enqueue_event=AsyncMock()) + + await executor.execute(context, queue) + + message = queue.enqueue_event.await_args.args[0] + assert message.parts[0].text == "final" + assert await executor.cancel(context, queue) is None + + +def _skill_card_payload(): + return { + "name": "skill", + "description": "d", + "version": "1", + "supportedInterfaces": [ + {"url": "", "protocolBinding": "JSONRPC", "protocolVersion": "0.3"}, + { + "url": "http://127.0.0.1:1/a2a", + "protocolBinding": "JSONRPC", + "protocolVersion": "1.0", + }, + ], + "capabilities": {"streaming": False}, + "defaultInputModes": ["text"], + "defaultOutputModes": ["text"], + "skills": [], + } + + +def _patch_skill_transport(monkeypatch, client): + from veadk.agents._remote_sandbox import skill as skill_module + + class FakeHttp: + async def __aenter__(self): + return self + + async def __aexit__(self, *args): + return None + + async def get(self, url): + return SimpleNamespace(status_code=200, json=lambda: _skill_card_payload()) + + class FakeFactory: + def __init__(self, config): + self.config = config + + def create(self, card): + return client + + monkeypatch.setattr( + skill_module, + "httpx", + SimpleNamespace( + AsyncClient=lambda **kwargs: FakeHttp(), + Timeout=httpx.Timeout, + URL=httpx.URL, + TransportError=httpx.TransportError, + ), + ) + monkeypatch.setattr(skill_module, "ClientFactory", FakeFactory) + return skill_module + + +def _skill_arguments(): + agent = SimpleNamespace( + name="sandbox", ready_timeout=5, request_timeout=5, expiry_buffer=0 + ) + ctx = SimpleNamespace( + user_id="u", + session=SimpleNamespace(id="s"), + invocation_id="inv", + branch=None, + ) + return dict( + agent=agent, + ctx=ctx, + endpoint="http://127.0.0.1:1/?route=fixture", + headers={}, + binding=None, + turn_key="turn-1", + task="ping", + context={}, + lease=None, + ) + + +@pytest.mark.asyncio +async def test_skill_events_consumes_status_message_and_empty_chunks(monkeypatch): + from veadk.agents.agentkit_remote_sandbox_agent import SandboxAgentError # noqa: F401 + + chunks = [ + StreamResponse( + status_update=TaskStatusUpdateEvent( + task_id="t-1", + context_id="ctx-1", + status=TaskStatus( + state=TaskState.TASK_STATE_COMPLETED, + message=_message("done"), + ), + ) + ), + StreamResponse( + message=Message( + message_id="m-1", + role=Role.ROLE_AGENT, + parts=[Part(text="hello")], + context_id="ctx-1", + ) + ), + StreamResponse(), + ] + + class FakeClient: + def __init__(self): + self.closed = False + + async def send_message(self, request): + for chunk in chunks: + yield chunk + + async def close(self): + self.closed = True + + async def cancel_task(self, request): + return None + + client = FakeClient() + skill_module = _patch_skill_transport(monkeypatch, client) + + events = [event async for event in skill_module.skill_events(**_skill_arguments())] + + texts = [part.text for event in events for part in event.content.parts if part.text] + assert "done" in texts + assert "hello" in texts + assert client.closed + + +@pytest.mark.asyncio +async def test_skill_events_transport_error_before_task_raises(monkeypatch): + from veadk.agents.agentkit_remote_sandbox_agent import SandboxAgentError + + class FakeClient: + def __init__(self): + self.closed = False + + async def send_message(self, request): + raise httpx.ConnectError("boom") + yield # unreachable: keeps this an async generator + + async def close(self): + self.closed = True + + async def cancel_task(self, request): + return None + + client = FakeClient() + skill_module = _patch_skill_transport(monkeypatch, client) + + with pytest.raises(SandboxAgentError): + async for _ in skill_module.skill_events(**_skill_arguments()): + pass + + assert client.closed + + +@pytest.mark.asyncio +async def test_skill_events_accepts_message_only_response(monkeypatch): + class FakeClient: + def __init__(self): + self.closed = False + + async def send_message(self, request): + yield StreamResponse( + message=Message( + message_id="m-only", + role=Role.ROLE_AGENT, + parts=[Part(text="direct-answer")], + context_id="ctx-only", + ) + ) + + async def close(self): + self.closed = True + + async def cancel_task(self, request): + return None + + client = FakeClient() + skill_module = _patch_skill_transport(monkeypatch, client) + + events = [event async for event in skill_module.skill_events(**_skill_arguments())] + + texts = [part.text for event in events for part in event.content.parts if part.text] + assert "direct-answer" in texts + assert client.closed diff --git a/tests/agents/test_remote_sandbox_agent.py b/tests/agents/test_remote_sandbox_agent.py index 1e3550f8a..09db41339 100644 --- a/tests/agents/test_remote_sandbox_agent.py +++ b/tests/agents/test_remote_sandbox_agent.py @@ -309,13 +309,14 @@ async def test_discovery_cache_is_user_scoped(): @pytest.mark.parametrize("streaming", [True, False]) async def test_skill_a2a_preserves_tool_parts_and_context(streaming): from google.adk.a2a.converters.part_converter import convert_genai_part_to_a2a_part + from a2a.compat.v0_3.conversions import to_compat_part release = asyncio.Event() contexts = [] methods = [] def wire(part): - return convert_genai_part_to_a2a_part(part).model_dump( + return to_compat_part(convert_genai_part_to_a2a_part(part)).model_dump( mode="json", by_alias=True, exclude_none=True ) @@ -549,17 +550,23 @@ async def generate_content_async(self, llm_request, stream=False): with socket.socket() as sock: sock.bind(("127.0.0.1", 0)) port = sock.getsockname()[1] - from a2a.types import AgentCard, AgentCapabilities + from a2a.types import AgentCard, AgentCapabilities, AgentInterface card = AgentCard( name="native_skill", description="fixture", version="1", - url=f"http://127.0.0.1:{port}/", capabilities=AgentCapabilities(streaming=streaming), default_input_modes=["text/plain"], default_output_modes=["text/plain"], skills=[], + supported_interfaces=[ + AgentInterface( + url=f"http://127.0.0.1:{port}/", + protocol_binding="JSONRPC", + protocol_version="1.0", + ) + ], ) application = to_a2a(remote, host="127.0.0.1", port=port, agent_card=card) server = uvicorn.Server( diff --git a/tests/cli/test_studio_tos_sdk_dependency.py b/tests/cli/test_studio_tos_sdk_dependency.py index b5af55f72..adb3a4be5 100644 --- a/tests/cli/test_studio_tos_sdk_dependency.py +++ b/tests/cli/test_studio_tos_sdk_dependency.py @@ -32,5 +32,7 @@ def test_studio_requires_agentkit_sdk_with_tos_credential_type() -> None: if Requirement(value).name == "agentkit-sdk-python" ) - assert requirement.specifier.contains("0.8.5") + # TOS credential type landed in agentkit-sdk-python 0.8.5; the declared floor + # must stay at or above it while still admitting the currently required line. + assert requirement.specifier.contains("0.9.3") assert not requirement.specifier.contains("0.8.4") diff --git a/tests/extensions/harness/test_sidecar_wheel.py b/tests/extensions/harness/test_sidecar_wheel.py index 915c3ead4..292b40ac4 100644 --- a/tests/extensions/harness/test_sidecar_wheel.py +++ b/tests/extensions/harness/test_sidecar_wheel.py @@ -110,7 +110,7 @@ def test_wheel_metadata_keeps_sidecar_optional_and_sdk_constraints_aligned( if canonicalize_name(item.name) == "agentkit-sdk-python" ] assert any( - item.marker is None and ">=0.8.5" in str(item.specifier) + item.marker is None and ">=0.9.3" in str(item.specifier) for item in sdk_requirements ) sidecar_extra = [ @@ -119,7 +119,7 @@ def test_wheel_metadata_keeps_sidecar_optional_and_sdk_constraints_aligned( if item.marker is not None and "harness-sidecar" in str(item.marker) ] assert len(sidecar_extra) == 1 - assert ">=0.8.5" in str(sidecar_extra[0].specifier) + assert ">=0.9.3" in str(sidecar_extra[0].specifier) forbidden = { "agentkit-harness-sidecar-integration", diff --git a/tests/test_cloud.py b/tests/test_cloud.py index bb45f3ea0..d7346a6a9 100644 --- a/tests/test_cloud.py +++ b/tests/test_cloud.py @@ -74,6 +74,81 @@ def test_vefaas_create_function_uses_configured_project() -> None: assert request.memory_mb == 2048 +def test_vefaas_merge_function_envs_preserves_existing_and_releases() -> None: + service = VeFaaS(access_key="ak", secret_key="sk") + service.client = Mock() + service.client.get_function.return_value = SimpleNamespace( + envs=[ + SimpleNamespace(key="_FAAS_FUNC_ID", value="fn-1"), + SimpleNamespace(key="APP_REGION", value="cn-beijing"), + ] + ) + service.client.get_release_status.return_value = SimpleNamespace(status="Success") + + with patch("time.sleep") as sleep: + service.merge_function_envs_and_release( + "fn-1", {"VEADK_A2A_PUBLIC_URL": "https://example.com"} + ) + + request = service.client.update_function.call_args.args[0] + envs = {item.key: item.value for item in request.envs} + assert envs["_FAAS_FUNC_ID"] == "fn-1" + assert envs["APP_REGION"] == "cn-beijing" + assert envs["VEADK_A2A_PUBLIC_URL"] == "https://example.com" + service.client.release.assert_called_once() + sleep.assert_not_called() + + +def test_vefaas_merge_function_envs_skips_when_already_present() -> None: + service = VeFaaS(access_key="ak", secret_key="sk") + service.client = Mock() + service.client.get_function.return_value = SimpleNamespace( + envs=[ + SimpleNamespace(key="VEADK_A2A_PUBLIC_URL", value="https://example.com"), + SimpleNamespace(key="APP_REGION", value="cn-beijing"), + ] + ) + + service.merge_function_envs_and_release( + "fn-1", {"VEADK_A2A_PUBLIC_URL": "https://example.com"} + ) + + service.client.update_function.assert_not_called() + service.client.release.assert_not_called() + + +def test_vefaas_merge_function_envs_raises_on_failed_release() -> None: + service = VeFaaS(access_key="ak", secret_key="sk") + service.client = Mock() + service.client.get_function.return_value = SimpleNamespace(envs=[]) + service.client.get_release_status.return_value = SimpleNamespace(status="Failed") + + with pytest.raises(RuntimeError, match="re-release failed"): + service.merge_function_envs_and_release( + "fn-1", {"VEADK_A2A_PUBLIC_URL": "https://example.com"} + ) + + +def test_vefaas_merge_function_envs_warns_on_timeout(caplog) -> None: + service = VeFaaS(access_key="ak", secret_key="sk") + service.client = Mock() + service.client.get_function.return_value = SimpleNamespace(envs=[]) + service.client.get_release_status.side_effect = lambda *args, **kwargs: ( + SimpleNamespace(status="Deploying") + ) + + with ( + patch("time.sleep") as sleep, + caplog.at_level("WARNING"), + ): + service.merge_function_envs_and_release( + "fn-1", {"VEADK_A2A_PUBLIC_URL": "https://example.com"} + ) + + assert "did not settle within timeout" in caplog.text + assert sleep.call_count == 60 + + @pytest.mark.parametrize("provider", ["volcengine", "byteplus"]) @pytest.mark.parametrize("existing", [False, True]) @pytest.mark.parametrize("studio_resources", [False, True]) @@ -109,6 +184,7 @@ def test_cloud_deploy_function_resources( ) ) service._upload_and_mount_code = Mock() + service.merge_function_envs_and_release = Mock() service._create_application = Mock(return_value="application-id") service._release_application = Mock(return_value="https://studio.example") service.ensure_application_route_methods = Mock() @@ -218,6 +294,7 @@ def test_vefaas_update_code_uses_resource_updating_bundle_path( ) -> None: project = tmp_path / "agent" project.mkdir() + (project / "requirements.txt").write_text("requests\n") service = object.__new__(VeFaaS) service.find_app_id_by_name = Mock(return_value="application-id") service._get_application_status = Mock( @@ -233,14 +310,26 @@ def test_vefaas_update_code_uses_resource_updating_bundle_path( }, ) ) - service._replace_application_code_bundle = Mock() + captured: dict[str, object] = {} + + def _capture(**kwargs: object) -> None: + uploaded = Path(str(kwargs["path"])) + captured["files"] = { + path.relative_to(uploaded).as_posix(): path.read_text() + for path in uploaded.rglob("*") + if path.is_file() + } + + service._replace_application_code_bundle = Mock(side_effect=_capture) service._release_application = Mock(return_value="https://studio.example") + service.merge_function_envs_and_release = Mock() service._set_function_min_instance = Mock() service.ensure_application_route_methods = Mock() def _cookiecutter(*, output_dir: str, extra_context: dict, **_: object) -> None: package = Path(output_dir) / str(extra_context["local_dir_name"]) - (package / "src").mkdir(parents=True) + (package / "src" / "agent").mkdir(parents=True) + (package / "src" / "agent" / "old.py").write_text("old = True\n") monkeypatch.setattr( "veadk.integrations.ve_faas.ve_faas.formatted_timestamp", lambda: "stamp" @@ -262,9 +351,125 @@ def _cookiecutter(*, output_dir: str, extra_context: dict, **_: object) -> None: environment_overrides=None, request_timeout=1800, ) + files = captured["files"] + assert files["requirements.txt"] == "requests\n" + assert files["agent/requirements.txt"] == "requests\n" + assert "agent/old.py" not in files service._set_function_min_instance.assert_called_once_with("function-id") +def test_vefaas_update_code_uses_rendered_src_in_place( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + src = tmp_path / "src" + (src / "a2a14_smoke").mkdir(parents=True) + (src / "app.py").write_text("app = None\n") + (src / "requirements.txt").write_text("./a2a14_smoke/x.whl\n") + (src / "a2a14_smoke" / "x.whl").write_text("wheel") + + service = object.__new__(VeFaaS) + service.find_app_id_by_name = Mock(return_value="application-id") + service._get_application_status = Mock( + return_value=( + "deploy_success", + { + "Result": { + "CloudResource": '{"framework":{"function":' + '{"Id":"function-id","Name":"studio-app-fn"}}}' + } + }, + ) + ) + captured: dict[str, object] = {} + + def _capture(**kwargs: object) -> None: + uploaded = Path(str(kwargs["path"])) + captured["files"] = { + path.relative_to(uploaded).as_posix(): path.read_text() + for path in uploaded.rglob("*") + if path.is_file() + } + + service._replace_application_code_bundle = Mock(side_effect=_capture) + service._release_application = Mock(return_value="https://studio.example") + service.merge_function_envs_and_release = Mock() + service._set_function_min_instance = Mock() + service.ensure_application_route_methods = Mock() + + def _cookiecutter(*, output_dir: str, extra_context: dict, **_: object) -> None: + package = Path(output_dir) / str(extra_context["local_dir_name"]) + (package / "src").mkdir(parents=True) + + monkeypatch.setattr( + "veadk.integrations.ve_faas.ve_faas.formatted_timestamp", lambda: "stamp" + ) + monkeypatch.setattr( + "veadk.integrations.ve_faas.ve_faas.tempfile.gettempdir", + lambda: str(tmp_path), + ) + monkeypatch.setattr( + "veadk.integrations.ve_faas.ve_faas.cookiecutter", _cookiecutter + ) + + result = service._update_function_code("studio-app", str(src)) + + assert result == ("https://studio.example", "application-id", "function-id") + files = captured["files"] + assert files["app.py"] == "app = None\n" + assert files["requirements.txt"] == "./a2a14_smoke/x.whl\n" + assert files["a2a14_smoke/x.whl"] == "wheel" + + +def test_vefaas_update_code_warns_without_requirements( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + caplog, +) -> None: + project = tmp_path / "agent" + project.mkdir() + (project / "agent.py").write_text("agent = None\n") + + service = object.__new__(VeFaaS) + service.find_app_id_by_name = Mock(return_value="application-id") + service._get_application_status = Mock( + return_value=( + "deploy_success", + { + "Result": { + "CloudResource": '{"framework":{"function":' + '{"Id":"function-id","Name":"studio-app-fn"}}}' + } + }, + ) + ) + service._replace_application_code_bundle = Mock() + service._release_application = Mock(return_value="https://studio.example") + service.merge_function_envs_and_release = Mock() + service._set_function_min_instance = Mock() + service.ensure_application_route_methods = Mock() + + def _cookiecutter(*, output_dir: str, extra_context: dict, **_: object) -> None: + package = Path(output_dir) / str(extra_context["local_dir_name"]) + (package / "src").mkdir(parents=True) + + monkeypatch.setattr( + "veadk.integrations.ve_faas.ve_faas.formatted_timestamp", lambda: "stamp" + ) + monkeypatch.setattr( + "veadk.integrations.ve_faas.ve_faas.tempfile.gettempdir", + lambda: str(tmp_path), + ) + monkeypatch.setattr( + "veadk.integrations.ve_faas.ve_faas.cookiecutter", _cookiecutter + ) + + with caplog.at_level("WARNING"): + service._update_function_code("studio-app", str(project)) + + assert "No requirements.txt found" in caplog.text + + def test_vefaas_deploy_updates_existing_application_in_place() -> None: service = object.__new__(VeFaaS) service.find_app_id_by_name = Mock(return_value="application-id") @@ -282,6 +487,7 @@ def test_vefaas_deploy_updates_existing_application_in_place() -> None: service.update_application_code_bundle = Mock( return_value="https://studio.example.com" ) + service.merge_function_envs_and_release = Mock() service._create_function = Mock() service._create_application = Mock() @@ -454,6 +660,7 @@ def test_vefaas_deploy_can_disable_gateway_cors() -> None: service._create_function = Mock(return_value=("studio-app-fn", "function-id")) service._create_application = Mock(return_value="application-id") service._release_application = Mock(return_value="https://studio.example.com") + service.merge_function_envs_and_release = Mock() service._set_function_min_instance = Mock() service.ensure_application_route_methods = Mock() @@ -1027,13 +1234,21 @@ async def test_cloud(): mock_vefaas_service.delete.assert_called_with("app-123") # Test CloudApp message_send functionality - mock_response = Mock() - mock_message = Mock() - mock_response.root.result = mock_message + from a2a.types import Message, Part, Role, StreamResponse + + mock_message = Message( + message_id="m-1", + role=Role.ROLE_AGENT, + parts=[Part(text="pong-from-mock")], + ) + mock_stream_response = StreamResponse(message=mock_message) + + async def _stream(*args, **kwargs): + yield mock_stream_response with patch.object(cloud_app, "_get_a2a_client") as mock_get_client: mock_client = AsyncMock() - mock_client.send_message = AsyncMock(return_value=mock_response) + mock_client.send_message = _stream mock_get_client.return_value = mock_client # Test message sending to cloud agent @@ -1044,8 +1259,9 @@ async def test_cloud(): ) # Verify message sending result - assert result == mock_message - mock_client.send_message.assert_called_once() + assert result is not None + assert result.parts[0].root.text == "pong-from-mock" + assert result.parts[0].text == "pong-from-mock" # Test CloudApp delete_self functionality with patch("builtins.input", return_value="y"): diff --git a/tests/test_runtime_dependency_compatibility.py b/tests/test_runtime_dependency_compatibility.py index d54c3bd16..c43dd63f8 100644 --- a/tests/test_runtime_dependency_compatibility.py +++ b/tests/test_runtime_dependency_compatibility.py @@ -24,7 +24,7 @@ ROOT = Path(__file__).resolve().parents[1] GOOGLE_ADK_BASELINE = "google-adk>=2.7.0,<2.15.0" GOOGLE_ADK_EVAL_BASELINE = "google-adk[eval]>=2.7.0,<2.15.0" -AGENTKIT_BASELINE = "agentkit-sdk-python>=0.8.5" +AGENTKIT_BASELINE = "agentkit-sdk-python>=0.9.3" OPENTELEMETRY_EXPORTER_BASELINE = "opentelemetry-exporter-otlp>=1.37.0,<1.43" OPENTELEMETRY_EXPORTER_LOCK_BASELINE = ( '{ name = "opentelemetry-exporter-otlp", specifier = ">=1.37.0,<1.43" }' @@ -50,10 +50,10 @@ def test_project_dependency_metadata_uses_runtime_compatibility_baseline() -> No def test_lock_metadata_matches_project_dependency_baseline() -> None: lock = (ROOT / "uv.lock").read_text(encoding="utf-8") - assert '{ name = "agentkit-sdk-python", specifier = ">=0.8.5" }' in lock + assert '{ name = "agentkit-sdk-python", specifier = ">=0.9.3" }' in lock assert ( '{ name = "agentkit-sdk-python", marker = "extra == ' - '\'harness-sidecar\'", specifier = ">=0.8.5" }' + '\'harness-sidecar\'", specifier = ">=0.9.3" }' ) in lock assert '{ name = "google-adk", specifier = ">=2.7.0,<2.15.0" }' in lock assert ( diff --git a/uv.lock b/uv.lock index 3a878b27b..710353c99 100644 --- a/uv.lock +++ b/uv.lock @@ -16,18 +16,27 @@ resolution-markers = [ [[package]] name = "a2a-sdk" -version = "0.3.26" +version = "1.4.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 = "httpx-sse" }, + { name = "json-rpc" }, + { name = "packaging" }, { name = "protobuf" }, { name = "pydantic" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/be/97/a6840e01795b182ce751ca165430d46459927cde9bfab838087cbb24aef7/a2a_sdk-0.3.26.tar.gz", hash = "sha256:44068e2d037afbb07ab899267439e9bc7eaa7ac2af94f1e8b239933c993ad52d", size = 274598, upload-time = "2026-04-09T15:21:13.902Z" } +sdist = { url = "https://files.pythonhosted.org/packages/01/3d/215dbe548f197c3d87dcb334569c5e0c16219e546e767966e234e7f5d377/a2a_sdk-1.4.0.tar.gz", hash = "sha256:14f642a58374badc9054b668fd9bc0915eb4a60454a35854de7712f852e45770", size = 466558, upload-time = "2026-11-30T11:00:58.135Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/dd/d5/51f4ee1bf3b736add42a542d3c8a3fd3fa85f3d36c17972127defc46c26f/a2a_sdk-0.3.26-py3-none-any.whl", hash = "sha256:754e0573f6d33b225c1d8d51f640efa69cbbed7bdfb06ce9c3540ea9f58d4a91", size = 151016, upload-time = "2026-04-09T15:21:12.35Z" }, + { url = "https://files.pythonhosted.org/packages/6a/d3/e5b1e3ccd8e1ed8a6ac4be5ae585ce16df4b5a77cccc5955f04539e2f839/a2a_sdk-1.4.0-py3-none-any.whl", hash = "sha256:9b814f6bc62b62de044f4c38342b2ed024fa2eac288bf2f1006194657ebcce3e", size = 310052, upload-time = "2026-11-30T11:00:56.647Z" }, +] + +[package.optional-dependencies] +http-server = [ + { name = "sse-starlette" }, + { name = "starlette" }, ] [[package]] @@ -77,7 +86,7 @@ wheels = [ [[package]] name = "agentkit-sdk-python" -version = "0.8.9" +version = "0.9.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "a2a-sdk" }, @@ -106,9 +115,9 @@ dependencies = [ { name = "volcengine" }, { name = "websocket-client" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/24/1e/e6fef2ff0a54fc8cb854e48b4dd82ee27a7aa5570ca5cb1b15716746f500/agentkit_sdk_python-0.8.9.tar.gz", hash = "sha256:226d868f340b77d3c0113c57a7c55c83a8719d5e13195ef939d12bd810905af5", size = 610207, upload-time = "2026-10-13T02:34:30.875Z" } +sdist = { url = "https://files.pythonhosted.org/packages/c5/27/60815e26bdd089f2f88fd5778c5d9a3da13d2f1b06a2dc0f5f6bac2d8488/agentkit_sdk_python-0.9.3.tar.gz", hash = "sha256:36e55d44f2550dca7461c5c0d7d8cba5120dd8b211ab432ef05a068ec8556121", size = 633954, upload-time = "2026-12-03T03:49:06.568Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/60/93/2417a81bf1a23a938594c99072ae178dbf5fd568e749cb8419b4a85228fa/agentkit_sdk_python-0.8.9-py3-none-any.whl", hash = "sha256:5bf428303615da6c730c6e84f2e4d3de1dd2accab554301a457ab307ed7c5c4f", size = 818571, upload-time = "2026-10-13T02:34:28.96Z" }, + { url = "https://files.pythonhosted.org/packages/63/4d/835da28f0d4d18d88fb0f897a90c2a1e17e6577b64eca9d98dc81e167c61/agentkit_sdk_python-0.9.3-py3-none-any.whl", hash = "sha256:6c46757666617a09bfa0ad5c574f99f94a361c5769fcf8856dee8f74b2a46917", size = 854551, upload-time = "2026-12-03T03:49:05.015Z" }, ] [[package]] @@ -244,6 +253,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ea/c0/649856ee655a843c8f8664592cfccb73ac80ede6a8c8db33a25d810c12db/aiohttp-3.13.4-cp313-cp313-win_amd64.whl", hash = "sha256:74a2eb058da44fa3a877a49e2095b591d4913308bb424c418b77beb160c55ce3", size = 459778, upload-time = "2026-03-28T17:17:21.964Z" }, ] +[[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 = "aiomysql" version = "0.3.2" @@ -1064,6 +1087,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 = "cyclopts" version = "4.23.3" @@ -2600,6 +2636,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/67/c5/82addfd375e5ee6520644e0553e4aadde92d668c4fc99cc716d337fe7bb3/joserfc-1.7.5-py3-none-any.whl", hash = "sha256:add2c2c84e8373b084d526a8b53daba5d7a513a118cd2dcd9fc9f979d0922159", size = 71269, upload-time = "2026-08-29T13:05:40.718Z" }, ] +[[package]] +name = "json-rpc" +version = "1.15.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/74/2d/3942cd7052da88f0ef3eacdc185b8fdc82becdb81768dea5249ea878740e/json_rpc-1.15.2.tar.gz", hash = "sha256:e0e12cd1327d9c743eacc21aeedf432ba31b25792d46a749d850c76dc99c97d4", size = 37294, upload-time = "2026-11-29T23:57:15.795Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3b/36/ddf8b0662258925505bf4c0645af62628a8ca0f3b28063bc852ab844a70c/json_rpc-1.15.2-py2.py3-none-any.whl", hash = "sha256:01c1246f66542b70a8aa1979ddf45b6ded94fc1949ecb53b9f027fcf2bdf712f", size = 49559, upload-time = "2026-11-29T23:57:14.375Z" }, +] + [[package]] name = "jsonpickle" version = "4.1.2" @@ -6058,7 +6103,7 @@ wheels = [ name = "veadk-python" source = { editable = "." } dependencies = [ - { name = "a2a-sdk" }, + { name = "a2a-sdk", extra = ["http-server"] }, { name = "agent-pilot-sdk" }, { name = "agentkit-sdk-python" }, { name = "aiomysql" }, @@ -6179,11 +6224,11 @@ dev = [ [package.metadata] requires-dist = [ - { name = "a2a-sdk", specifier = ">=0.3.7,<1.0.0" }, + { name = "a2a-sdk", extras = ["http-server"], specifier = ">=1.4.0,<1.5.0" }, { name = "a2ui-agent-sdk", marker = "extra == 'a2ui'", specifier = ">=0.2.1" }, { name = "agent-pilot-sdk", specifier = "==0.1.2" }, - { name = "agentkit-sdk-python", specifier = ">=0.8.5" }, - { name = "agentkit-sdk-python", marker = "extra == 'harness-sidecar'", specifier = ">=0.8.5" }, + { name = "agentkit-sdk-python", specifier = ">=0.9.3" }, + { name = "agentkit-sdk-python", marker = "extra == 'harness-sidecar'", specifier = ">=0.9.3" }, { name = "aiomysql", specifier = "==0.3.2" }, { name = "anthropic", marker = "extra == 'sandbox'", specifier = ">=0.40.0" }, { name = "async-timeout", marker = "python_full_version < '3.11'", specifier = ">=5,<6" }, diff --git a/veadk/a2a/agent_card.py b/veadk/a2a/agent_card.py index 8e815d1de..2758c2c34 100644 --- a/veadk/a2a/agent_card.py +++ b/veadk/a2a/agent_card.py @@ -12,15 +12,50 @@ # See the License for the specific language governing permissions and # limitations under the License. -from a2a.types import AgentCapabilities, AgentCard, AgentProvider, AgentSkill +from a2a.types import ( + AgentCapabilities, + AgentCard, + AgentInterface, + AgentProvider, + AgentSkill, +) from veadk import Agent +from veadk.utils.logger import get_logger from veadk.version import VERSION +logger = get_logger(__name__) + + +def _normalize_public_url(url: str) -> str: + """Return a URL suitable for ``AgentInterface.url``. + + ``0.0.0.0`` is a bind address, not a public URL. Existing callers may + still pass it (the FaaS template used to), so keep the process alive and + only warn; the deployment flow is responsible for injecting a real public + URL via ``VEADK_A2A_PUBLIC_URL``. + """ + normalized = (url or "").strip().rstrip("/") + if not normalized: + return "" + if normalized.startswith("0.0.0.0"): + logger.warning( + "AgentCard URL %r is a bind address, not a public URL. " + "A2A clients will not be able to reach the agent; configure " + "VEADK_A2A_PUBLIC_URL or pass a public URL.", + normalized, + ) + return normalized + def get_agent_card( - agent: Agent, url: str, version: str = VERSION, provider: str = "veadk" + agent: Agent, + url: str, + version: str = VERSION, + provider: str = "veadk", + compat_v0_3: bool = True, ) -> AgentCard: + public_url = _normalize_public_url(url) agent_provider = AgentProvider(organization=provider, url="") agent_capabilities = AgentCapabilities() agent_skills = [ @@ -31,15 +66,34 @@ def get_agent_card( tags=["chat", "talk"], ) ] + supported_interfaces = [] + if compat_v0_3: + # Keep the legacy interface first: clients that do not implement the + # SDK's version preference (including hand-written v0.3 clients) read + # the first entry. The SDK client itself always prefers 1.0. + supported_interfaces.append( + AgentInterface( + url=public_url, + protocol_binding="JSONRPC", + protocol_version="0.3", + ) + ) + supported_interfaces.append( + AgentInterface( + url=public_url, + protocol_binding="JSONRPC", + protocol_version="1.0", + ) + ) agent_card = AgentCard( capabilities=agent_capabilities, description=agent.description, name=agent.name, - defaultInputModes=["text"], - defaultOutputModes=["text"], + default_input_modes=["text"], + default_output_modes=["text"], provider=agent_provider, skills=agent_skills, - url=url, + supported_interfaces=supported_interfaces, version=version, ) return agent_card diff --git a/veadk/a2a/hub/a2a_hub_client.py b/veadk/a2a/hub/a2a_hub_client.py index bdc77c104..a9f13f470 100644 --- a/veadk/a2a/hub/a2a_hub_client.py +++ b/veadk/a2a/hub/a2a_hub_client.py @@ -14,6 +14,7 @@ import requests from a2a.types import AgentCard +from a2a.server.request_handlers.response_helpers import agent_card_to_dict class A2AHubClient: @@ -55,7 +56,7 @@ def register_agent(self, group_id: str, agent_id: str, agent_card: AgentCard): json={ "group_id": group_id, "agent_id": agent_id, - "agent_card": agent_card.model_dump(), + "agent_card": agent_card_to_dict(agent_card), }, ) diff --git a/veadk/a2a/remote_ve_agent.py b/veadk/a2a/remote_ve_agent.py index 1eddedaa9..a34a363fa 100644 --- a/veadk/a2a/remote_ve_agent.py +++ b/veadk/a2a/remote_ve_agent.py @@ -12,11 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -import json import functools from typing import AsyncGenerator, Literal, Optional from a2a.client.base_client import BaseClient +from a2a.client.card_resolver import parse_agent_card import httpx import requests from a2a.types import AgentCard @@ -36,9 +36,27 @@ def _convert_agent_card_dict_to_obj(agent_card_dict: dict) -> AgentCard: - agent_card_json_str = json.dumps(agent_card_dict, ensure_ascii=False, indent=2) - agent_card_object = AgentCard.model_validate_json(str(agent_card_json_str)) - return agent_card_object + return parse_agent_card(agent_card_dict) + + +def _rewrite_interface_urls(card: AgentCard, effective_url: str) -> AgentCard: + """Point every HTTP interface at the caller's origin. + + ``parse_agent_card`` ignores the legacy top-level ``url`` as soon as the + card contains ``supportedInterfaces``. A gateway or port-forward would + otherwise send the client back to the address registered inside the card, + so preserve each interface path but replace scheme/host/port with the URL + the caller actually provided. + """ + base = httpx.URL(effective_url) + for interface in card.supported_interfaces: + if not interface.url: + continue + target = httpx.URL(interface.url) + if target.scheme not in ("http", "https"): + continue + interface.url = str(base.copy_with(path=target.path or "/", fragment=None)) + return card class RemoteVeAgent(RemoteA2aAgent): @@ -173,10 +191,8 @@ def __init__( headers=req_headers, params=req_params, ).json() - # replace agent_card_url with actual host - agent_card_dict["url"] = effective_url - agent_card_object = _convert_agent_card_dict_to_obj(agent_card_dict) + agent_card_object = _rewrite_interface_urls(agent_card_object, effective_url) logger.debug(f"Agent card of {name}: {agent_card_object}") diff --git a/veadk/a2a/utils/agent_to_a2a.py b/veadk/a2a/utils/agent_to_a2a.py index ebd104edf..523d8ece1 100644 --- a/veadk/a2a/utils/agent_to_a2a.py +++ b/veadk/a2a/utils/agent_to_a2a.py @@ -13,19 +13,108 @@ # limitations under the License. from __future__ import annotations -from typing import Literal, Optional, Union -from a2a.types import AgentCard +import copy +import json +from contextlib import asynccontextmanager +from pathlib import Path +from typing import AsyncIterator, Literal, Optional, Union + +from a2a.client.card_resolver import parse_agent_card +from a2a.server.request_handlers import DefaultRequestHandler +from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes +from a2a.server.tasks import InMemoryTaskStore +from a2a.types import AgentCard, AgentInterface +from google.adk.a2a.executor.a2a_agent_executor import A2aAgentExecutor +from google.adk.a2a.utils.agent_card_builder import AgentCardBuilder from google.adk.agents import BaseAgent -from starlette.applications import Starlette -from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService -from google.adk.sessions.in_memory_session_service import InMemorySessionService +from google.adk.artifacts.in_memory_artifact_service import ( + InMemoryArtifactService, +) +from google.adk.auth.credential_service.in_memory_credential_service import ( + InMemoryCredentialService, +) from google.adk.memory.in_memory_memory_service import InMemoryMemoryService -from google.adk.a2a.utils.agent_to_a2a import to_a2a as google_adk_to_a2a +from google.adk.runners import Runner as AdkRunner +from google.adk.sessions.in_memory_session_service import InMemorySessionService +from starlette.applications import Starlette + from veadk import Runner from veadk.a2a.ve_middlewares import build_a2a_auth_middleware from veadk.auth.ve_credential_service import VeCredentialService from veadk.consts import DEFAULT_AGENT_NAME +from veadk.utils.logger import get_logger + +logger = get_logger(__name__) + +_AGENT_CARD_WELL_KNOWN_PATH = "/.well-known/agent-card.json" +_PREV_AGENT_CARD_WELL_KNOWN_PATH = "/.well-known/agent.json" + + +def _load_agent_card(agent_card: Union[AgentCard, str, None]) -> Optional[AgentCard]: + """Load a caller-provided AgentCard from an object or a JSON path.""" + if agent_card is None: + return None + if isinstance(agent_card, str): + with Path(agent_card).open("r", encoding="utf-8") as f: + return parse_agent_card(json.load(f)) + return agent_card + + +def _has_protocol_version(card: AgentCard, prefix: str) -> bool: + return any( + (interface.protocol_version or "").startswith(prefix) + for interface in card.supported_interfaces + ) + + +def _augment_agent_card(card: AgentCard, rpc_url: str) -> AgentCard: + """Ensure the card advertises both a v0.3 and a v1.0 JSON-RPC interface. + + ADK's ``AgentCardBuilder`` only emits a 1.0 interface under a2a-sdk 1.x. + A 1.0-only card has no legacy top-level ``url``, so a2a-sdk 0.3.x clients + fail discovery before they reach the v0.3-compatible RPC route. Keep the + caller's card untouched and return an augmented copy. + """ + augmented = copy.deepcopy(card) + interfaces = list(augmented.supported_interfaces) + base_url = next( + (interface.url for interface in interfaces if interface.url), rpc_url + ) + + if not _has_protocol_version(augmented, "0.3"): + interfaces.insert( + 0, + AgentInterface( + url=base_url, + protocol_binding="JSONRPC", + protocol_version="0.3", + ), + ) + if not _has_protocol_version(augmented, "1."): + interfaces.append( + AgentInterface( + url=base_url, + protocol_binding="JSONRPC", + protocol_version="1.0", + ), + ) + + del augmented.supported_interfaces[:] + augmented.supported_interfaces.extend(interfaces) + return augmented + + +def _create_default_runner(agent: BaseAgent) -> AdkRunner: + """Create the same in-memory runner ADK's ``to_a2a`` uses by default.""" + return AdkRunner( + app_name=agent.name or "adk_agent", + agent=agent, + artifact_service=InMemoryArtifactService(), + session_service=InMemorySessionService(), + memory_service=InMemoryMemoryService(), + credential_service=InMemoryCredentialService(), + ) def to_a2a( @@ -39,105 +128,49 @@ def to_a2a( enable_auth: bool = False, auth_method: Literal["header", "querystring"] = "header", ) -> Starlette: - """Convert an ADK agent to a A2A Starlette application with optional VeADK enhancements. + """Convert an ADK agent to a dual-stack A2A Starlette application. - This function wraps Google ADK's to_a2a utility and optionally adds: - - VeCredentialService for authentication management - - A2A authentication middleware for token validation + The public signature is intentionally unchanged. The implementation no + longer delegates to ``google.adk.a2a.utils.agent_to_a2a`` because that + helper only advertises a 1.0 interface under a2a-sdk 1.x. This wrapper + builds the same ``A2aAgentExecutor`` + ``DefaultRequestHandler`` stack, + augments the ADK-built card with a 0.3 interface, and serves both + well-known card paths so a2a-sdk 0.3.x and 1.x clients can discover and + call the agent. Args: - agent: The ADK agent to convert to A2A server - host: The host for the A2A RPC URL (default: "localhost") - port: The port for the A2A RPC URL (default: 8000) - protocol: The protocol for the A2A RPC URL (default: "http") - agent_card: Optional pre-built AgentCard object or path to agent card - JSON. If not provided, will be built automatically from the - agent. + agent: The ADK agent to convert to an A2A server. + host: The host for the A2A RPC URL (default: "localhost"). + port: The port for the A2A RPC URL (default: 8000). + protocol: The protocol for the A2A RPC URL (default: "http"). + agent_card: Optional pre-built AgentCard object or path to an agent + card JSON file. If not provided, the card is built from the agent. runner: Optional pre-built Runner object. If not provided, a default - runner will be created using in-memory services. - When enable_auth=True: - - If runner is provided and has a credential_service, it must be - a VeCredentialService instance (raises TypeError otherwise) - - If runner is provided without credential_service, a new - VeCredentialService will be created and set - - If runner is not provided, a new runner with VeCredentialService - will be created - auth_method: Authentication method for A2A requests (only used when - enable_auth=True). Options: - - "header": Extract token from Authorization header (default) - - "querystring": Extract token from query parameter + runner will be created using in-memory services. enable_auth: Whether to enable VeADK authentication features. - When True, enables credential service and auth middleware. - When False, uses standard Google ADK behavior. - Default: False + auth_method: Authentication method for A2A requests (only used when + enable_auth=True). Options: "header" or "querystring". Returns: - A Starlette application that can be run with uvicorn - - Raises: - TypeError: If enable_auth=True and runner has a credential_service - that is not a VeCredentialService instance - - Example: - Basic usage (without VeADK auth): - ```python - from veadk import Agent - from veadk.a2a.utils.agent_to_a2a import to_a2a - - agent = Agent(name="my_agent", tools=[...]) - app = to_a2a(agent, host="localhost", port=8000) - # Run with: uvicorn module:app --host localhost --port 8000 - ``` - - With VeADK authentication enabled: - ```python - app = to_a2a(agent, enable_auth=True) - ``` - - With custom runner and VeADK auth: - ```python - from veadk import Agent, Runner - from veadk.memory.short_term_memory import ShortTermMemory - from veadk.auth.ve_credential_service import VeCredentialService - - agent = Agent(name="my_agent") - runner = Runner( - agent=agent, - short_term_memory=ShortTermMemory(), - app_name="my_app", - credential_service=VeCredentialService() # Optional - ) - app = to_a2a(agent, runner=runner, enable_auth=True) - ``` - - With querystring authentication: - ```python - app = to_a2a(agent, enable_auth=True, auth_method="querystring") - ``` + A Starlette application that can be run with uvicorn. """ app_name = agent.name or DEFAULT_AGENT_NAME - middleware = None # May need support multiple middlewares in the future + middleware = None - # Handle VeADK authentication setup if enable_auth: - # Create credential service if not provided credential_service = VeCredentialService() if runner is not None: - # Check if runner has credential_service if runner.credential_service is not None: - # Validate that it's a VeCredentialService if not isinstance(runner.credential_service, VeCredentialService): raise TypeError( - f"When enable_auth=True, runner.credential_service must be " - f"a VeCredentialService instance, got {type(runner.credential_service).__name__}" + "When enable_auth=True, runner.credential_service must " + "be a VeCredentialService instance, got " + f"{type(runner.credential_service).__name__}" ) - # Use existing credential service credential_service = runner.credential_service else: - # Add credential_service to runner runner.credential_service = credential_service else: - # Create runner with credential_service runner = Runner( app_name=app_name, agent=agent, @@ -153,17 +186,49 @@ def to_a2a( auth_method=auth_method, ) - # Convert agent to A2A Starlette app using Google ADK utility - app: Starlette = google_adk_to_a2a( - agent=agent, - host=host, - port=port, - protocol=protocol, - agent_card=agent_card, - runner=runner, - ) + if runner is None: + runner = _create_default_runner(agent) + + provided_card = _load_agent_card(agent_card) + rpc_url = f"{protocol}://{host}:{port}/" + card_builder = AgentCardBuilder(agent=agent, rpc_url=rpc_url) + agent_executor = A2aAgentExecutor(runner=runner) + task_store = InMemoryTaskStore() + + async def setup_a2a(app: Starlette) -> None: + if provided_card is not None: + final_card = _augment_agent_card(provided_card, rpc_url) + else: + final_card = _augment_agent_card(await card_builder.build(), rpc_url) + + handler = DefaultRequestHandler( + agent_executor=agent_executor, + task_store=task_store, + agent_card=final_card, + ) + app.routes.extend( + [ + *create_agent_card_routes( + final_card, card_url=_AGENT_CARD_WELL_KNOWN_PATH + ), + *create_agent_card_routes( + final_card, card_url=_PREV_AGENT_CARD_WELL_KNOWN_PATH + ), + *create_jsonrpc_routes( + handler, + rpc_url="/", + enable_v0_3_compat=True, + ), + ] + ) + + @asynccontextmanager + async def _lifespan(app: Starlette) -> AsyncIterator[None]: + await setup_a2a(app) + yield + + app = Starlette(lifespan=_lifespan) - # Add VeADK authentication middleware only if enabled if middleware: app.add_middleware(middleware) diff --git a/veadk/a2a/ve_a2a_server.py b/veadk/a2a/ve_a2a_server.py index f5fb54388..d4fe8afab 100644 --- a/veadk/a2a/ve_a2a_server.py +++ b/veadk/a2a/ve_a2a_server.py @@ -12,21 +12,73 @@ # See the License for the specific language governing permissions and # limitations under the License. -from a2a.server.apps.jsonrpc.fastapi_app import A2AFastAPIApplication -from a2a.server.request_handlers.default_request_handler import DefaultRequestHandler -from a2a.server.tasks.inmemory_task_store import InMemoryTaskStore +import os +from dataclasses import dataclass + +from a2a.server.request_handlers import DefaultRequestHandler +from a2a.server.routes import ( + add_a2a_routes_to_fastapi, + create_agent_card_routes, + create_jsonrpc_routes, +) +from a2a.server.tasks import InMemoryTaskStore from fastapi import FastAPI from veadk import Agent from veadk.a2a.agent_card import get_agent_card from veadk.runner import Runner from veadk.memory.short_term_memory import ShortTermMemory +from veadk.utils.logger import get_logger from google.adk.a2a.executor.a2a_agent_executor import A2aAgentExecutor from google.adk.auth.credential_service.base_credential_service import ( BaseCredentialService, ) +logger = get_logger(__name__) + + +@dataclass +class A2AServerConfig: + """Configuration for the veadk A2A server. + + ``compat_v0_3`` keeps the legacy JSON-RPC methods and the historical + ``/.well-known/agent.json`` card path enabled. ``docs_enabled`` registers + the A2A routes through ``add_a2a_routes_to_fastapi`` so they appear in the + generated OpenAPI schema; it is opt-in and does not change runtime RPC + behavior. + """ + + compat_v0_3: bool = True + docs_enabled: bool = False + + +def _resolve_public_url(server_url: str) -> str: + """Resolve the public URL advertised in the AgentCard. + + The FaaS template historically passed ``0.0.0.0`` (a bind address). Keep + that process alive: prefer the deployment-injected + ``VEADK_A2A_PUBLIC_URL``, then the existing MPA/CLI convention + ``A2A_PUBLIC_URL``, and only warn when neither is available. + """ + candidates = ( + server_url, + os.getenv("VEADK_A2A_PUBLIC_URL", ""), + os.getenv("A2A_PUBLIC_URL", ""), + ) + for candidate in candidates: + normalized = (candidate or "").strip().rstrip("/") + if normalized and not normalized.startswith("0.0.0.0"): + return normalized + + logger.warning( + "A2A public URL is empty or 0.0.0.0; AgentCard clients will not be " + "able to reach the agent. Set VEADK_A2A_PUBLIC_URL or pass a public " + "URL. Falling back to %r.", + server_url, + ) + return (server_url or "").rstrip("/") + class VeA2AServer: def __init__( @@ -36,8 +88,14 @@ def __init__( app_name: str, short_term_memory: ShortTermMemory, credential_service: BaseCredentialService | None = None, + config: A2AServerConfig | None = None, ): - self.agent_card = get_agent_card(agent, url) + self.config = config or A2AServerConfig() + self.agent_card = get_agent_card( + agent, + _resolve_public_url(url), + compat_v0_3=self.config.compat_v0_3, + ) self.agent_executor = A2aAgentExecutor( runner=Runner( @@ -51,17 +109,38 @@ def __init__( self.task_store = InMemoryTaskStore() self.request_handler = DefaultRequestHandler( - agent_executor=self.agent_executor, task_store=self.task_store + agent_executor=self.agent_executor, + task_store=self.task_store, + agent_card=self.agent_card, ) def build(self) -> FastAPI: - app_application = A2AFastAPIApplication( - agent_card=self.agent_card, - http_handler=self.request_handler, + card_routes = [*create_agent_card_routes(self.agent_card)] + if self.config.compat_v0_3: + # a2a-sdk 0.3.x served both paths; keep the historical one so + # existing discovery code keeps working after the upgrade. + card_routes.extend( + create_agent_card_routes( + self.agent_card, + card_url="/.well-known/agent.json", + ) + ) + rpc_routes = create_jsonrpc_routes( + self.request_handler, + rpc_url="/", + enable_v0_3_compat=self.config.compat_v0_3, ) - app = app_application.build() # build routes - return app + if self.config.docs_enabled: + app = FastAPI() + add_a2a_routes_to_fastapi( + app, + agent_card_routes=card_routes, + jsonrpc_routes=rpc_routes, + ) + return app + + return FastAPI(routes=[*card_routes, *rpc_routes]) def init_app( @@ -70,6 +149,7 @@ def init_app( agent: Agent, short_term_memory: ShortTermMemory, credential_service: BaseCredentialService | None = None, + config: A2AServerConfig | None = None, ) -> FastAPI: """Init the fastapi application in terms of VeADK agent. @@ -78,6 +158,9 @@ def init_app( app_name: str, the name of the app agent: Agent, the agent of the app short_term_memory: ShortTermMemory, the short term memory of the app + credential_service: optional credential service used by the runner + config: optional server configuration; defaults to dual-stack v0.3 + + v1.0 with the legacy card path enabled Returns: FastAPI, the fastapi app @@ -85,9 +168,10 @@ def init_app( server = VeA2AServer( agent=agent, - url=server_url, + url=_resolve_public_url(server_url), app_name=app_name, short_term_memory=short_term_memory, credential_service=credential_service, + config=config, ) return server.build() diff --git a/veadk/a2a/ve_agent_executor.py b/veadk/a2a/ve_agent_executor.py index f9e84ce3a..db0a16d21 100644 --- a/veadk/a2a/ve_agent_executor.py +++ b/veadk/a2a/ve_agent_executor.py @@ -15,7 +15,7 @@ from a2a.server.agent_execution.agent_executor import AgentExecutor from a2a.server.agent_execution.context import RequestContext from a2a.server.events.event_queue import EventQueue -from a2a.utils import new_agent_text_message +from a2a.helpers import new_text_message from typing_extensions import override from veadk import Agent @@ -71,7 +71,7 @@ async def execute(self, context: RequestContext, event_queue: EventQueue) -> Non logger.debug(f"Final output: {final_output}") - await event_queue.enqueue_event(new_agent_text_message(final_output)) + await event_queue.enqueue_event(new_text_message(final_output)) @override async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None: diff --git a/veadk/a2a/ve_task_store.py b/veadk/a2a/ve_task_store.py index 0c1555dda..6f0e3a62b 100644 --- a/veadk/a2a/ve_task_store.py +++ b/veadk/a2a/ve_task_store.py @@ -12,8 +12,9 @@ # See the License for the specific language governing permissions and # limitations under the License. +from a2a.server.context import ServerCallContext from a2a.server.tasks import TaskStore -from a2a.types import Task +from a2a.types import ListTasksRequest, ListTasksResponse, Task from typing_extensions import override @@ -22,16 +23,29 @@ def __init__(self): super().__init__() @override - async def save(self, task: Task) -> None: + async def save(self, task: Task, context: ServerCallContext | None = None) -> None: """Saves or updates a task in the store.""" return None @override - async def get(self, task_id: str) -> Task | None: + async def get( + self, task_id: str, context: ServerCallContext | None = None + ) -> Task | None: """Retrieves a task from the store by ID.""" return None @override - async def delete(self, task_id: str) -> None: + async def list( + self, + params: ListTasksRequest, + context: ServerCallContext | None = None, + ) -> ListTasksResponse: + """Retrieves a list of tasks from the store.""" + return ListTasksResponse() + + @override + async def delete( + self, task_id: str, context: ServerCallContext | None = None + ) -> None: """Deletes a task from the store by ID.""" return None diff --git a/veadk/agents/_remote_sandbox/skill.py b/veadk/agents/_remote_sandbox/skill.py index ffb276b2c..713ef891b 100644 --- a/veadk/agents/_remote_sandbox/skill.py +++ b/veadk/agents/_remote_sandbox/skill.py @@ -23,16 +23,17 @@ import httpx from a2a.client import ClientConfig, ClientFactory -from a2a.client.errors import A2AClientHTTPError, A2AClientTimeoutError +from a2a.client.card_resolver import parse_agent_card +from a2a.client.errors import A2AClientError from a2a.types import ( - AgentCard, + CancelTaskRequest, + GetTaskRequest, Message, Part, - TaskArtifactUpdateEvent, - TaskIdParams, - TaskQueryParams, + Role, + SendMessageRequest, + Task, TaskState, - TextPart, ) from google.adk.a2a.converters.part_converter import convert_a2a_part_to_genai_part from google.genai import types @@ -41,7 +42,7 @@ from veadk.agents._remote_sandbox.code import check_lease, event_for, observation from veadk.agents.agentkit_remote_sandbox_agent import SandboxAgentError -_ACTIVE = {TaskState.submitted, TaskState.working} +_ACTIVE = {TaskState.TASK_STATE_SUBMITTED, TaskState.TASK_STATE_WORKING} def endpoint_path(endpoint, path): @@ -51,6 +52,14 @@ def endpoint_path(endpoint, path): return url.copy_with(path=url.path.rstrip("/") + "/" + path.lstrip("/")) +def _is_text(part: Part) -> bool: + return part.WhichOneof("content") == "text" + + +def _text_of(parts) -> str: + return "".join(part.text for part in parts or [] if _is_text(part)) + + async def skill_events( *, agent, ctx, endpoint, headers, binding, turn_key, task, context, lease ): @@ -64,7 +73,7 @@ async def skill_events( endpoint_path(endpoint, "/.well-known/agent-card.json") ) if response.status_code == 200: - card = AgentCard.model_validate(response.json()) + card = parse_agent_card(response.json()) break if response.status_code not in {502, 503, 504}: raise SandboxAgentError( @@ -75,15 +84,18 @@ async def skill_events( await asyncio.sleep(1) check_lease(agent, lease) # Keep the platform authority/query, using only the Card's RPC path. - card = card.model_copy(deep=True) - card.url = str(endpoint_path(endpoint, httpx.URL(card.url).path)) - card.additional_interfaces = None + base = httpx.URL(endpoint) + for interface in card.supported_interfaces: + if not interface.url: + continue + target = httpx.URL(interface.url) + interface.url = str(base.copy_with(path=target.path or "/", fragment=None)) client = ClientFactory( ClientConfig( httpx_client=http, streaming=bool(card.capabilities.streaming), polling=True, - supported_transports=["JSONRPC"], + supported_protocol_bindings=["JSONRPC"], use_client_preference=True, ) ).create(card) @@ -99,11 +111,18 @@ async def skill_events( invocations[turn_key] = {"status": "submitting"} message = Message( message_id=turn_key, - role="user", - parts=[Part(root=TextPart(text=task))], + role=Role.ROLE_USER, + parts=[Part(text=task)], context_id=context.get("context_id"), ) - remote_task = None + request = SendMessageRequest( + message=message, + metadata={ + "user_id": ctx.user_id, + "session_id": ctx.session.id, + }, + ) + remote_task: Task | None = None completed = False emitted = set() final_text = "" @@ -157,81 +176,107 @@ def convert(parts, *, source): ) return result - def consume(response): - nonlocal remote_task, final_text, completed - if isinstance(response, Message): - completed = True - if response.context_id: - context["context_id"] = response.context_id - final_text = "\n".join( - p.root.text for p in response.parts if isinstance(p.root, TextPart) - ) - return convert(response.parts, source=response.message_id) - remote_task, update = response + def consume_message(message: Message): + nonlocal final_text, completed + # A direct Message response is a terminal result, exactly like a + # completed Task. Keep that pre-1.4 behavior so message-only + # Skill servers do not fail the "no terminal task" check below. + completed = True + if message.context_id: + context["context_id"] = message.context_id + final_text = "\n".join( + part.text for part in message.parts if _is_text(part) + ) + return convert(message.parts, source=message.message_id) + + def consume_task(task: Task): + nonlocal remote_task, final_text + remote_task = task invocations[turn_key] = { - "status": remote_task.status.state.value, - "task_id": remote_task.id, + "status": TaskState.Name(task.status.state), + "task_id": task.id, } - if remote_task.context_id: - context["context_id"] = remote_task.context_id - if isinstance(update, TaskArtifactUpdateEvent): - artifact = update.artifact - text = "".join( - p.root.text for p in artifact.parts if isinstance(p.root, TextPart) - ) - snapshots[artifact.artifact_id] = ( - (snapshots.get(artifact.artifact_id, "") + text) - if update.append - else text - ) - return convert(artifact.parts, source=artifact.artifact_id) + if task.context_id: + context["context_id"] = task.context_id events = [] - messages = list(remote_task.history or []) if update is None else [] - if remote_task.status.message: - messages.append(remote_task.status.message) + messages = list(task.history or []) + if task.status.message: + messages.append(task.status.message) for msg in messages: - if msg.role == "user" or msg.message_id in emitted: + if msg.role == Role.ROLE_USER or msg.message_id in emitted: continue emitted.add(msg.message_id) events.extend(convert(msg.parts, source=msg.message_id)) + if task.status.state not in _ACTIVE: + text = _text_of(msg.parts) + if text: + final_text = text + # Final/polled snapshots provide authoritative artifacts. + for artifact in task.artifacts or []: + snapshots[artifact.artifact_id] = _text_of(artifact.parts) + tool_parts = [part for part in artifact.parts if not _is_text(part)] + events.extend(convert(tool_parts, source=artifact.artifact_id)) + return events + + def consume_status_update(update): + nonlocal remote_task, final_text + if remote_task is None: + remote_task = Task( + id=update.task_id, + context_id=update.context_id, + status=update.status, + ) + else: + if update.task_id: + remote_task.id = update.task_id + if update.context_id: + remote_task.context_id = update.context_id + remote_task.status.CopyFrom(update.status) + invocations[turn_key] = { + "status": TaskState.Name(remote_task.status.state), + "task_id": remote_task.id, + } + if remote_task.context_id: + context["context_id"] = remote_task.context_id + events = [] + message = update.status.message + if message and message.message_id not in emitted: + emitted.add(message.message_id) + events.extend(convert(message.parts, source=message.message_id)) if remote_task.status.state not in _ACTIVE: - text = "\n".join( - p.root.text for p in msg.parts if isinstance(p.root, TextPart) - ) + text = _text_of(message.parts) if text: final_text = text - # Final/polled snapshots provide authoritative artifacts. Streaming - # artifact deltas were already shown; only extract tools on final. - if update is None or remote_task.status.state not in _ACTIVE: - for artifact in remote_task.artifacts or []: - snapshots[artifact.artifact_id] = "".join( - p.root.text - for p in artifact.parts - if isinstance(p.root, TextPart) - ) - tool_parts = [ - p for p in artifact.parts if not isinstance(p.root, TextPart) - ] - events.extend(convert(tool_parts, source=artifact.artifact_id)) return events + def consume_artifact_update(update): + artifact = update.artifact + text = _text_of(artifact.parts) + snapshots[artifact.artifact_id] = ( + (snapshots.get(artifact.artifact_id, "") + text) + if update.append + else text + ) + return convert(artifact.parts, source=artifact.artifact_id) + + def consume(chunk): + if chunk.HasField("message"): + return consume_message(chunk.message) + if chunk.HasField("task"): + return consume_task(chunk.task) + if chunk.HasField("status_update"): + return consume_status_update(chunk.status_update) + if chunk.HasField("artifact_update"): + return consume_artifact_update(chunk.artifact_update) + return [] + try: async with timeout(agent.request_timeout): try: - async for response in client.send_message( - message, - request_metadata={ - "user_id": ctx.user_id, - "session_id": ctx.session.id, - }, - ): - for event in consume(response): + async for chunk in client.send_message(request): + for event in consume(chunk): yield event - except ( - httpx.TransportError, - A2AClientHTTPError, - A2AClientTimeoutError, - ): + except (httpx.TransportError, A2AClientError): # An accepted Task can be queried; never send the message twice. if remote_task is None: raise SandboxAgentError( @@ -240,15 +285,16 @@ def consume(response): while remote_task and remote_task.status.state in _ACTIVE: await asyncio.sleep(1) queried = await client.get_task( - TaskQueryParams(id=remote_task.id, history_length=20) + GetTaskRequest(id=remote_task.id, history_length=20) ) - for event in consume((queried, None)): + for event in consume_task(queried): yield event if remote_task: completed = remote_task.status.state not in _ACTIVE - if remote_task.status.state != TaskState.completed: + if remote_task.status.state != TaskState.TASK_STATE_COMPLETED: raise SandboxAgentError( - f"Skill task ended with state {remote_task.status.state.value}" + "Skill task ended with state " + f"{TaskState.Name(remote_task.status.state)}" ) if not completed: raise SandboxAgentError( @@ -274,6 +320,7 @@ def consume(response): if remote_task and not completed: with suppress(Exception): await asyncio.wait_for( - client.cancel_task(TaskIdParams(id=remote_task.id)), timeout=10 + client.cancel_task(CancelTaskRequest(id=remote_task.id)), + timeout=10, ) await client.close() diff --git a/veadk/cloud/cloud_agent_engine.py b/veadk/cloud/cloud_agent_engine.py index 00bf34a60..c562ebf5a 100644 --- a/veadk/cloud/cloud_agent_engine.py +++ b/veadk/cloud/cloud_agent_engine.py @@ -346,6 +346,13 @@ def deploy( ) _ = function_id # for future use + # 方案 B:公网地址只有在首次发布后才知道,把它注入函数环境变量 + # 并重新发布,供 AgentCard 使用。重复部署时该值不变,会跳过更新。 + self._vefaas_service.merge_function_envs_and_release( + function_id=function_id, + extra_envs={"VEADK_A2A_PUBLIC_URL": vefaas_application_url}, + ) + veapig_gateway_id, _, veapig_route_id = ( self._vefaas_service.get_application_route(app_id=app_id) ) @@ -555,6 +562,12 @@ def update_function_code( path=path, ) ) + # The code update preserves the function env list, but an app + # created before this feature may not carry the public URL yet. + self._vefaas_service.merge_function_envs_and_release( + function_id=function_id, + extra_envs={"VEADK_A2A_PUBLIC_URL": vefaas_application_url}, + ) return CloudApp( vefaas_application_name=application_name, diff --git a/veadk/cloud/cloud_app.py b/veadk/cloud/cloud_app.py index b308d6b25..5640f113c 100644 --- a/veadk/cloud/cloud_app.py +++ b/veadk/cloud/cloud_app.py @@ -15,12 +15,23 @@ import json import os import time -from typing import Any +from dataclasses import dataclass, field +from typing import Any, AsyncIterator from uuid import uuid4 import httpx -from a2a.client import A2ACardResolver, A2AClient -from a2a.types import AgentCard, Message, MessageSendParams, SendMessageRequest +from a2a.client import A2ACardResolver, ClientCallContext, ClientConfig, ClientFactory +from a2a.types import ( + AgentCard, + AgentCapabilities, + AgentInterface, + Message, + Part, + Role, + SendMessageRequest, + StreamResponse, +) +from google.protobuf.json_format import MessageToDict from veadk.config import getenv from veadk.utils.logger import get_logger @@ -29,6 +40,106 @@ logger = get_logger(__name__) +@dataclass +class CloudPart: + """Lightweight A2A text part that keeps the historical ``.root`` access.""" + + text: str = "" + raw: bytes = b"" + url: str = "" + metadata: dict[str, Any] | None = None + filename: str = "" + media_type: str = "" + + @property + def root(self) -> "CloudPart": + return self + + def __str__(self) -> str: + return self.text + + +@dataclass +class CloudMessage: + """VeADK-owned response wrapper for :meth:`CloudApp.message_send`. + + a2a-sdk 1.x exposes a flat Protobuf ``Part`` and no Pydantic ``.root``. + The official tutorial and the FaaS template use ``parts[0].root.text``, + so this wrapper exposes both the historical and the new access style: + ``parts[0].root.text`` and ``parts[0].text``. + """ + + message_id: str = "" + role: str = "agent" + parts: list[CloudPart] = field(default_factory=list) + context_id: str = "" + task_id: str = "" + metadata: dict[str, Any] | None = None + reference_task_ids: list[str] = field(default_factory=list) + + @property + def messageId(self) -> str: + return self.message_id + + @property + def text(self) -> str: + return "".join(part.text for part in self.parts) + + def __str__(self) -> str: + return self.text + + @classmethod + def from_message(cls, message: Message) -> "CloudMessage": + return cls( + message_id=message.message_id, + role="agent" if message.role == Role.ROLE_AGENT else "user", + parts=[ + CloudPart( + text=part.text, + raw=part.raw, + url=part.url, + metadata=( + MessageToDict(part.metadata) + if part.HasField("metadata") + else None + ), + filename=part.filename, + media_type=part.media_type, + ) + for part in message.parts + ], + context_id=message.context_id, + task_id=message.task_id, + metadata=( + MessageToDict(message.metadata) + if message.HasField("metadata") + else None + ), + reference_task_ids=list(message.reference_task_ids), + ) + + @classmethod + async def from_stream( + cls, stream: AsyncIterator[StreamResponse] + ) -> "CloudMessage | None": + """Reduce a non-streaming ``StreamResponse`` to the historical shape. + + ``message_send`` has always used non-streaming ``message/send``: a + ``Message`` is returned directly, while a ``Task`` is reduced to the + last agent message in its history (or ``None`` when there is none). + """ + async for chunk in stream: + if chunk.HasField("message"): + return cls.from_message(chunk.message) + if chunk.HasField("task"): + task = chunk.task + agent_messages = [ + msg for msg in reversed(task.history) if msg.role == Role.ROLE_AGENT + ] + return cls.from_message(agent_messages[0]) if agent_messages else None + return None + + class CloudApp: """Represents a deployed cloud agent application on Volcengine FaaS platform. @@ -224,38 +335,49 @@ def _get_vefaas_application_id_by_name(self) -> str: ) return vefaas_application_id - async def _get_a2a_client(self) -> A2AClient: + async def _get_a2a_client(self): """Constructs an A2A client configured for this cloud app. - If use_agent_card, resolves agent card and uses its URL; otherwise uses direct endpoint. - - Args: - self: The CloudApp instance. + If use_agent_card, resolves the agent card and lets the SDK select the + matching interface; otherwise constructs a minimal v0.3-only card and + sends ``message/send`` directly to the configured endpoint. The + default mode deliberately does not fetch the card: that was the + pre-1.4 behavior and avoids an extra network round-trip. Returns: - A2AClient: Ready-to-use A2A client. + A ready-to-use a2a client. Note: - Manages httpx_client context. - For card mode, fetches from base_url/ (public card). + The shared ``httpx_client`` is passed through ``ClientConfig``; + the SDK marks it shared and never closes it. Callers close it via + :meth:`aclose` or ``async with``. """ if self.use_agent_card: - async with self.httpx_client as httpx_client: - resolver = A2ACardResolver( - httpx_client=httpx_client, base_url=self.vefaas_endpoint - ) - - final_agent_card_to_use: AgentCard | None = None - _public_card = ( - await resolver.get_agent_card() - ) # Fetches from default public path - final_agent_card_to_use = _public_card - - return A2AClient( - httpx_client=self.httpx_client, agent_card=final_agent_card_to_use - ) + resolver = A2ACardResolver( + httpx_client=self.httpx_client, base_url=self.vefaas_endpoint + ) + card = await resolver.get_agent_card() else: - return A2AClient(httpx_client=self.httpx_client, url=self.vefaas_endpoint) + card = AgentCard( + name="cloud_app", + description="CloudApp default endpoint", + version="1.0.0", + supported_interfaces=[ + AgentInterface( + url=self.vefaas_endpoint, + protocol_binding="JSONRPC", + protocol_version="0.3", + ) + ], + capabilities=AgentCapabilities(), + default_input_modes=["text"], + default_output_modes=["text"], + skills=[], + ) + + return ClientFactory( + ClientConfig(httpx_client=self.httpx_client, streaming=False) + ).create(card) def update_self( self, @@ -374,10 +496,12 @@ def delete_self( async def message_send( self, message: str, session_id: str, user_id: str, timeout: float = 600.0 - ) -> Message | None: + ) -> CloudMessage | None: """Sends a user message to the cloud agent and retrieves the response. - Constructs A2A SendMessageRequest and executes via client. + The public signature is unchanged. The return value is a VeADK-owned + ``CloudMessage`` wrapper that supports both the historical + ``parts[0].root.text`` and the a2a 1.x ``parts[0].text`` access. Args: message (str): Text content of the user message. @@ -386,102 +510,75 @@ async def message_send( timeout (float): Maximum wait time in seconds. Defaults to 600.0. Returns: - Message | None: Assistant response message or None if error occurs. - - Raises: - Exception: Communication or processing errors; error is printed. + CloudMessage | None: Assistant response message or None if an + error occurs. Note: - Uses UUID for message and request IDs. - Payload includes role 'user' and text part. - Debug logs the full response. - Ignores type checks for result as it may not be Task. + Uses a non-streaming ``message/send``. A ``Task`` response is + reduced to the last agent message in its history, matching the + pre-1.4 behavior. Examples: ```python response = await app.message_send("What is AI?", "chat-1", "user-1", timeout=300) - print(response.content) + print(response.parts[0].root.text) ``` """ - a2a_client = await self._get_a2a_client() - - async with self.httpx_client: - send_message_payload: dict[str, Any] = { - "message": { - "role": "user", - "parts": [{"type": "text", "text": message}], - "messageId": uuid4().hex, - }, - "metadata": { - "user_id": user_id, - "session_id": session_id, - }, - } - try: - message_send_request = SendMessageRequest( - id=uuid4().hex, - params=MessageSendParams(**send_message_payload), - ) + try: + a2a_client = await self._get_a2a_client() + message_send_request = SendMessageRequest( + message=Message( + message_id=uuid4().hex, + role=Role.ROLE_USER, + parts=[Part(text=message)], + ), + metadata={"user_id": user_id, "session_id": session_id}, + ) - res = await a2a_client.send_message( + result = await CloudMessage.from_stream( + a2a_client.send_message( message_send_request, - http_kwargs={"timeout": httpx.Timeout(timeout)}, + context=ClientCallContext(timeout=timeout), ) + ) - logger.debug( - f"Message sent to cloud app {self.vefaas_application_name} with response: {res}" - ) + logger.debug( + f"Message sent to cloud app {self.vefaas_application_name} " + f"with response: {result}" + ) + return result + except Exception as e: + logger.error(f"Failed to send message to cloud app. Error: {e}") + return None - # we ignore type checking here, because the response - # from CloudApp will not be `Task` type - result = res.root.result # type: ignore - try: - from a2a.types import Task - except ImportError: - return result - - if isinstance(result, Task): - if result.history: # type: ignore - return next( - ( - msg - for msg in reversed(result.history) # type: ignore - if msg.role == "agent" - ), - None, - ) - else: - return None - else: - return result - except Exception as e: - logger.error(f"Failed to send message to cloud app. Error: {e}") - return None - - -def get_message_id(message: Message): - """Extracts the unique ID from an A2A Message object. - - Checks for both legacy 'messageId' and current 'message_id' attributes. + async def aclose(self) -> None: + """Close the shared HTTP client if it is still open.""" + if not self.httpx_client.is_closed: + await self.httpx_client.aclose() + + async def close(self) -> None: + """Alias of :meth:`aclose` for callers that use ``close()``.""" + await self.aclose() + + async def __aenter__(self) -> "CloudApp": + return self + + async def __aexit__(self, exc_type, exc, tb) -> None: + await self.aclose() + + +def get_message_id(message: Message | CloudMessage): + """Extracts the unique ID from an A2A message or CloudMessage. + + Checks for both the legacy 'messageId' and the current 'message_id'. Args: - message (Message): The A2A message instance. + message: The A2A message or CloudMessage instance. Returns: str: The message identifier. - - Note: - Ensures compatibility with a2a-python versions before and after 0.3.0. - Prefers 'message_id' if available, falls back to 'messageId'. - - Examples: - ```python - mid = get_message_id(response_message) - print(mid) - ``` """ if getattr(message, "messageId", None): - # Compatible with the messageId of the old a2a-python version (<0.3.0) in cloud app + # Compatible with the messageId of the old a2a-python version (<0.3.0) return message.messageId # type: ignore - else: - return message.message_id + return message.message_id diff --git a/veadk/integrations/ve_faas/template/{{cookiecutter.local_dir_name}}/deploy.py b/veadk/integrations/ve_faas/template/{{cookiecutter.local_dir_name}}/deploy.py index 51abebe15..64edbde0e 100644 --- a/veadk/integrations/ve_faas/template/{{cookiecutter.local_dir_name}}/deploy.py +++ b/veadk/integrations/ve_faas/template/{{cookiecutter.local_dir_name}}/deploy.py @@ -15,7 +15,6 @@ import asyncio from pathlib import Path -from a2a.types import TextPart from fastmcp.client import Client from veadk.cloud.cloud_agent_engine import CloudAgentEngine @@ -38,14 +37,9 @@ async def _send_msg_with_a2a(cloud_app: CloudApp, message: str) -> None: print(f"Message ID: {get_message_id(response_message)}") - if isinstance(response_message.parts[0].root, TextPart): - print( - f"Response from {cloud_app.vefaas_endpoint}: {response_message.parts[0].root.text}" - ) - else: - print( - f"Response from {cloud_app.vefaas_endpoint}: {response_message.parts[0].root}" - ) + print( + f"Response from {cloud_app.vefaas_endpoint}: {response_message.parts[0].text}" + ) async def _send_msg_with_mcp(cloud_app: CloudApp, message: str) -> None: diff --git a/veadk/integrations/ve_faas/template/{{cookiecutter.local_dir_name}}/src/app.py b/veadk/integrations/ve_faas/template/{{cookiecutter.local_dir_name}}/src/app.py index 9807c944e..1fa478c5b 100644 --- a/veadk/integrations/ve_faas/template/{{cookiecutter.local_dir_name}}/src/app.py +++ b/veadk/integrations/ve_faas/template/{{cookiecutter.local_dir_name}}/src/app.py @@ -26,6 +26,7 @@ from starlette.routing import Route from google.adk.a2a.utils.agent_card_builder import AgentCardBuilder +from a2a.server.request_handlers.response_helpers import agent_card_to_dict from a2a.types import AgentProvider from veadk.a2a.ve_a2a_server import init_app @@ -117,7 +118,7 @@ async def run_agent( async def agent_card() -> dict: agent_card = await agent_card_builder.build() - return agent_card.model_dump() + return agent_card_to_dict(agent_card) async def get_cozeloop_space_id() -> dict: return {"space_id": os.getenv("OBSERVABILITY_OPENTELEMETRY_COZELOOP_SERVICE_NAME", default="")} @@ -127,8 +128,15 @@ async def get_cozeloop_space_id() -> dict: # Build a run_agent function for building MCP server run_agent_func = build_mcp_run_agent_func() +public_url = os.getenv("VEADK_A2A_PUBLIC_URL", "").strip().rstrip("/") +if not public_url: + raise RuntimeError( + "VEADK_A2A_PUBLIC_URL is required; it must be the public JSON-RPC URL " + "injected at deploy time, not 0.0.0.0" + ) + a2a_app = init_app( - server_url="0.0.0.0", + server_url=public_url, app_name=app_name, agent=agent, short_term_memory=short_term_memory, @@ -140,7 +148,8 @@ async def get_cozeloop_space_id() -> dict: # === Build mcp server === -mcp = FastMCP.from_fastapi(app=a2a_app, name=app_name, include_tags={"mcp"}) +mcp = FastMCP.from_fastapi(app=a2a_app, name=app_name) +mcp.enable(tags={"mcp"}, only=True) # Create MCP ASGI app mcp_app = mcp.http_app(path="/", transport="streamable-http") diff --git a/veadk/integrations/ve_faas/ve_faas.py b/veadk/integrations/ve_faas/ve_faas.py index e7fef939c..1952f6beb 100644 --- a/veadk/integrations/ve_faas/ve_faas.py +++ b/veadk/integrations/ve_faas/ve_faas.py @@ -378,10 +378,17 @@ def _create_function( *, cpu_milli: int | None = None, memory_mb: int | None = None, + extra_envs: dict[str, str] | None = None, ): # Read envs envs = [] - for key, value in veadk.config.veadk_environments.items(): + merged_envs = { + key: value + for key, value in veadk.config.veadk_environments.items() + if value is not None + } + merged_envs.update(extra_envs or {}) + for key, value in merged_envs.items(): envs.append(EnvForCreateFunctionInput(key=key, value=value)) logger.info( f"Fetch {len(envs)} environment variables.", @@ -846,18 +853,28 @@ def _update_function_code( tmp_path = temp_base / tmp_dir_name try: - agent_dir = tmp_path / "src" / user_proj_path.name.replace("-", "_") - if agent_dir.exists(): - shutil.rmtree(agent_dir) - agent_dir.mkdir(parents=True, exist_ok=True) - shutil.copytree(user_proj_path, agent_dir, dirs_exist_ok=True) - user_requirements = user_proj_path / "requirements.txt" - - if user_requirements.exists(): - logger.debug("Using user-provided requirements.txt") - shutil.copy(user_requirements, tmp_path / "src" / "requirements.txt") + if (user_proj_path / "app.py").exists(): + # `veadk init` projects pass the rendered `src` directory to + # deploy(). Update that directory in place instead of nesting + # it under `src/`, which would break relative + # requirements paths such as local wheels. + logger.debug("Updating an already-rendered src directory in place") + shutil.copytree(user_proj_path, tmp_path / "src", dirs_exist_ok=True) else: - logger.warning("No requirements.txt found, using template default") + agent_dir = tmp_path / "src" / user_proj_path.name.replace("-", "_") + if agent_dir.exists(): + shutil.rmtree(agent_dir) + agent_dir.mkdir(parents=True, exist_ok=True) + shutil.copytree(user_proj_path, agent_dir, dirs_exist_ok=True) + user_requirements = user_proj_path / "requirements.txt" + + if user_requirements.exists(): + logger.debug("Using user-provided requirements.txt") + shutil.copy( + user_requirements, tmp_path / "src" / "requirements.txt" + ) + else: + logger.warning("No requirements.txt found, using template default") self._replace_application_code_bundle( function_id=function_id, @@ -875,6 +892,10 @@ def _update_function_code( f"VeFaaS application {application_name} with ID {app_id} released." ) logger.info(f"VeFaaS application {application_name} updated on {url}.") + self.merge_function_envs_and_release( + function_id=function_id, + extra_envs={"VEADK_A2A_PUBLIC_URL": url}, + ) return url, app_id, function_id finally: @@ -1087,6 +1108,68 @@ def update_function_envs_and_release( time.sleep(5) logger.warning("Function re-release did not settle within timeout.") + def merge_function_envs_and_release( + self, function_id: str, extra_envs: dict + ) -> None: + """Merge ``extra_envs`` into the function's current env vars and release. + + Unlike :meth:`update_function_envs_and_release`, this preserves the + env vars already configured on the function (including + platform-provided values such as ``_FAAS_FUNC_ID`` and ``APP_REGION``) + instead of replacing the whole list with local ``veadk_environments``. + It is idempotent: when the values are already present no update or + release is issued. + + Used by :class:`veadk.cloud.cloud_agent_engine.CloudAgentEngine` to + inject ``VEADK_A2A_PUBLIC_URL`` after the public endpoint is known. + """ + import time + + from volcenginesdkvefaas import ( + EnvForUpdateFunctionInput, + GetFunctionRequest, + GetReleaseStatusRequest, + ReleaseRequest, + UpdateFunctionRequest, + ) + + function = self.client.get_function(GetFunctionRequest(id=function_id)) + environment = { + item.key: item.value for item in (getattr(function, "envs", None) or []) + } + if all(environment.get(key) == value for key, value in extra_envs.items()): + logger.debug( + "Function %s already has envs %s; skipping release.", + function_id, + sorted(extra_envs), + ) + return + + environment.update(extra_envs) + self.client.update_function( + UpdateFunctionRequest( + id=function_id, + envs=[ + EnvForUpdateFunctionInput(key=key, value=value) + for key, value in environment.items() + ], + ) + ) + # revision_number=0 releases the latest revision. + self.client.release(ReleaseRequest(function_id=function_id, revision_number=0)) + + for _ in range(60): + status = self.client.get_release_status( + GetReleaseStatusRequest(function_id=function_id) + ) + state = str(getattr(status, "status", "") or "").lower() + if "succ" in state or state == "done": + return + if "fail" in state or "error" in state: + raise RuntimeError(f"Function re-release failed: {state}") + time.sleep(5) + logger.warning("Function re-release did not settle within timeout.") + def deploy( self, name: str, @@ -1163,6 +1246,10 @@ def deploy( logger.info( f"VeFaaS application {name} with ID {existing_app_id} updated on {url}." ) + self.merge_function_envs_and_release( + function_id=function_id, + extra_envs={"VEADK_A2A_PUBLIC_URL": url}, + ) return url, existing_app_id, function_id # Give default names @@ -1194,8 +1281,17 @@ def deploy( f"Start to create VeFaaS function {function_name} with path {path}. Gateway: {gateway_name}, Gateway Service: {gateway_service_name}, Gateway Upstream: {gateway_upstream_name}." ) try: + # The template validates VEADK_A2A_PUBLIC_URL at import time, but + # the real public URL is only known after the first release. Seed + # a syntactically valid placeholder so the first release can boot, + # then replace it with the real URL and release again below. + pending_public_url = "http://veadk-a2a-public-url-pending.invalid" function_name, function_id = self._create_function( - function_name, path, cpu_milli=cpu_milli, memory_mb=memory_mb + function_name, + path, + cpu_milli=cpu_milli, + memory_mb=memory_mb, + extra_envs={"VEADK_A2A_PUBLIC_URL": pending_public_url}, ) logger.info( f"VeFaaS function {function_name} with ID {function_id} created." @@ -1215,6 +1311,10 @@ def deploy( logger.info(f"VeFaaS application {name} with ID {app_id} created.") logger.info(f"Start to release VeFaaS application {app_id}.") url = self._release_application(app_id) + self.merge_function_envs_and_release( + function_id=function_id, + extra_envs={"VEADK_A2A_PUBLIC_URL": url}, + ) self._set_function_min_instance(function_id, max_instance=max_instance) self.ensure_application_route_methods( app_id, diff --git a/veadk/integrations/ve_identity/auth_processor.py b/veadk/integrations/ve_identity/auth_processor.py index 2dea7cec2..f3a967cac 100644 --- a/veadk/integrations/ve_identity/auth_processor.py +++ b/veadk/integrations/ve_identity/auth_processor.py @@ -33,7 +33,7 @@ get_function_call_id, is_pending_auth_event, ) -from a2a.utils import new_agent_text_message +from a2a.helpers import new_text_message from veadk.utils.logger import get_logger from a2a.server.tasks import TaskUpdater @@ -240,8 +240,8 @@ async def process_auth_request( updated_oauth2_auth = await active_poller.poll_for_auth() if task_updater: await task_updater.update_status( - TaskState.working, - message=new_agent_text_message("Authorization received, continuing..."), + TaskState.TASK_STATE_WORKING, + message=new_text_message("Authorization received, continuing..."), ) for k, v in updated_oauth2_auth.__dict__.items(): if ( diff --git a/veadk/runner.py b/veadk/runner.py index 0b79c02a8..c31a26350 100644 --- a/veadk/runner.py +++ b/veadk/runner.py @@ -517,10 +517,21 @@ def __init__( **kwargs, ) - self.run_async = MethodType( - intercept_new_message(_upload_image_to_tos)(super().run_async), self + intercepted_run_async = intercept_new_message(_upload_image_to_tos)( + super().run_async ) + def _run_async_with_interceptor(self, *args, **kwargs): + # ADK 2.14.x's A2A executor calls inspect.signature() on the bound + # ``runner.run_async``. The interceptor wrapper has keyword-only + # parameters, which Python's inspect rejects for a bound method + # ("invalid method signature"). Expose a positional ``*args`` + # wrapper so the signature is introspectable while preserving the + # interceptor and the underlying keyword-only contract. + return intercepted_run_async(self, *args, **kwargs) + + self.run_async = MethodType(_run_async_with_interceptor, self) + async def run( self, messages: RunnerMessage,