Skip to content

armgit / ax

Public Imported from GitHub
0

Agent Executor (AX) is Google's open agentic orchestration runtime

Go

Remove A2A agent and bridge (#160)

JoyceLiu3438251c0415
diff --git a/.gitignore b/.gitignore
index 5c71552..55472ef 100644
--- a/.gitignore
+++ b/.gitignore
@@ -15,4 +15,3 @@ python/__pycache__
python/proto/__pycache__
/axepp
__pycache__/
-examples/a2a_agent/output/*
diff --git a/README.md b/README.md
index c3659ca..4c56c46 100644
--- a/README.md
+++ b/README.md
@@ -330,7 +330,6 @@ invoked over a protocol boundary.
- [Remote Agent](examples/remote_agent) implements AX's native `AgentService` directly.
- [ADK Agent (Python)](examples/adk_agent) runs a Google ADK agent as a remote agent.
-- [A2A Agent](examples/a2a_agent) connects agents that speak the [A2A protocol](https://github.com/a2aproject/A2A) through AX's A2A bridge.
Please note that AX is actively developing its resumable streaming and agent communication protocols; these interfaces will change before a stable release.
diff --git a/ax.yaml b/ax.yaml
index 8a34b93..814c32c 100644
--- a/ax.yaml
+++ b/ax.yaml
@@ -46,13 +46,3 @@ registry:
# address: "localhost:50051"
# metadata:
# version: "1.0"
-
- # - id: "coding-agent"
- # name: "Coding Agent (A2A)"
- # address: "http://localhost:41241"
- # protocol: "a2a"
- # auth:
- # type: "bearer"
- # credential_env: "CODING_AGENT_AUTH_TOKEN"
- # metadata:
- # version: "1.0"
diff --git a/examples/a2a_agent/README.md b/examples/a2a_agent/README.md
deleted file mode 100644
index 4d1b5ea..0000000
--- a/examples/a2a_agent/README.md
+++ /dev/null
@@ -1,117 +0,0 @@
-# A2A Agent
-
-`coding_agent.py` is a sample [A2A-protocol](https://github.com/a2aproject/A2A)
-agent built on Google ADK's `LlmAgent` (Gemini). It demonstrates how to
-register and use any A2A-compliant agent from AX.
-
-The agent writes Python code on request, saves the source directly under
-`examples/a2a_agent/output/`, and returns the saved file as a
-`text/x-python` attachment alongside its text reply.
-
-## What it demonstrates
-
-- **The full A2A integration surface AX supports**: AgentCard discovery,
- multi-transport (gRPC + JSON-RPC + HTTP+JSON REST), streaming and
- polling-fallback, FilePart artifacts.
-- **Inline tool calls inside a single A2A turn**: the agent calls
- `save_python_file(filename, code)`, the file is written immediately,
- and the same task transitions `SUBMITTED → WORKING → COMPLETED` without
- pausing.
-- **Optional dual-scheme auth** (`--auth`): the AgentCard advertises
- Bearer and API-key as alternatives; the server enforces either via
- HTTP middleware and a gRPC interceptor.
-
-## Prerequisites
-
-- Python 3.10+ and [`uv`](https://docs.astral.sh/uv/) (the script uses
- PEP-723 inline metadata to declare its dependencies)
-- Gemini credentials set in the environment:
- ```bash
- # Either a Gemini API key:
- export GOOGLE_API_KEY="<your-key>"
-
- # OR Vertex AI (requires gcloud application-default credentials):
- export GOOGLE_GENAI_USE_VERTEXAI=TRUE
- export GOOGLE_CLOUD_PROJECT="<your-project>"
- export GOOGLE_CLOUD_LOCATION="<your-region>"
- ```
-
-## Run the agent server
-
-```bash
-# From ax root directory
-uv run examples/a2a_agent/coding_agent.py
-```
-
-This serves:
-
-- HTTP / JSON-RPC / REST on `127.0.0.1:41241`
-- gRPC on `127.0.0.1:50051`
-- AgentCard at `http://127.0.0.1:41241/.well-known/agent-card.json`
-
-### Useful flags
-
-| Flag | Purpose |
-|---|---|
-| `--host`, `--port`, `--grpc-port` | Override default listen addresses. |
-| `--no-streaming` | Disable streaming in the AgentCard so clients exercise the polling fallback. |
-| `--auth` | Enable auth (advertises both Bearer and API key on the card; accepts either). Requires the env var named by `--auth-token-env`. |
-| `--auth-token-env` | Env var that holds the expected credential value. Default: `CODING_AGENT_AUTH_TOKEN`. |
-| `--api-key-header` | Header name advertised on the AgentCard's `APIKeySecurityScheme.name`. Default: `X-API-Key`. |
-| `--log-level` | `DEBUG`, `INFO`, `WARNING`, `ERROR`. Default: `INFO`. |
-
-### Where saved files land
-
-The agent writes every generated file to `examples/a2a_agent/output/`
-(created on first save). Filenames are constrained to bare names ending
-in `.py` — no path components, no `..`.
-
-## Register the agent in AX
-
-Add an entry under `registry.remote_agents` in your `ax.yaml`:
-
-```yaml
-registry:
- remote_agents:
- - id: "coding-agent"
- name: "Coding Agent"
- description: "Writes Python code and saves it under examples/a2a_agent/output/."
- address: "http://127.0.0.1:41241"
- protocol: "a2a"
-```
-
-To use the auth flow, also set the credential and add an `auth` block:
-
-```yaml
-registry:
- remote_agents:
- - id: "coding-agent"
- name: "Coding Agent"
- description: "Writes Python code and saves it under examples/a2a_agent/output/."
- address: "http://127.0.0.1:41241"
- protocol: "a2a"
- auth:
- type: "bearer" # or "api_key"
- credential_env: "CODING_AGENT_AUTH_TOKEN"
-```
-
-Make sure both AX's process and the agent process see the same value
-for `CODING_AGENT_AUTH_TOKEN`. The api_key header name is auto-discovered
-from the AgentCard, so you don't need to configure it on the AX side.
-
-## Try it
-
-Start the agent server in one terminal, then in another:
-
-```bash
-ax exec --input "Write me a Python flask hello-world server."
-```
-
-The planner delegates to `coding-agent`, which:
-
-1. Generates the code.
-2. Calls `save_python_file('flask_hello.py', '<code>')` inline. The file
- is written to `examples/a2a_agent/output/flask_hello.py`.
-3. Returns its text reply plus the saved source as a `text/x-python`
- FilePart attached to the same response artifact.
-
\ No newline at end of file
diff --git a/examples/a2a_agent/coding_agent.py b/examples/a2a_agent/coding_agent.py
deleted file mode 100644
index 9c14eaa..0000000
--- a/examples/a2a_agent/coding_agent.py
+++ /dev/null
@@ -1,615 +0,0 @@
-# Copyright 2026 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# /// script
-# requires-python = ">=3.10"
-# dependencies = [
-# "a2a-sdk>=1.0.0",
-# "google-adk>=1.31.0",
-# "google-genai>=1.0.0",
-# "fastapi>=0.115",
-# "uvicorn>=0.30",
-# "grpcio>=1.66",
-# ]
-# ///
-"""Sample Coding A2A agent backed by a Google ADK LlmAgent.
-
-Exposes an ADK Gemini agent over the A2A protocol on three transports
-(gRPC, JSON-RPC, HTTP+JSON REST).
-
-What it does:
- - Writes Python code on request.
- - Saves the code to a file under examples/a2a_agent/output/.
- - Returns the saved file as a FilePart (``text/x-python``) alongside the
- agent's text reply, so clients can surface the actual generated source.
- - Optionally enforces auth (``--auth``): when enabled, the AgentCard
- advertises both Bearer and API-key schemes as alternatives, and the
- server accepts either credential on every request.
-
-Auth (set one before launching):
- * Gemini API key: export GOOGLE_API_KEY=...
- * Vertex AI: export GOOGLE_GENAI_USE_VERTEXAI=TRUE
- export GOOGLE_CLOUD_PROJECT=<project>
- export GOOGLE_CLOUD_LOCATION=<region>
-
-Run:
- uv run examples/a2a_agent/coding_agent.py
- # Demo polling fallback by disabling streaming in the AgentCard:
- uv run examples/a2a_agent/coding_agent.py --no-streaming
-"""
-
-import argparse
-import asyncio
-import contextlib
-import logging
-import os
-import secrets
-
-from pathlib import Path
-
-import grpc
-import uvicorn
-
-from fastapi import FastAPI, Request
-from fastapi.responses import JSONResponse
-
-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.server.request_handlers import DefaultRequestHandler, GrpcHandler
-from a2a.server.request_handlers.response_helpers import agent_card_to_dict
-from a2a.server.routes import (
- create_jsonrpc_routes,
- create_rest_routes,
-)
-from a2a.server.tasks.inmemory_task_store import InMemoryTaskStore
-from a2a.server.tasks.task_updater import TaskUpdater
-from a2a.utils.constants import AGENT_CARD_WELL_KNOWN_PATH
-from a2a.types import (
- AgentCapabilities,
- AgentCard,
- AgentInterface,
- AgentSkill,
- APIKeySecurityScheme,
- HTTPAuthSecurityScheme,
- Part,
- SecurityRequirement,
- SecurityScheme,
- StringList,
- Task,
- TaskState,
- TaskStatus,
- a2a_pb2_grpc,
-)
-
-from google.adk.agents import Agent
-from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService
-from google.adk.events.event import Event as AdkEvent
-from google.adk.memory.in_memory_memory_service import InMemoryMemoryService
-from google.adk.runners import Runner
-from google.adk.sessions.in_memory_session_service import InMemorySessionService
-from google.genai import types as genai_types
-
-
-logger = logging.getLogger(__name__)
-
-
-# Generated files land here. Bare filenames only (no path components, no '..').
-_OUTPUT_DIR = Path(__file__).resolve().parent / "output"
-
-
-def _check_http_credential(
- request: Request,
- expected_token: str,
- api_key_header: str,
-) -> bool:
- """Validates a credential carried in HTTP headers (Bearer OR API key).
-
- Uses secrets.compare_digest for constant-time comparison so the auth
- decision does not leak the token via response-time differences.
- """
- v = request.headers.get("authorization", "")
- if v.startswith("Bearer ") and secrets.compare_digest(
- v[len("Bearer ") :], expected_token
- ):
- return True
- return secrets.compare_digest(
- request.headers.get(api_key_header, ""), expected_token
- )
-
-
-class _GrpcAuthInterceptor(grpc.aio.ServerInterceptor):
- """Rejects gRPC calls without a valid Bearer or API-key credential in metadata."""
-
- def __init__(self, expected_token: str, api_key_header: str) -> None:
- self._expected_token = expected_token
- # gRPC normalizes metadata keys to lowercase.
- self._api_key_header_lower = api_key_header.lower()
-
- async def intercept_service(self, continuation, handler_call_details):
- meta = dict(handler_call_details.invocation_metadata or [])
- v = meta.get("authorization", "")
- bearer_ok = v.startswith("Bearer ") and secrets.compare_digest(
- v[len("Bearer ") :], self._expected_token
- )
- apikey_ok = secrets.compare_digest(
- meta.get(self._api_key_header_lower, ""), self._expected_token
- )
- if bearer_ok or apikey_ok:
- return await continuation(handler_call_details)
-
- async def _abort(unused_request, context):
- await context.abort(
- grpc.StatusCode.UNAUTHENTICATED, "missing or invalid credential"
- )
-
- return grpc.unary_unary_rpc_method_handler(_abort)
-
-
-def save_python_file(filename: str, code: str) -> dict:
- """Save Python code to examples/a2a_agent/output/<filename>.
-
- Args:
- filename: Bare filename (no path components, no '..', must end in '.py').
- code: The Python source to write. Overwrites any existing file in the
- output directory.
-
- Returns:
- {"status": "saved", "path": "/abs/.../examples/a2a_agent/output/<filename>"}
- on success, or {"status": "error", "message": "..."} on validation failure.
- """
- name = (filename or "").strip()
- if not name or "/" in name or "\\" in name or ".." in name:
- return {"status": "error", "message": f"Invalid filename: {filename!r}"}
- if not name.endswith(".py"):
- return {"status": "error", "message": "Filename must end in .py"}
- target = (_OUTPUT_DIR / name).resolve()
- if target.parent != _OUTPUT_DIR:
- return {
- "status": "error",
- "message": "Filename must not contain path components",
- }
- try:
- _OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
- target.write_text(code, encoding="utf-8")
- except OSError as exc:
- return {"status": "error", "message": f"Failed to write file: {exc}"}
- logger.info("[save_python_file] Saved %d bytes to %s", len(code), target)
- return {"status": "saved", "path": str(target)}
-
-
-class AdkAgentExecutor(AgentExecutor):
- """A2A AgentExecutor that runs a Google ADK LlmAgent.
-
- Each A2A context is mapped 1:1 to an ADK session. Each user turn is a
- single straight-through invocation of ``Runner.run_async``: the agent
- streams text (forwarded as TASK_STATE_WORKING status updates) and may
- call ``save_python_file`` inline; any successfully saved files are
- attached to the final artifact as text/x-python FileParts.
- """
-
- USER_ID = "a2a_user"
-
- def __init__(self, runner: Runner) -> None:
- self._runner = runner
- self._running_tasks: set[str] = set()
-
- async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
- """Marks an in-flight task as cancelled."""
- task_id = context.task_id
- if task_id in self._running_tasks:
- self._running_tasks.remove(task_id)
-
- updater = TaskUpdater(
- event_queue=event_queue,
- task_id=task_id or "",
- context_id=context.context_id or "",
- )
- await updater.cancel()
-
- async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
- """Runs the ADK agent for the incoming A2A request."""
- user_message = context.message
- task_id = context.task_id
- context_id = context.context_id
-
- if not user_message or not task_id or not context_id:
- return
-
- self._running_tasks.add(task_id)
-
- updater = TaskUpdater(
- event_queue=event_queue, task_id=task_id, context_id=context_id
- )
-
- # Fresh turn: emit submitted/working events.
- await event_queue.enqueue_event(
- Task(
- id=task_id,
- context_id=context_id,
- status=TaskStatus(state=TaskState.TASK_STATE_SUBMITTED),
- history=[user_message],
- )
- )
- await updater.start_work(
- message=updater.new_agent_message(
- parts=[Part(text="Processing your question...")],
- )
- )
-
- new_message = genai_types.Content(
- role="user",
- parts=[genai_types.Part(text=context.get_user_input() or "")],
- )
-
- # Stream ADK events: forward text as WORKING updates and harvest the
- # paths of any files the save_python_file tool wrote.
- final_chunks: list[str] = []
- saved_paths: list[str] = []
- try:
- async for adk_event in self._runner.run_async(
- user_id=self.USER_ID,
- session_id=context_id,
- new_message=new_message,
- ):
- if task_id not in self._running_tasks:
- return
-
- saved_paths.extend(self._extract_saved_paths(adk_event))
-
- event_text = self._extract_text(adk_event)
- if not event_text:
- continue
-
- if adk_event.is_final_response():
- final_chunks.append(event_text)
- else:
- await updater.update_status(
- state=TaskState.TASK_STATE_WORKING,
- message=updater.new_agent_message(
- parts=[Part(text=event_text)]
- ),
- )
- except Exception as exc: # noqa: BLE001
- logger.exception("[AdkAgentExecutor] ADK run failed for task %s", task_id)
- await updater.failed(
- message=updater.new_agent_message(parts=[Part(text=str(exc))])
- )
- self._running_tasks.discard(task_id)
- return
-
- if task_id not in self._running_tasks:
- return
-
- # Build artifact: text reply + one FilePart per saved file (in call order).
- final_text = "".join(final_chunks).strip() or "(no response)"
- parts: list[Part] = [Part(text=final_text)]
- for raw_path in saved_paths:
- path = Path(raw_path)
- try:
- file_bytes = path.read_bytes()
- parts.append(
- Part(
- raw=file_bytes,
- media_type="text/x-python",
- filename=path.name,
- )
- )
- except OSError as exc:
- logger.warning(
- "[AdkAgentExecutor] Could not attach saved file %s: %s",
- path,
- exc,
- )
-
- await updater.add_artifact(parts=parts, name="response", last_chunk=True)
- await updater.complete()
- self._running_tasks.discard(task_id)
-
- # Helpers
-
- @staticmethod
- def _extract_text(event: AdkEvent) -> str:
- """Concatenates text parts on an ADK event, ignoring tool calls etc."""
- content = getattr(event, "content", None)
- if not content or not getattr(content, "parts", None):
- return ""
- return "".join(
- part.text for part in content.parts if getattr(part, "text", None)
- )
-
- @staticmethod
- def _extract_saved_paths(event: AdkEvent) -> list[str]:
- """Returns absolute paths from successful save_python_file responses on this event."""
- out: list[str] = []
- content = getattr(event, "content", None)
- if not content or not getattr(content, "parts", None):
- return out
- for part in content.parts:
- fr = getattr(part, "function_response", None)
- if not fr or fr.name != "save_python_file":
- continue
- resp = getattr(fr, "response", None) or {}
- if (
- isinstance(resp, dict)
- and resp.get("status") == "saved"
- and resp.get("path")
- ):
- out.append(resp["path"])
- return out
-
-
-async def serve(
- host: str = "127.0.0.1",
- port: int = 41241,
- grpc_port: int = 50051,
- streaming: bool = True,
- auth_enabled: bool = False,
- expected_token: str = "",
- api_key_header: str = "X-API-Key",
-) -> None:
- """Run the Coding Agent server with mounted JSON-RPC, HTTP+JSON and gRPC transports."""
- jsonrpc_url = f"http://{host}:{port}/a2a/jsonrpc"
- rest_url = f"http://{host}:{port}/a2a/rest"
- supported_interfaces = [
- AgentInterface(
- protocol_binding="GRPC", protocol_version="1.0", url=f"{host}:{grpc_port}"
- ),
- AgentInterface(
- protocol_binding="JSONRPC", protocol_version="1.0", url=jsonrpc_url
- ),
- AgentInterface(
- protocol_binding="HTTP+JSON", protocol_version="1.0", url=rest_url
- ),
- ]
-
- # Optional auth: when enabled, advertise BOTH Bearer and API key on the
- # AgentCard as alternative requirements (OR semantics: client may use
- # either). Enforcement is symmetric (HTTP middleware + gRPC interceptor
- # accept either credential).
- security_schemes: dict = {}
- security_requirements: list = []
- if auth_enabled:
- security_schemes = {
- "bearerAuth": SecurityScheme(
- http_auth_security_scheme=HTTPAuthSecurityScheme(
- scheme="bearer",
- description="Bearer token in Authorization header.",
- )
- ),
- "apiKey": SecurityScheme(
- api_key_security_scheme=APIKeySecurityScheme(
- location="header",
- name=api_key_header,
- description=f"API key sent in the {api_key_header} header.",
- )
- ),
- }
- # Two SecurityRequirement entries = OR (caller satisfies either alone),
- # not one entry with both keys (which would mean AND, requiring both).
- security_requirements = [
- SecurityRequirement(schemes={"bearerAuth": StringList(list=[])}),
- SecurityRequirement(schemes={"apiKey": StringList(list=[])}),
- ]
-
- agent_card = AgentCard(
- name="Coding Agent",
- description=(
- "A sample ADK agent that writes Python code and saves it under "
- "examples/a2a_agent/output/. Saved files are returned as FilePart "
- "attachments alongside the agent's text reply."
- ),
- version="1.0.0",
- capabilities=AgentCapabilities(streaming=streaming, push_notifications=False),
- default_input_modes=["text"],
- default_output_modes=["text", "file", "task-status"],
- skills=[
- AgentSkill(
- id="coding_agent",
- name="Coding Agent",
- description=(
- "Write Python scripts. Each is saved to "
- "examples/a2a_agent/output/<filename>.py and returned as a "
- "text/x-python attachment."
- ),
- tags=["coding", "python", "code-generation"],
- examples=[
- "write me a hello world script",
- "make a small fizzbuzz",
- "write a function that reverses a string",
- ],
- input_modes=["text"],
- output_modes=["text", "file", "task-status"],
- )
- ],
- supported_interfaces=supported_interfaces,
- security_schemes=security_schemes,
- security_requirements=security_requirements,
- )
-
- adk_agent = Agent(
- name="coding_agent",
- model="gemini-3.5-flash",
- instruction="""You are a Python coding assistant.
-
-When the user asks you to write Python code:
- 1. Reply with the full code in a fenced ```python block.
- 2. Call `save_python_file(filename, code)` to persist the code. Pick a short,
- descriptive filename ending in `.py` (e.g. 'fizzbuzz.py'). Filenames must be
- bare names with no path components - the server saves them under
- examples/a2a_agent/output/.
- 3. Briefly confirm the save in your reply, mentioning the filename.
-
-For non-coding messages, respond conversationally without calling any tools.""",
- tools=[save_python_file],
- )
- runner = Runner(
- app_name="coding_agent",
- agent=adk_agent,
- session_service=InMemorySessionService(),
- artifact_service=InMemoryArtifactService(),
- memory_service=InMemoryMemoryService(),
- # The A2A context_id is used directly as the ADK session_id; let the
- # runner create the session on first use instead of pre-provisioning.
- auto_create_session=True,
- )
-
- task_store = InMemoryTaskStore()
- request_handler = DefaultRequestHandler(
- agent_executor=AdkAgentExecutor(runner=runner),
- task_store=task_store,
- agent_card=agent_card,
- )
-
- app = FastAPI()
-
- if auth_enabled:
-
- @app.middleware("http")
- async def _enforce_auth(request: Request, call_next):
- # Keep agent-card discovery unauthenticated so clients can read the
- # card to learn how to authenticate.
- if request.url.path.startswith("/.well-known/"):
- return await call_next(request)
- if not _check_http_credential(request, expected_token, api_key_header):
- # RFC 7235 allows multiple challenges in one WWW-Authenticate value.
- return JSONResponse(
- {"error": "unauthorized"},
- status_code=401,
- headers={
- "WWW-Authenticate": f'Bearer, ApiKey realm="{api_key_header}"'
- },
- )
- return await call_next(request)
-
- @app.get(AGENT_CARD_WELL_KNOWN_PATH)
- async def _serve_agent_card():
- """Serve the AgentCard with a workaround for a Python <-> Go SDK shape
- mismatch: a2a-sdk Python emits SecurityRequirement.schemes[<name>] as
- the empty `{}` object (the StringList proto wrapper, with `list`
- elided), but a2a-go expects a bare JSON array `[]`. Walk the response
- and convert any dict value to its `list` contents (or [] when missing).
- Becomes a no-op once either SDK fixes the underlying serialization."""
- d = agent_card_to_dict(agent_card)
- for owner in (d, *d.get("skills", [])):
- for req in owner.get("securityRequirements", []) or []:
- for name, val in list(req.get("schemes", {}).items()):
- if isinstance(val, dict):
- req["schemes"][name] = val.get("list", [])
- return JSONResponse(d)
-
- for routes in (
- create_jsonrpc_routes(
- request_handler=request_handler,
- rpc_url="/a2a/jsonrpc",
- ),
- create_rest_routes(
- request_handler=request_handler,
- path_prefix="/a2a/rest",
- ),
- ):
- app.routes.extend(routes)
-
- grpc_interceptors: list = []
- if auth_enabled:
- grpc_interceptors.append(_GrpcAuthInterceptor(expected_token, api_key_header))
- grpc_server = grpc.aio.server(interceptors=grpc_interceptors)
- grpc_server.add_insecure_port(f"{host}:{grpc_port}")
- a2a_pb2_grpc.add_A2AServiceServicer_to_server(
- GrpcHandler(request_handler), grpc_server
- )
-
- uvicorn_server = uvicorn.Server(uvicorn.Config(app, host=host, port=port))
-
- logger.info(
- "Starting Coding Agent: HTTP http://%s:%s, gRPC %s:%s, "
- "AgentCard http://%s:%s/.well-known/agent-card.json",
- host,
- port,
- host,
- grpc_port,
- host,
- port,
- )
-
- await asyncio.gather(
- grpc_server.start(),
- uvicorn_server.serve(),
- )
-
-
-if __name__ == "__main__":
- parser = argparse.ArgumentParser(description="Coding A2A agent server")
- parser.add_argument("--host", default="127.0.0.1")
- parser.add_argument("--port", type=int, default=41241)
- parser.add_argument("--grpc-port", type=int, default=50051)
- parser.add_argument(
- "--no-streaming",
- action="store_true",
- help="Disable streaming in the AgentCard (clients fall back to non-streaming polling).",
- )
- parser.add_argument(
- "--log-level",
- default="INFO",
- choices=["DEBUG", "INFO", "WARNING", "ERROR"],
- help="Logging verbosity (default: INFO).",
- )
- parser.add_argument(
- "--auth",
- action="store_true",
- help=(
- "Enable auth: advertises both Bearer and API key on the AgentCard "
- "and accepts either credential on incoming requests."
- ),
- )
- parser.add_argument(
- "--auth-token-env",
- default="CODING_AGENT_AUTH_TOKEN",
- help=(
- "Env var that holds the expected token / API key value (used when "
- "--auth is set)."
- ),
- )
- parser.add_argument(
- "--api-key-header",
- default="X-API-Key",
- help=(
- "Header name advertised on the AgentCard's APIKeySecurityScheme.name. "
- "Clients (including ax) read the name from the card and use it on "
- "outgoing requests."
- ),
- )
- args = parser.parse_args()
- logging.basicConfig(level=getattr(logging, args.log_level))
-
- expected_token = ""
- if args.auth:
- expected_token = os.environ.get(args.auth_token_env, "")
- if not expected_token:
- parser.error(
- f"--auth requires environment variable {args.auth_token_env} to be set."
- )
-
- with contextlib.suppress(KeyboardInterrupt):
- asyncio.run(
- serve(
- host=args.host,
- port=args.port,
- grpc_port=args.grpc_port,
- streaming=not args.no_streaming,
- auth_enabled=args.auth,
- expected_token=expected_token,
- api_key_header=args.api_key_header,
- )
- )
diff --git a/go.mod b/go.mod
index e535dd6..03f135e 100644
--- a/go.mod
+++ b/go.mod
@@ -5,7 +5,6 @@ go 1.26.3
require (
charm.land/huh/v2 v2.0.3
charm.land/lipgloss/v2 v2.0.3
- github.com/a2aproject/a2a-go/v2 v2.2.0
github.com/agent-substrate/substrate v0.0.0-20260622205654-fe93d160a1df
github.com/envoyproxy/go-control-plane/envoy v1.37.0
github.com/google/uuid v1.6.0
@@ -67,7 +66,6 @@ require (
go.opentelemetry.io/otel/metric v1.43.0 // indirect
go.opentelemetry.io/otel/trace v1.43.0 // indirect
golang.org/x/crypto v0.51.0 // indirect
- golang.org/x/mod v0.35.0 // indirect
golang.org/x/net v0.55.0 // indirect
golang.org/x/sys v0.45.0 // indirect
golang.org/x/text v0.37.0 // indirect
diff --git a/go.sum b/go.sum
index 4198b68..cd73761 100644
--- a/go.sum
+++ b/go.sum
@@ -14,8 +14,6 @@ cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdB
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
-github.com/a2aproject/a2a-go/v2 v2.2.0 h1:eayiNXYpyTOLVhhQrGmIHlcy8GnOdnwaNdYQPvS84Ik=
-github.com/a2aproject/a2a-go/v2 v2.2.0/go.mod h1:htTxMwicNXXXEwwfjuB/Pd1g7UHDrswhSievncmTVcE=
github.com/agent-substrate/substrate v0.0.0-20260622205654-fe93d160a1df h1:Qq7cujws6kbtE/ykSlCBcZQWlpK/HQQZcmbUjJbWiUs=
github.com/agent-substrate/substrate v0.0.0-20260622205654-fe93d160a1df/go.mod h1:TgdtEUV6iaflJTwmS8ONiGsyyJD+5okPZj2H6mM8WlA=
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
diff --git a/internal/auth/auth.go b/internal/auth/auth.go
deleted file mode 100644
index 2133360..0000000
--- a/internal/auth/auth.go
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// Package auth holds shared, transport-agnostic data types and helpers
-// for describing how AX authenticates outbound calls to remote agents
-// and what extra headers to attach.
-package auth
-
-import (
- "errors"
- "fmt"
- "maps"
- "os"
-)
-
-// Auth describes how AX authenticates to a remote agent. Two well-known
-// schemes are supported, both sourcing their credential value from a
-// single environment variable named in CredentialEnv:
-// - "api_key": the credential is injected into a single HTTP header.
-// For A2A consumers, the header name is determined at runtime from
-// the agent's APIKeySecurityScheme on the AgentCard.
-// - "bearer": the credential is injected as
-// "Authorization: Bearer <value>".
-type Auth struct {
- Type string `yaml:"type"` // "api_key" or "bearer"
- CredentialEnv string `yaml:"credential_env"` // env var holding credential value
-}
-
-// Headers is a reusable bundle of HTTP-style header values, with both
-// literal and env-sourced sources.
-type Headers struct {
- Literal map[string]string `yaml:"literal,omitempty"` // literal values (NOT secret-safe)
- Env map[string]string `yaml:"env,omitempty"` // header name -> env var name (secret-safe)
-}
-
-// resolveAuthHeader translates an Auth into a single (header name, value)
-// tuple to inject.
-func resolveAuthHeader(a Auth, apiKeyHeader string) (name, value string, err error) {
- if a.CredentialEnv == "" {
- return "", "", errors.New(`auth: credential_env is required`)
- }
- value = os.Getenv(a.CredentialEnv)
- if value == "" {
- return "", "", fmt.Errorf(`auth: env var %q is empty or unset`, a.CredentialEnv)
- }
- switch a.Type {
- case "bearer":
- return "Authorization", "Bearer " + value, nil
- case "api_key":
- if apiKeyHeader == "" {
- return "", "", errors.New(`auth.api_key: no header name provided by the transport`)
- }
- return apiKeyHeader, value, nil
- default:
- return "", "", fmt.Errorf(`auth.type: unsupported %q (want "api_key" or "bearer")`, a.Type)
- }
-}
-
-// MergeAllHeaders flattens user-supplied Headers and the auth-resolved
-// header into a single map[string]string applied to every outgoing
-// request. Returns (nil, nil) when no headers are produced.
-func MergeAllHeaders(a Auth, h Headers, apiKeyHeader string) (map[string]string, error) {
- out := make(map[string]string, len(h.Literal)+len(h.Env)+1)
- maps.Copy(out, h.Literal)
- for k, envVar := range h.Env {
- v := os.Getenv(envVar)
- if v == "" {
- return nil, fmt.Errorf("headers.env[%q]: env var %q is empty or unset", k, envVar)
- }
- out[k] = v
- }
- if a.Type != "" {
- name, value, err := resolveAuthHeader(a, apiKeyHeader)
- if err != nil {
- return nil, err
- }
- if _, exists := out[name]; exists {
- return nil, fmt.Errorf(
- "auth resolves to header %q which is also set via headers; remove one source",
- name)
- }
- out[name] = value
- }
- if len(out) == 0 {
- return nil, nil
- }
- return out, nil
-}
diff --git a/internal/auth/auth_test.go b/internal/auth/auth_test.go
deleted file mode 100644
index 7a214de..0000000
--- a/internal/auth/auth_test.go
+++ /dev/null
@@ -1,173 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package auth
-
-import (
- "strings"
- "testing"
-)
-
-// ----- ResolveAuthHeader -----
-
-func TestResolveAuthHeader_BearerSuccess(t *testing.T) {
- t.Setenv("MY_TOKEN", "abc123")
- name, value, err := resolveAuthHeader(Auth{Type: "bearer", CredentialEnv: "MY_TOKEN"}, "")
- if err != nil {
- t.Fatalf("got err=%v, want nil", err)
- }
- if name != "Authorization" {
- t.Errorf("name=%q, want %q", name, "Authorization")
- }
- if value != "Bearer abc123" {
- t.Errorf("value=%q, want %q", value, "Bearer abc123")
- }
-}
-
-func TestResolveAuthHeader_MissingCredentialEnvFieldErrors(t *testing.T) {
- for _, scheme := range []string{"bearer", "api_key"} {
- t.Run(scheme, func(t *testing.T) {
- _, _, err := resolveAuthHeader(Auth{Type: scheme}, "")
- if err == nil {
- t.Fatal("got nil err, want non-nil for missing credential_env")
- }
- if !strings.Contains(err.Error(), "credential_env") {
- t.Errorf("err should mention credential_env field; got: %v", err)
- }
- })
- }
-}
-
-func TestResolveAuthHeader_EnvVarUnsetErrors(t *testing.T) {
- t.Setenv("MY_CRED", "")
- for _, scheme := range []string{"bearer", "api_key"} {
- t.Run(scheme, func(t *testing.T) {
- // apiKeyHeader is "", but the env-empty check fires before
- // the api_key path even consults it.
- _, _, err := resolveAuthHeader(Auth{Type: scheme, CredentialEnv: "MY_CRED"}, "")
- if err == nil {
- t.Fatal("got nil err, want non-nil for unset env")
- }
- if !strings.Contains(err.Error(), "MY_CRED") {
- t.Errorf("err should mention env var; got: %v", err)
- }
- })
- }
-}
-
-func TestResolveAuthHeader_UnknownTypeErrors(t *testing.T) {
- t.Setenv("MY_CRED", "value")
- _, _, err := resolveAuthHeader(Auth{Type: "oauth2", CredentialEnv: "MY_CRED"}, "")
- if err == nil {
- t.Fatal("got nil err, want non-nil for unknown type")
- }
- if !strings.Contains(err.Error(), "oauth2") {
- t.Errorf("err should mention the unknown type; got: %v", err)
- }
-}
-
-func TestResolveAuthHeader_ApiKeyEmptyHeaderErrors(t *testing.T) {
- t.Setenv("MY_KEY", "k-secret")
- _, _, err := resolveAuthHeader(Auth{Type: "api_key", CredentialEnv: "MY_KEY"}, "")
- if err == nil {
- t.Fatal("got nil err, want non-nil for empty apiKeyHeader")
- }
- if !strings.Contains(err.Error(), "no header name") {
- t.Errorf("err should mention missing header name; got: %v", err)
- }
-}
-
-// ----- MergeAllHeaders -----
-
-func TestMergeAllHeaders_LiteralOnly(t *testing.T) {
- got, err := MergeAllHeaders(Auth{}, Headers{
- Literal: map[string]string{"X-Org": "acme", "X-Project": "demo"},
- }, "")
- if err != nil {
- t.Fatalf("got err=%v, want nil", err)
- }
- if got["X-Org"] != "acme" || got["X-Project"] != "demo" || len(got) != 2 {
- t.Errorf("got=%v, want X-Org=acme + X-Project=demo (2 entries)", got)
- }
-}
-
-func TestMergeAllHeaders_EnvResolvesValues(t *testing.T) {
- t.Setenv("MY_TOK", "secret123")
- got, err := MergeAllHeaders(Auth{}, Headers{
- Env: map[string]string{"X-Token": "MY_TOK"},
- }, "")
- if err != nil {
- t.Fatalf("got err=%v, want nil", err)
- }
- if got["X-Token"] != "secret123" {
- t.Errorf("X-Token=%q, want %q", got["X-Token"], "secret123")
- }
-}
-
-func TestMergeAllHeaders_EnvOverridesLiteralOnCollision(t *testing.T) {
- t.Setenv("OVERRIDE_VAL", "from-env")
- got, err := MergeAllHeaders(Auth{}, Headers{
- Literal: map[string]string{"X-Header": "from-yaml"},
- Env: map[string]string{"X-Header": "OVERRIDE_VAL"},
- }, "")
- if err != nil {
- t.Fatalf("got err=%v, want nil", err)
- }
- if got["X-Header"] != "from-env" {
- t.Errorf("collision: got %q, want %q (Env must override Literal)", got["X-Header"], "from-env")
- }
-}
-
-func TestMergeAllHeaders_EnvMissingErrors(t *testing.T) {
- t.Setenv("EMPTY_VAR", "")
- _, err := MergeAllHeaders(Auth{}, Headers{
- Env: map[string]string{"X-Missing": "EMPTY_VAR"},
- }, "")
- if err == nil {
- t.Fatal("got nil err, want non-nil for unset env")
- }
- if !strings.Contains(err.Error(), "EMPTY_VAR") || !strings.Contains(err.Error(), "X-Missing") {
- t.Errorf("err should mention env var and header name; got: %v", err)
- }
-}
-
-func TestMergeAllHeaders_AuthAndUserMerge(t *testing.T) {
- t.Setenv("MY_TOKEN", "abc123")
- got, err := MergeAllHeaders(
- Auth{Type: "bearer", CredentialEnv: "MY_TOKEN"},
- Headers{Literal: map[string]string{"X-Org": "acme"}},
- "",
- )
- if err != nil {
- t.Fatalf("got err=%v, want nil", err)
- }
- if got["Authorization"] != "Bearer abc123" || got["X-Org"] != "acme" || len(got) != 2 {
- t.Errorf("got=%v, want Authorization+X-Org (2 entries)", got)
- }
-}
-
-func TestMergeAllHeaders_AuthCollidesWithUserHeaderErrors(t *testing.T) {
- t.Setenv("MY_TOKEN", "abc123")
- _, err := MergeAllHeaders(
- Auth{Type: "bearer", CredentialEnv: "MY_TOKEN"},
- Headers{Literal: map[string]string{"Authorization": "Bearer manual"}},
- "",
- )
- if err == nil {
- t.Fatal("got nil err, want non-nil for header collision")
- }
- if !strings.Contains(err.Error(), "Authorization") {
- t.Errorf("err should mention the colliding header name; got: %v", err)
- }
-}
diff --git a/internal/config/config.go b/internal/config/config.go
index 7491cff..341f487 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -21,7 +21,6 @@ import (
"time"
"github.com/google/ax/internal/agent"
- "github.com/google/ax/internal/auth"
"gopkg.in/yaml.v3"
)
@@ -101,21 +100,9 @@ type RemoteAgentConfig struct {
Name string `yaml:"name"` // Human-readable name
Description string `yaml:"description"` // Description
Address string `yaml:"address"` // Remote agent address
- Protocol string `yaml:"protocol,omitempty"` // "axp" (default) or "a2a"
- Auth auth.Auth `yaml:"auth,omitempty"` // Optional auth (cross-protocol; today honored only for a2a)
- Headers auth.Headers `yaml:"headers,omitempty"` // Optional headers (cross-protocol; today honored only for a2a)
- A2A A2AConfig `yaml:"a2a,omitempty"` // A2A-protocol-specific options
Metadata map[string]string `yaml:"metadata,omitempty"` // Optional metadata
}
-// A2AConfig holds A2A-protocol-specific options. Honored only when
-// RemoteAgentConfig.Protocol is "a2a".
-type A2AConfig struct {
- Stateless bool `yaml:"stateless,omitempty"` // Send full history each turn (default: stateful)
-}
-
-
-
type LocalAgentConfig struct {
ID string `yaml:"id"` // Unique agent identifier
Name string `yaml:"name"` // Human-readable name
diff --git a/internal/controller/registry.go b/internal/controller/registry.go
index e1fae30..5c1081c 100644
--- a/internal/controller/registry.go
+++ b/internal/controller/registry.go
@@ -17,13 +17,10 @@ package controller
import (
"context"
"fmt"
- "strings"
"sync"
"github.com/google/ax/internal/agent"
"github.com/google/ax/internal/config"
- "github.com/google/ax/internal/experimental/a2abridge"
- expagent "github.com/google/ax/internal/experimental/agent"
)
// Registry manages a collection of local and remote agents.
@@ -73,11 +70,8 @@ func (r *Registry) RegisterLocal(cfg config.LocalAgentConfig) error {
return nil
}
-// RegisterRemote registers a remote agent by creating a remote agent client.
-// The protocol field determines what kind of remote agent to register
-// (matched case-insensitively):
-// - "axp" (default): AX's proto.AgentService.
-// - "a2a": A2A protocol.
+// RegisterRemote registers a remote agent by creating a remote agent client
+// for AX's proto.AgentService.
func (r *Registry) RegisterRemote(ctx context.Context, cfg config.RemoteAgentConfig) error {
r.mu.Lock()
defer r.mu.Unlock()
@@ -89,17 +83,6 @@ func (r *Registry) RegisterRemote(ctx context.Context, cfg config.RemoteAgentCon
return fmt.Errorf("agent %s already registered", cfg.ID)
}
- switch strings.ToLower(cfg.Protocol) {
- case "", "axp":
- return r.registerRemote(cfg)
- case "a2a":
- return r.registerA2A(ctx, cfg)
- default:
- return fmt.Errorf("remote agent %s: invalid protocol %q (want \"axp\" or \"a2a\")", cfg.ID, cfg.Protocol)
- }
-}
-
-func (r *Registry) registerRemote(cfg config.RemoteAgentConfig) error {
remoteAgent, err := agent.NewRemoteAgent(agent.RemoteAgentConfig{
Address: cfg.Address,
Reconnect: true,
@@ -118,31 +101,6 @@ func (r *Registry) registerRemote(cfg config.RemoteAgentConfig) error {
return nil
}
-// Creates an A2A-protocol agent client. The agent's AgentCard is resolved at
-// registration time and used to populate the agent's information.
-func (r *Registry) registerA2A(ctx context.Context, cfg config.RemoteAgentConfig) error {
- a2aAgent, err := expagent.NewA2AAgent(ctx, expagent.A2AAgentConfig{
- ID: cfg.ID,
- Address: cfg.Address,
- Auth: cfg.Auth,
- Headers: cfg.Headers,
- Stateless: cfg.A2A.Stateless,
- })
- if err != nil {
- return fmt.Errorf("failed to create a2a agent: %w", err)
- }
- name, description := a2abridge.AgentMetadataFromCard(a2aAgent.Card(), cfg.Name, cfg.Description)
- r.agents[cfg.ID] = a2aAgent
- r.agentInfo[cfg.ID] = &agent.AgentInfo{
- ID: cfg.ID,
- Name: name,
- Description: description,
- Metadata: cfg.Metadata,
- }
- return nil
-}
-
-
// Get retrieves an agent by ID.
func (r *Registry) Get(id string) (agent.Agent, error) {
r.mu.RLock()
diff --git a/internal/experimental/a2abridge/a2a_converter.go b/internal/experimental/a2abridge/a2a_converter.go
deleted file mode 100644
index 393f12c..0000000
--- a/internal/experimental/a2abridge/a2a_converter.go
+++ /dev/null
@@ -1,368 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package a2abridge
-
-import (
- "encoding/json"
- "fmt"
- "strings"
-
- "github.com/a2aproject/a2a-go/v2/a2a"
- "github.com/google/ax/proto"
-)
-
-// ----- AX -> A2A direction -----
-
-// MessagesToA2AParts converts AX message history into a flat list of A2A
-// Parts. Internal-only AX content are skipped.
-func MessagesToA2AParts(msgs []*proto.Message) []*a2a.Part {
- out := make([]*a2a.Part, 0, len(msgs))
- for _, msg := range msgs {
- if msg == nil || msg.Content == nil {
- continue
- }
- if isStateMarkerMessage(msg) {
- continue
- }
- if p := contentToA2APart(msg.Content); p != nil {
- out = append(out, p)
- }
- }
- return out
-}
-
-// LatestUserInputParts returns the most recent user-role input as a single
-// A2A Part - i.e. what the AX user just typed. The walk goes backward
-// from the end of msgs and returns as soon as it finds a user-role
-// message with usable content (text/file/data).
-func LatestUserInputParts(msgs []*proto.Message) []*a2a.Part {
- for i := len(msgs) - 1; i >= 0; i-- {
- msg := msgs[i]
- if msg == nil || msg.Role != "user" || msg.Content == nil {
- continue
- }
- if isStateMarkerMessage(msg) {
- continue
- }
- switch msg.Content.Type.(type) {
- case *proto.Content_Confirmation,
- *proto.Content_ToolCall,
- *proto.Content_ToolResult,
- *proto.Content_Thought:
- continue
- }
- if p := contentToA2APart(msg.Content); p != nil {
- return []*a2a.Part{p}
- }
- }
- return nil
-}
-
-// contentToA2APart converts a single AX Content variant into an A2A Part.
-func contentToA2APart(content *proto.Content) *a2a.Part {
- if content == nil {
- return nil
- }
- switch t := content.Type.(type) {
- case *proto.Content_Text:
- if t.Text == nil || t.Text.Text == "" {
- return nil
- }
- return a2a.NewTextPart(t.Text.Text)
- case *proto.Content_Image:
- return imageContentToPart(t.Image)
- case *proto.Content_Audio:
- return audioContentToPart(t.Audio)
- case *proto.Content_Video:
- return videoContentToPart(t.Video)
- case *proto.Content_Document:
- return documentContentToPart(t.Document)
- }
- return nil
-}
-
-// rawOrURLPart builds an A2A Part from inline bytes (Raw variant) or a URI
-// (URL variant), whichever is non-empty. Returns nil if both are empty.
-func rawOrURLPart(data []byte, uri, mediaType string) *a2a.Part {
- if len(data) > 0 {
- return &a2a.Part{Content: a2a.Raw(data), MediaType: mediaType}
- }
- if uri != "" {
- return &a2a.Part{Content: a2a.URL(uri), MediaType: mediaType}
- }
- return nil
-}
-
-// mediaTypeOr returns table[enum] if present, otherwise fallback. Used by
-// the typed-content converters to resolve the wire-mime string with a
-// type-specific generic ("image/*", "audio/*", etc.) when the AX enum
-// value isn't in our mapping table.
-func mediaTypeOr[E comparable](table map[E]string, enum E, fallback string) string {
- if s := table[enum]; s != "" {
- return s
- }
- return fallback
-}
-
-func imageContentToPart(c *proto.ImageContent) *a2a.Part {
- if c == nil {
- return nil
- }
- return rawOrURLPart(c.GetData(), c.GetUri(), mediaTypeOr(imageMimeToString, c.MimeType, "image/*"))
-}
-
-func audioContentToPart(c *proto.AudioContent) *a2a.Part {
- if c == nil {
- return nil
- }
- return rawOrURLPart(c.GetData(), c.GetUri(), mediaTypeOr(audioMimeToString, c.MimeType, "audio/*"))
-}
-
-func videoContentToPart(c *proto.VideoContent) *a2a.Part {
- if c == nil {
- return nil
- }
- return rawOrURLPart(c.GetData(), c.GetUri(), mediaTypeOr(videoMimeToString, c.MimeType, "video/*"))
-}
-
-func documentContentToPart(c *proto.DocumentContent) *a2a.Part {
- if c == nil {
- return nil
- }
- // DocumentContent with TYPE_JSON is the round-trip representation of
- // an A2A DataPart - convert it back. Falls through to raw bytes if
- // the JSON is malformed.
- if c.MimeType == proto.DocumentContent_TYPE_JSON {
- if data := c.GetData(); len(data) > 0 {
- var v any
- if err := json.Unmarshal(data, &v); err == nil {
- return &a2a.Part{
- Content: a2a.Data{Value: v},
- MediaType: "application/json",
- }
- }
- }
- }
- return rawOrURLPart(c.GetData(), c.GetUri(), mediaTypeOr(documentMimeToString, c.MimeType, "application/octet-stream"))
-}
-
-// ----- A2A -> AX direction -----
-
-// a2aPartsToMessages converts a list of A2A Parts into AX Messages. Each
-// Part becomes one Message with the supplied role.
-func a2aPartsToMessages(parts []*a2a.Part, role string) []*proto.Message {
- out := make([]*proto.Message, 0, len(parts))
- for _, part := range parts {
- if part == nil {
- continue
- }
- content := a2aPartToContent(part)
- if content == nil {
- continue
- }
- out = append(out, &proto.Message{Role: role, Content: content})
- }
- return out
-}
-
-// a2aPartToContent classifies an A2A Part by its Content variant and
-// MediaType and produces the appropriate AX Content. Returns nil if the part
-// is empty or unrecognised.
-func a2aPartToContent(part *a2a.Part) *proto.Content {
- if part == nil {
- return nil
- }
- switch c := part.Content.(type) {
- case a2a.Text:
- text := string(c)
- if text == "" {
- return nil
- }
- return &proto.Content{
- Type: &proto.Content_Text{
- Text: &proto.TextContent{Text: text},
- },
- }
- case a2a.Raw:
- return classifyByMediaType([]byte(c), "", part.MediaType)
- case a2a.URL:
- return classifyByMediaType(nil, string(c), part.MediaType)
- case a2a.Data:
- return dataValueToContent(c.Value)
- }
- return nil
-}
-
-// classifyByMediaType builds an AX Content from inline bytes (data) OR a
-// URL reference (uri); pass exactly one. The wire MIME string selects
-// the typed Content variant (Image/Audio/Video/Document); unrecognised
-// MIME types land in DocumentContent with TYPE_UNSPECIFIED.
-func classifyByMediaType(data []byte, uri, mediaType string) *proto.Content {
- if e, ok := imageMimeFromString[mediaType]; ok {
- return newImageContent(e, data, uri)
- }
- if e, ok := audioMimeFromString[mediaType]; ok {
- return newAudioContent(e, data, uri)
- }
- if e, ok := videoMimeFromString[mediaType]; ok {
- return newVideoContent(e, data, uri)
- }
- if e, ok := documentMimeFromString[mediaType]; ok {
- return newDocumentContent(e, data, uri)
- }
- return newDocumentContent(proto.DocumentContent_TYPE_UNSPECIFIED, data, uri)
-}
-
-// newImageContent constructs an Image-typed proto.Content from inline
-// bytes or a URI (whichever is non-empty); pass exactly one.
-func newImageContent(mime proto.ImageContent_MimeType, data []byte, uri string) *proto.Content {
- img := &proto.ImageContent{MimeType: mime}
- if len(data) > 0 {
- img.DataOrUri = &proto.ImageContent_Data{Data: data}
- } else if uri != "" {
- img.DataOrUri = &proto.ImageContent_Uri{Uri: uri}
- }
- return &proto.Content{Type: &proto.Content_Image{Image: img}}
-}
-
-// newAudioContent constructs an Audio-typed proto.Content from inline
-// bytes or a URI (whichever is non-empty); pass exactly one.
-func newAudioContent(mime proto.AudioContent_MimeType, data []byte, uri string) *proto.Content {
- aud := &proto.AudioContent{MimeType: mime}
- if len(data) > 0 {
- aud.DataOrUri = &proto.AudioContent_Data{Data: data}
- } else if uri != "" {
- aud.DataOrUri = &proto.AudioContent_Uri{Uri: uri}
- }
- return &proto.Content{Type: &proto.Content_Audio{Audio: aud}}
-}
-
-// newVideoContent constructs a Video-typed proto.Content from inline
-// bytes or a URI (whichever is non-empty); pass exactly one.
-func newVideoContent(mime proto.VideoContent_MimeType, data []byte, uri string) *proto.Content {
- vid := &proto.VideoContent{MimeType: mime}
- if len(data) > 0 {
- vid.DataOrUri = &proto.VideoContent_Data{Data: data}
- } else if uri != "" {
- vid.DataOrUri = &proto.VideoContent_Uri{Uri: uri}
- }
- return &proto.Content{Type: &proto.Content_Video{Video: vid}}
-}
-
-// newDocumentContent constructs a Document-typed proto.Content from
-// inline bytes or a URI (whichever is non-empty); pass exactly one.
-func newDocumentContent(mime proto.DocumentContent_MimeType, data []byte, uri string) *proto.Content {
- doc := &proto.DocumentContent{MimeType: mime}
- if len(data) > 0 {
- doc.DataOrUri = &proto.DocumentContent_Data{Data: data}
- } else if uri != "" {
- doc.DataOrUri = &proto.DocumentContent_Uri{Uri: uri}
- }
- return &proto.Content{Type: &proto.Content_Document{Document: doc}}
-}
-
-// dataValueToContent serialises arbitrary structured data into JSON
-// bytes stored as a DocumentContent with mime_type=TYPE_JSON.
-func dataValueToContent(value any) *proto.Content {
- bytes, err := json.Marshal(value)
- if err != nil {
- // Fall back to a string representation so we never lose the data
- // entirely.
- bytes = fmt.Appendf(nil, "%v", value)
- }
- return &proto.Content{Type: &proto.Content_Document{
- Document: &proto.DocumentContent{
- MimeType: proto.DocumentContent_TYPE_JSON,
- DataOrUri: &proto.DocumentContent_Data{Data: bytes},
- },
- }}
-}
-
-// a2aArtifactToMessages converts an A2A Artifact into a list of AX Messages
-// by flattening its Parts.
-func a2aArtifactToMessages(artifact *a2a.Artifact, role string) []*proto.Message {
- if artifact == nil {
- return nil
- }
- out := make([]*proto.Message, 0, len(artifact.Parts))
- for _, part := range artifact.Parts {
- content := a2aPartToContent(part)
- if content == nil {
- continue
- }
- out = append(out, &proto.Message{Role: role, Content: content})
- }
- return out
-}
-
-// a2aRoleToRole maps A2A's MessageRole back to AX's role string.
-func a2aRoleToRole(role a2a.MessageRole) string {
- if s, ok := a2aRoleToString[role]; ok {
- return s
- }
- return "unspecified"
-}
-
-// ----- card-derived metadata -----
-
-// AgentMetadataFromCard composes the AX-side (Name, Description) for a
-// registered A2A agent from its AgentCard plus optional config-supplied
-// overrides.
-func AgentMetadataFromCard(card *a2a.AgentCard, cfgName, cfgDescription string) (name, description string) {
- name = cfgName
- description = cfgDescription
- if card != nil {
- if name == "" {
- name = card.Name
- }
- if description == "" {
- description = card.Description
- }
- description = enrichDescriptionWithSkills(description, card)
- }
- return name, description
-}
-
-// enrichDescriptionWithSkills appends a structured summary of the agent's
-// Skills (name, description, examples, tags) to the base description.
-func enrichDescriptionWithSkills(base string, card *a2a.AgentCard) string {
- if card == nil || len(card.Skills) == 0 {
- return base
- }
- var b strings.Builder
- b.WriteString(strings.TrimRight(base, " \n"))
- if base != "" && !strings.HasSuffix(strings.TrimRight(base, " \n"), ".") {
- b.WriteString(".")
- }
- b.WriteString("\n\nSkills:\n")
- for _, s := range card.Skills {
- fmt.Fprintf(&b, "- %s: %s", s.Name, s.Description)
- if len(s.Tags) > 0 {
- fmt.Fprintf(&b, " (tags: %s)", strings.Join(s.Tags, ", "))
- }
- b.WriteString("\n")
- if len(s.Examples) > 0 {
- b.WriteString(" Examples: ")
- for i, ex := range s.Examples {
- if i > 0 {
- b.WriteString("; ")
- }
- fmt.Fprintf(&b, "%q", ex)
- }
- b.WriteString("\n")
- }
- }
- return b.String()
-}
diff --git a/internal/experimental/a2abridge/a2a_converter_test.go b/internal/experimental/a2abridge/a2a_converter_test.go
deleted file mode 100644
index cdce672..0000000
--- a/internal/experimental/a2abridge/a2a_converter_test.go
+++ /dev/null
@@ -1,423 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package a2abridge
-
-import (
- "strings"
- "testing"
-
- "github.com/a2aproject/a2a-go/v2/a2a"
- "github.com/google/ax/proto"
-)
-
-// userTextMsg returns a user-role message wrapping the given text.
-func userTextMsg(text string) *proto.Message {
- return &proto.Message{
- Role: "user",
- Content: &proto.Content{
- Type: &proto.Content_Text{Text: &proto.TextContent{Text: text}},
- },
- }
-}
-
-// modelTextMsg returns a model-role message wrapping the given text.
-func modelTextMsg(text string) *proto.Message {
- return &proto.Message{
- Role: "model",
- Content: &proto.Content{
- Type: &proto.Content_Text{Text: &proto.TextContent{Text: text}},
- },
- }
-}
-
-// modelDocument returns a model-role message wrapping a DocumentContent
-// for the supplied MIME string.
-func modelDocument(data []byte, mime, name string) *proto.Message {
- _ = name
- e := documentMimeFromString[mime] // zero value = TYPE_UNSPECIFIED
- return &proto.Message{
- Role: "model",
- Content: &proto.Content{
- Type: &proto.Content_Document{
- Document: &proto.DocumentContent{
- MimeType: e,
- DataOrUri: &proto.DocumentContent_Data{Data: data},
- },
- },
- },
- }
-}
-
-// userConfirmation returns a user-role ConfirmationContent reply.
-func userConfirmation(id string, approved bool) *proto.Message {
- conf := &proto.ConfirmationContent{Id: id}
- if approved {
- conf.Decision = &proto.ConfirmationContent_Approval{
- Approval: &proto.ApprovalDecision{Approved: true},
- }
- } else {
- conf.Decision = &proto.ConfirmationContent_Decline{
- Decline: &proto.DeclineDecision{Declined: true},
- }
- }
- return &proto.Message{
- Role: "user",
- Content: &proto.Content{Type: &proto.Content_Confirmation{Confirmation: conf}},
- }
-}
-
-// modelConfirmation returns a model-role ConfirmationContent question.
-func modelConfirmation(id, question string) *proto.Message {
- return &proto.Message{
- Role: "model",
- Content: &proto.Content{
- Type: &proto.Content_Confirmation{
- Confirmation: &proto.ConfirmationContent{Id: id, Question: question},
- },
- },
- }
-}
-
-// modelToolCall returns a model-role ToolCall message.
-func modelToolCall(id, name string) *proto.Message {
- return &proto.Message{
- Role: "model",
- Content: &proto.Content{
- Type: &proto.Content_ToolCall{
- ToolCall: &proto.ToolCallContent{
- Id: id,
- Type: &proto.ToolCallContent_FunctionCall{
- FunctionCall: &proto.FunctionCallContent{Name: name},
- },
- },
- },
- },
- }
-}
-
-// stateMarker returns the kind of internal_only marker the bridge
-// persists during HITL. Delegates to buildStateMarker so a marshalA2AState
-// failure aborts the test rather than silently producing nil.
-func stateMarker(t *testing.T, conversationID, taskID string) *proto.Message {
- t.Helper()
- return buildStateMarker(t, conversationID, taskID, nil)
-}
-
-// partTexts extracts the Text() value of every Text-typed Part in order,
-// for easy comparison in test assertions.
-func partTexts(parts []*a2a.Part) []string {
- out := make([]string, 0, len(parts))
- for _, p := range parts {
- if p == nil {
- continue
- }
- if t := p.Text(); t != "" {
- out = append(out, t)
- }
- }
- return out
-}
-
-func TestLatestUserInputParts_SingleUserMessage(t *testing.T) {
- got := LatestUserInputParts([]*proto.Message{
- userTextMsg("hello world"),
- })
- want := []string{"hello world"}
- gotTexts := partTexts(got)
- if !equalStrings(gotTexts, want) {
- t.Fatalf("LatestUserInputParts: got %v, want %v", gotTexts, want)
- }
-}
-
-func TestLatestUserInputParts_StopsAtPriorModelTurn(t *testing.T) {
- // Only the trailing user-role messages after the last model turn
- // should be returned.
- got := LatestUserInputParts([]*proto.Message{
- userTextMsg("write me a flask server"), // exec 1 user input
- modelTextMsg("here is your flask server"), // exec 1 model reply
- userTextMsg("change port to 5050"), // exec 2 user input
- })
- want := []string{"change port to 5050"}
- gotTexts := partTexts(got)
- if !equalStrings(gotTexts, want) {
- t.Fatalf("LatestUserInputParts: got %v, want %v", gotTexts, want)
- }
-}
-
-func TestLatestUserInputParts_StopsAtPriorModelDocument(t *testing.T) {
- // A DocumentContent emitted by the bridge (file artifact) is a
- // model-role content turn. The walk must stop there so we don't
- // re-send the prior text user message.
- got := LatestUserInputParts([]*proto.Message{
- userTextMsg("write me a flask server"),
- modelDocument([]byte("print('hi')"), "text/x-python", "hi.py"),
- userTextMsg("change port to 5050"),
- })
- want := []string{"change port to 5050"}
- gotTexts := partTexts(got)
- if !equalStrings(gotTexts, want) {
- t.Fatalf("LatestUserInputParts: got %v, want %v", gotTexts, want)
- }
-}
-
-func TestLatestUserInputParts_SkipsStateMarkers(t *testing.T) {
- // State markers should be transparent - they don't break the
- // contiguous-user run, but they don't contribute parts either.
- got := LatestUserInputParts([]*proto.Message{
- modelTextMsg("prior agent reply"),
- stateMarker(t, "conv-1", ""),
- userTextMsg("new user message"),
- })
- want := []string{"new user message"}
- gotTexts := partTexts(got)
- if !equalStrings(gotTexts, want) {
- t.Fatalf("LatestUserInputParts: got %v, want %v", gotTexts, want)
- }
-}
-
-func TestLatestUserInputParts_SkipsAXInternalContent(t *testing.T) {
- // Confirmation, ToolCall, ToolResult, Thought are AX-internal and
- // should not break the walk or contribute parts.
- got := LatestUserInputParts([]*proto.Message{
- modelTextMsg("prior turn"),
- modelConfirmation("task-x", "ok?"),
- userConfirmation("task-x", true),
- modelToolCall("call-1", "some-tool"),
- userTextMsg("the actual new request"),
- })
- want := []string{"the actual new request"}
- gotTexts := partTexts(got)
- if !equalStrings(gotTexts, want) {
- t.Fatalf("LatestUserInputParts: got %v, want %v", gotTexts, want)
- }
-}
-
-func TestLatestUserInputParts_MultipleConsecutiveUserMessages(t *testing.T) {
- // AX is one-message-per-exec in practice, so the helper returns
- // only the most recent user-typed message. If multiple user
- // messages somehow appear in a row, only the last one is returned.
- got := LatestUserInputParts([]*proto.Message{
- modelTextMsg("prior agent reply"),
- userTextMsg("first follow-up"),
- userTextMsg("second follow-up"),
- })
- want := []string{"second follow-up"}
- gotTexts := partTexts(got)
- if !equalStrings(gotTexts, want) {
- t.Fatalf("LatestUserInputParts: got %v, want %v", gotTexts, want)
- }
-}
-
-func TestLatestUserInputParts_SkipsPlannerOutputAfterUserInput(t *testing.T) {
- // AX's planner emits its own text reasoning and a ToolCall AFTER the
- // user's input but BEFORE the bridge is invoked. The helper must walk
- // past those model-role messages and still find the user's actual input
- // from earlier in the history.
- got := LatestUserInputParts([]*proto.Message{
- userTextMsg("write me a flask server"),
- modelTextMsg("here's a flask server"),
- modelDocument([]byte("..."), "text/x-python", "flask_app.py"),
- userTextMsg("change port to 5050"), // the actual new input
- modelTextMsg("I'll delegate to coding-agent"), // planner reasoning
- modelToolCall("call-1", "coding-agent"), // planner tool call
- })
- want := []string{"change port to 5050"}
- gotTexts := partTexts(got)
- if !equalStrings(gotTexts, want) {
- t.Fatalf("LatestUserInputParts (planner-after-user): got %v, want %v", gotTexts, want)
- }
-}
-
-func TestLatestUserInputParts_NoUserMessage(t *testing.T) {
- // History with only model content yields no parts.
- got := LatestUserInputParts([]*proto.Message{
- modelTextMsg("just an agent reply"),
- })
- if len(got) != 0 {
- t.Fatalf("LatestUserInputParts: got %d parts, want 0", len(got))
- }
-}
-
-func TestLatestUserInputParts_EmptyHistory(t *testing.T) {
- got := LatestUserInputParts(nil)
- if len(got) != 0 {
- t.Fatalf("LatestUserInputParts(nil): got %d parts, want 0", len(got))
- }
- got = LatestUserInputParts([]*proto.Message{})
- if len(got) != 0 {
- t.Fatalf("LatestUserInputParts(empty): got %d parts, want 0", len(got))
- }
-}
-
-func TestLatestUserInputParts_FollowupMessage(t *testing.T) {
- // End-to-end shape mimicking the user-reported bug: after exec 1
- // completes (HITL save approved + file artifact emitted), exec 2
- // kicks off with a new "change port" request. The bridge should
- // send only the new request to the A2A agent.
- got := LatestUserInputParts([]*proto.Message{
- userTextMsg("write me a flask server that listens on port 8080"),
- modelTextMsg("Here is the flask server: ..."),
- modelConfirmation("task-1", "I'd like to save this to ./flask_app.py"),
- stateMarker(t, "conv-1", "task-1"),
- userConfirmation("task-1", true),
- modelDocument([]byte("from flask import Flask\n..."), "text/x-python", "flask_app.py"),
- stateMarker(t, "conv-1", ""),
- userTextMsg("change port to 5050"),
- })
- want := []string{"change port to 5050"}
- gotTexts := partTexts(got)
- if !equalStrings(gotTexts, want) {
- t.Fatalf("LatestUserInputParts (exec 2 scenario): got %v, want %v", gotTexts, want)
- }
-}
-
-func TestAxMessagesToA2AParts_FullHistory(t *testing.T) {
- // Stateless mode: every text/file/data part across the whole
- // history (regardless of role) should be included.
- history := []*proto.Message{
- userTextMsg("write me a flask server"),
- modelTextMsg("here is your flask server"),
- modelDocument([]byte("print('hi')"), "text/x-python", "hi.py"),
- userTextMsg("change port to 5050"),
- }
- got := MessagesToA2AParts(history)
- wantTexts := []string{
- "write me a flask server",
- "here is your flask server",
- "change port to 5050",
- }
- if gotTexts := partTexts(got); !equalStrings(gotTexts, wantTexts) {
- t.Errorf("MessagesToA2AParts text parts: got %v, want %v", gotTexts, wantTexts)
- }
- // 3 text parts + 1 document part = 4 total.
- if len(got) != 4 {
- t.Errorf("MessagesToA2AParts total parts: got %d, want 4", len(got))
- }
-}
-
-func TestAxMessagesToA2AParts_SkipsAXInternalAndStateMarkers(t *testing.T) {
- // State markers and AX-internal types must be filtered out.
- got := MessagesToA2AParts([]*proto.Message{
- userTextMsg("hi"),
- stateMarker(t, "conv-1", "task-1"),
- modelConfirmation("task-1", "ok?"),
- userConfirmation("task-1", true),
- modelToolCall("call-1", "tool"),
- userTextMsg("bye"),
- })
- wantTexts := []string{"hi", "bye"}
- gotTexts := partTexts(got)
- if !equalStrings(gotTexts, wantTexts) {
- t.Fatalf("MessagesToA2AParts: got %v, want %v", gotTexts, wantTexts)
- }
-}
-
-func equalStrings(a, b []string) bool {
- if len(a) != len(b) {
- return false
- }
- for i := range a {
- if a[i] != b[i] {
- return false
- }
- }
- return true
-}
-
-// ----- AgentMetadataFromCard -----
-
-// cardWithSkills returns a minimal AgentCard populated with the supplied
-// fields and one Skill carrying name+description+tags+examples.
-func cardWithSkills(name, description, skillName, skillDesc string, tags, examples []string) *a2a.AgentCard {
- return &a2a.AgentCard{
- Name: name,
- Description: description,
- Skills: []a2a.AgentSkill{
- {
- Name: skillName,
- Description: skillDesc,
- Tags: tags,
- Examples: examples,
- },
- },
- }
-}
-
-func TestAgentMetadataFromCard_NilCard(t *testing.T) {
- // Nil card: returns cfg values unchanged, no skills enrichment.
- name, desc := AgentMetadataFromCard(nil, "cfgName", "cfgDescription")
- if name != "cfgName" {
- t.Errorf("name: got %q, want %q", name, "cfgName")
- }
- if desc != "cfgDescription" {
- t.Errorf("description: got %q, want %q", desc, "cfgDescription")
- }
-}
-
-func TestAgentMetadataFromCard_CfgOverridesCard(t *testing.T) {
- // Both cfgName and cfgDescription are non-empty; they win over the
- // card values. (Description still gets skills enrichment though.)
- card := cardWithSkills("cardName", "cardDescription", "skill1", "Does X", nil, nil)
- name, desc := AgentMetadataFromCard(card, "cfgName", "cfgDescription")
- if name != "cfgName" {
- t.Errorf("name: got %q, want %q (cfg wins)", name, "cfgName")
- }
- if !strings.HasPrefix(desc, "cfgDescription.") {
- t.Errorf("description: got %q, want it to start with 'cfgDescription.' (cfg wins, then enriched)", desc)
- }
- if !strings.Contains(desc, "skill1: Does X") {
- t.Errorf("description: got %q, want it to contain skill metadata", desc)
- }
-}
-
-func TestAgentMetadataFromCard_FallsBackToCardWhenCfgEmpty(t *testing.T) {
- // Empty cfg -> falls back to card values.
- card := cardWithSkills("cardName", "cardDescription", "skill1", "Does X", nil, nil)
- name, desc := AgentMetadataFromCard(card, "", "")
- if name != "cardName" {
- t.Errorf("name: got %q, want %q (fallback to card)", name, "cardName")
- }
- if !strings.HasPrefix(desc, "cardDescription.") {
- t.Errorf("description: got %q, want it to start with 'cardDescription.' (fallback to card, then enriched)", desc)
- }
-}
-
-func TestAgentMetadataFromCard_NoSkillsLeavesDescriptionUnchanged(t *testing.T) {
- // Card with no Skills -> description NOT enriched (no Skills: header).
- card := &a2a.AgentCard{Name: "cardName", Description: "cardDescription"}
- _, desc := AgentMetadataFromCard(card, "", "")
- if desc != "cardDescription" {
- t.Errorf("description: got %q, want %q (no skills, no enrichment)", desc, "cardDescription")
- }
-}
-
-func TestAgentMetadataFromCard_FullEnrichmentFormat(t *testing.T) {
- // Card with skills + tags + examples produces the full markdown
- // format: terminating period normalized; skills bullet list with
- // "(tags: ...)" suffix and indented "Examples: ..." line.
- card := cardWithSkills(
- "agent",
- "A coding agent",
- "code",
- "Write Python",
- []string{"dev", "python"},
- []string{"fizzbuzz", "hello world"},
- )
- _, desc := AgentMetadataFromCard(card, "", "")
- expected := "A coding agent.\n\nSkills:\n- code: Write Python (tags: dev, python)\n Examples: \"fizzbuzz\"; \"hello world\"\n"
- if desc != expected {
- t.Errorf("description format mismatch\ngot:\n%s\nwant:\n%s", desc, expected)
- }
-}
diff --git a/internal/experimental/a2abridge/a2a_event_handler.go b/internal/experimental/a2abridge/a2a_event_handler.go
deleted file mode 100644
index 89ea480..0000000
--- a/internal/experimental/a2abridge/a2a_event_handler.go
+++ /dev/null
@@ -1,471 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package a2abridge
-
-import (
- "context"
- "errors"
- "fmt"
- "iter"
- "strings"
- "time"
-
- "github.com/a2aproject/a2a-go/v2/a2a"
- "github.com/a2aproject/a2a-go/v2/a2aclient"
- "github.com/google/ax/internal/agent"
- "github.com/google/ax/proto"
-)
-
-type streamState struct {
- conversationID string
- toolCallID string // planner's tool call ID
- agentID string // for AuthRequiredError
- o agent.OutputHandler
- activeTaskID a2a.TaskID
- terminal bool
- lastSeenTask *a2a.Task
- artifactBuffer map[a2a.ArtifactID]*a2a.Artifact
- emittedArtifact map[a2a.ArtifactID]bool
-}
-
-func newStreamState(conversationID, toolCallID, agentID string, o agent.OutputHandler) *streamState {
- return &streamState{
- conversationID: conversationID,
- toolCallID: toolCallID,
- agentID: agentID,
- o: o,
- artifactBuffer: make(map[a2a.ArtifactID]*a2a.Artifact),
- emittedArtifact: make(map[a2a.ArtifactID]bool),
- }
-}
-
-// handleEvent dispatches a single event from the A2A stream. Returns
-// (stop, err): stop indicates the stream should end (e.g. HITL pause).
-func (s *streamState) handleEvent(evt a2a.Event) (bool, error) {
- switch e := evt.(type) {
- case *a2a.Message:
- // Direct message response (no task).
- msgs := a2aPartsToMessages(e.Parts, a2aRoleToRole(e.Role))
- if len(msgs) > 0 {
- if err := s.o(&proto.AgentOutputs{Messages: msgs}); err != nil {
- return false, err
- }
- }
- return false, nil
-
- case *a2a.Task:
- // Snapshot of the task. Track it; emit any artifacts we haven't
- // seen yet. If the task is in INPUT_REQUIRED, treat it the same
- // way as the corresponding TaskStatusUpdateEvent: surface a
- // ConfirmationContent and persist the activeTaskID, then stop
- // the loop.
- s.lastSeenTask = e
- if e.ID != "" {
- s.activeTaskID = e.ID
- }
- for _, art := range e.Artifacts {
- if s.emittedArtifact[art.ID] {
- continue
- }
- s.emittedArtifact[art.ID] = true
- msgs := a2aArtifactToMessages(art, "agent")
- if len(msgs) > 0 {
- if err := s.o(&proto.AgentOutputs{Messages: msgs}); err != nil {
- return false, err
- }
- }
- }
- if e.Status.State == a2a.TaskStateAuthRequired {
- // Server is asking for refreshed credentials. The current static
- // credential model can't hot-reload, so mark terminal,
- // clear the marker, and return an actionable error.
- s.terminal = true
- _ = ClearStateMarker(s.conversationID, s.o)
- return false, AuthRequiredError(s.agentID, s.activeTaskID, e.Status.Message)
- }
- if e.Status.State == a2a.TaskStateInputRequired {
- if err := EmitConfirmation(s.conversationID, s.toolCallID, s.activeTaskID, e, emittedArtifactKeys(s.emittedArtifact), s.o); err != nil {
- return false, err
- }
- return true, nil
- }
- if e.Status.State.Terminal() {
- s.terminal = true
- }
- return false, nil
-
- case *a2a.TaskStatusUpdateEvent:
- if e.TaskID != "" {
- s.activeTaskID = e.TaskID
- }
- // Surface any human-readable status message to the client - EXCEPT
- // when the status is input_required (delivered as
- // ConfirmationContent.Question) or auth_required (delivered as
- // part of AuthRequiredError).
- if e.Status.Message != nil &&
- e.Status.State != a2a.TaskStateInputRequired &&
- e.Status.State != a2a.TaskStateAuthRequired {
- msgs := a2aPartsToMessages(e.Status.Message.Parts, a2aRoleToRole(e.Status.Message.Role))
- if len(msgs) > 0 {
- if err := s.o(&proto.AgentOutputs{Messages: msgs}); err != nil {
- return false, err
- }
- }
- }
- switch e.Status.State {
- case a2a.TaskStateInputRequired:
- // HITL pause: persist the active task ID and emit a
- // ConfirmationContent. Stop the stream loop.
- task := &a2a.Task{
- ID: s.activeTaskID,
- ContextID: s.conversationID,
- Status: e.Status,
- }
- if err := EmitConfirmation(s.conversationID, s.toolCallID, s.activeTaskID, task, emittedArtifactKeys(s.emittedArtifact), s.o); err != nil {
- return false, err
- }
- return true, nil
- case a2a.TaskStateAuthRequired:
- // Server is asking for refreshed credentials mid-stream.
- // Our static-credential model can't hot-reload, so mark
- // terminal, clear the marker, and return an actionable error.
- s.terminal = true
- _ = ClearStateMarker(s.conversationID, s.o)
- return false, AuthRequiredError(s.agentID, s.activeTaskID, e.Status.Message)
- case a2a.TaskStateCompleted:
- s.terminal = true
- if err := ClearStateMarker(s.conversationID, s.o); err != nil {
- return false, err
- }
- case a2a.TaskStateFailed, a2a.TaskStateCanceled, a2a.TaskStateRejected:
- s.terminal = true
- _ = ClearStateMarker(s.conversationID, s.o)
- return false, fmt.Errorf("a2a task %s ended with state %s", s.activeTaskID, e.Status.State)
- }
- return false, nil
-
- case *a2a.TaskArtifactUpdateEvent:
- if e.TaskID != "" {
- s.activeTaskID = e.TaskID
- }
- if e.Artifact == nil {
- return false, nil
- }
- // Buffer chunks by artifact ID; emit on LastChunk=true. We rely
- // on the A2A protocol's LastChunk contract and don't add a
- // per-artifact timeout.
- existing, ok := s.artifactBuffer[e.Artifact.ID]
- if !ok || !e.Append {
- // Start a new buffer entry (or replace if not appending).
- cp := *e.Artifact
- s.artifactBuffer[e.Artifact.ID] = &cp
- } else {
- existing.Parts = append(existing.Parts, e.Artifact.Parts...)
- }
- if e.LastChunk {
- full := s.artifactBuffer[e.Artifact.ID]
- delete(s.artifactBuffer, e.Artifact.ID)
- s.emittedArtifact[e.Artifact.ID] = true
- msgs := a2aArtifactToMessages(full, "agent")
- if len(msgs) > 0 {
- if err := s.o(&proto.AgentOutputs{Messages: msgs}); err != nil {
- return false, err
- }
- }
- }
- return false, nil
- }
- return false, nil
-}
-
-// IterateStream walks the SDK's iter.Seq2 stream of events, dispatches
-// each to the appropriate handler, and returns once the stream ends or a
-// fatal error is encountered. If the stream ends with the active task
-// still in a non-terminal state, falls back to polling GetTask via
-// PollUntilTerminal until the task reaches a terminal state.
-//
-// client and agentID are passed through to the polling fallback so it
-// can issue GetTask calls and format error messages.
-func IterateStream(
- ctx context.Context,
- client *a2aclient.Client,
- agentID string,
- conversationID string,
- toolCallID string,
- events iter.Seq2[a2a.Event, error],
- o agent.OutputHandler,
-) error {
- state := newStreamState(conversationID, toolCallID, agentID, o)
- for evt, err := range events {
- if err != nil {
- return fmt.Errorf("a2a agent %s: stream error: %w", agentID, err)
- }
- stop, err := state.handleEvent(evt)
- if err != nil {
- return err
- }
- if stop {
- return nil
- }
- }
- // Stream ended. If we have an active task that's still non-terminal
- // the server expects us to poll for completion.
- if state.activeTaskID != "" && !state.terminal {
- return PollUntilTerminal(ctx, client, agentID, conversationID, toolCallID, state.activeTaskID, state.lastSeenTask, emittedArtifactKeys(state.emittedArtifact), o)
- }
- return nil
-}
-
-// PollUntilTerminal polls GetTask with exponential backoff until the task
-// reaches a terminal state, the context is canceled, or an error occurs.
-// Newly discovered artifacts and status changes are emitted to the client.
-//
-// client and agentID identify the SDK client and the bridge's registered
-// agent ID for issuing GetTask and constructing user-facing errors.
-//
-// toolCallID is forwarded to EmitConfirmation if the task transitions to
-// INPUT_REQUIRED while we are polling.
-//
-// alreadyEmitted seeds the dedup set with artifact IDs already emitted by
-// the caller. It prevents re-emission across the streaming<->polling handoff
-// and across invocation boundaries.
-func PollUntilTerminal(
- ctx context.Context,
- client *a2aclient.Client,
- agentID string,
- conversationID string,
- toolCallID string,
- taskID a2a.TaskID,
- lastSeen *a2a.Task,
- alreadyEmitted []string,
- o agent.OutputHandler,
-) error {
- emittedArtifactIDs := make(map[a2a.ArtifactID]bool)
- if lastSeen != nil {
- for _, art := range lastSeen.Artifacts {
- emittedArtifactIDs[art.ID] = true
- }
- }
- for _, id := range alreadyEmitted {
- emittedArtifactIDs[a2a.ArtifactID(id)] = true
- }
-
- const initialDelay = 250 * time.Millisecond
- const maxDelay = 60 * time.Second
-
- delay := initialDelay
- for {
- select {
- case <-ctx.Done():
- return ctx.Err()
- case <-time.After(delay):
- }
-
- task, err := client.GetTask(ctx, &a2a.GetTaskRequest{ID: taskID})
- if err != nil {
- // If the server has dropped the task while we were polling,
- // the marker is stale: clear it and surface a clean error.
- if errors.Is(err, a2a.ErrTaskNotFound) {
- _ = ClearStateMarker(conversationID, o)
- return fmt.Errorf("a2a agent %s: task %s no longer exists on server (state marker cleared)", agentID, taskID)
- }
- return fmt.Errorf("a2a agent %s: poll GetTask(%s): %w", agentID, taskID, err)
- }
-
- // Emit newly observed artifacts. Track whether anything new
- // arrived this iteration.
- sawNewArtifact := false
- for _, art := range task.Artifacts {
- if emittedArtifactIDs[art.ID] {
- continue
- }
- emittedArtifactIDs[art.ID] = true
- sawNewArtifact = true
- msgs := a2aArtifactToMessages(art, "agent")
- if len(msgs) > 0 {
- if err := o(&proto.AgentOutputs{Messages: msgs}); err != nil {
- return err
- }
- }
- }
-
- switch task.Status.State {
- case a2a.TaskStateCompleted:
- return ClearStateMarker(conversationID, o)
- case a2a.TaskStateFailed, a2a.TaskStateCanceled, a2a.TaskStateRejected:
- _ = ClearStateMarker(conversationID, o)
- return fmt.Errorf("a2a agent %s: task %s ended with state %s", agentID, taskID, task.Status.State)
- case a2a.TaskStateAuthRequired:
- // Server is asking for refreshed credentials mid-poll.
- // Our static-credential model can't hot-reload, so clear
- // the marker and surface an actionable error.
- _ = ClearStateMarker(conversationID, o)
- return AuthRequiredError(agentID, taskID, task.Status.Message)
- case a2a.TaskStateInputRequired:
- // Convert to HITL pause; persist the current emitted set
- // so resume after the user's answer doesn't re-emit.
- return EmitConfirmation(conversationID, toolCallID, taskID, task, emittedArtifactKeys(emittedArtifactIDs), o)
- }
-
- // Reset poll delay on activity.
- if sawNewArtifact {
- delay = initialDelay
- } else {
- delay *= 2
- if delay > maxDelay {
- delay = maxDelay
- }
- }
- }
-}
-
-// EmitTaskArtifacts emits all artifacts from a completed task to the client.
-func EmitTaskArtifacts(task *a2a.Task, o agent.OutputHandler) error {
- for _, art := range task.Artifacts {
- msgs := a2aArtifactToMessages(art, "agent")
- if len(msgs) > 0 {
- if err := o(&proto.AgentOutputs{Messages: msgs}); err != nil {
- return err
- }
- }
- }
- return nil
-}
-
-// EmitConfirmation surfaces a HITL prompt to the AX client and persists the
-// state marker so the bridge can resume the same task on the user's reply.
-//
-// ConfirmationContentID is set to toolCallID so the planner can correlate
-// the user's reply back to the call via a strict ID match.
-// If toolCallID is empty (the bridge was invoked without a planner), we fall
-// back to string(taskID).
-func EmitConfirmation(conversationID, toolCallID string, taskID a2a.TaskID, task *a2a.Task, emittedArtifactIDs []string, o agent.OutputHandler) error {
- question := "The agent requires confirmation."
- if task != nil && task.Status.Message != nil {
- var b string
- for _, part := range task.Status.Message.Parts {
- if t := part.Text(); t != "" {
- if b != "" {
- b += "\n"
- }
- b += t
- }
- }
- if b != "" {
- question = b
- }
- }
- // Persist the (conversationID, taskID, emittedArtifactIDs) first so
- // resume can recover it.
- stateMsg, err := marshalA2AState(conversationID, string(taskID), emittedArtifactIDs)
- if err != nil {
- return err
- }
- if err := o(&proto.AgentOutputs{Messages: []*proto.Message{stateMsg}}); err != nil {
- return err
- }
- confID := toolCallID
- if confID == "" {
- confID = string(taskID)
- }
- // Emit the ConfirmationContent last so the executor sees it as the
- // final output and records the exec as PENDING.
- confirmMsg := &proto.Message{
- Role: "agent",
- Content: &proto.Content{
- Type: &proto.Content_Confirmation{
- Confirmation: &proto.ConfirmationContent{
- Id: confID,
- Question: question,
- },
- },
- },
- }
- return o(&proto.AgentOutputs{Messages: []*proto.Message{confirmMsg}})
-}
-
-// AuthRequiredError formats a user-facing error for TaskStateAuthRequired.
-// Surfaces any hint the agent included in Status.Message. Temporary for now.
-func AuthRequiredError(agentID string, taskID a2a.TaskID, statusMsg *a2a.Message) error {
- var b strings.Builder
- fmt.Fprintf(&b, "a2a agent %s: task %s requires updated auth credentials", agentID, taskID)
- if statusMsg != nil {
- var hint string
- for _, part := range statusMsg.Parts {
- if t := part.Text(); t != "" {
- if hint != "" {
- hint += "\n"
- }
- hint += t
- }
- }
- if hint != "" {
- fmt.Fprintf(&b, ": %s", hint)
- }
- }
- b.WriteString("; refresh credentials and restart AX")
- return errors.New(b.String())
-}
-
-// ClearStateMarker writes a final state marker indicating no active task.
-func ClearStateMarker(conversationID string, o agent.OutputHandler) error {
- msg, err := marshalA2AState(conversationID, "", nil)
- if err != nil {
- return err
- }
- return o(&proto.AgentOutputs{Messages: []*proto.Message{msg}})
-}
-
-// FindConfirmationAnswer scans the history (most recent first) for a user
-// reply to the ConfirmationContent we emitted with the given confID.
-// Returns (true, approved) if a matching answer is found, (false, false)
-// otherwise.
-func FindConfirmationAnswer(history []*proto.Message, confID string) (answered, approved bool) {
- for i := len(history) - 1; i >= 0; i-- {
- conf := history[i].GetContent().GetConfirmation()
- if conf == nil {
- continue
- }
- if confID != "" && conf.Id != confID {
- continue
- }
- if conf.GetApproval() != nil {
- return true, true
- }
- if conf.GetDecline() != nil {
- return true, false
- }
- }
- return false, false
-}
-
-// FindToolCallID returns the ID of the most recent ToolCall in history
-// whose function name matches agentID.
-// Returns "" when no matching ToolCall is found - e.g. the bridge was
-// invoked without a planner.
-func FindToolCallID(agentID string, messages []*proto.Message) string {
- for i := len(messages) - 1; i >= 0; i-- {
- tc := messages[i].GetContent().GetToolCall()
- if tc == nil {
- continue
- }
- fc := tc.GetFunctionCall()
- if fc == nil || fc.Name != agentID {
- continue
- }
- return tc.Id
- }
- return ""
-}
diff --git a/internal/experimental/a2abridge/a2a_event_handler_test.go b/internal/experimental/a2abridge/a2a_event_handler_test.go
deleted file mode 100644
index 9e776d9..0000000
--- a/internal/experimental/a2abridge/a2a_event_handler_test.go
+++ /dev/null
@@ -1,194 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package a2abridge
-
-import (
- "strings"
- "testing"
-
- "github.com/a2aproject/a2a-go/v2/a2a"
- "github.com/google/ax/proto"
-)
-
-// captureHandler records every AgentOutputs emission for later inspection.
-type captureHandler struct {
- emissions []*proto.AgentOutputs
-}
-
-func (c *captureHandler) handle(out *proto.AgentOutputs) error {
- c.emissions = append(c.emissions, out)
- return nil
-}
-
-// allMessages returns the flattened list of messages across every emission.
-func (c *captureHandler) allMessages() []*proto.Message {
- var out []*proto.Message
- for _, e := range c.emissions {
- out = append(out, e.Messages...)
- }
- return out
-}
-
-// findConfirmation returns the first ConfirmationContent emitted, or nil.
-func (c *captureHandler) findConfirmation() *proto.ConfirmationContent {
- for _, msg := range c.allMessages() {
- if conf := msg.GetContent().GetConfirmation(); conf != nil {
- return conf
- }
- }
- return nil
-}
-
-// findStateMarker returns the recovered state marker fields, if any was emitted.
-func (c *captureHandler) findStateMarker() (conv string, taskID string, ok bool) {
- conv, taskID, _, ok = RecoverA2AState(c.allMessages())
- return
-}
-
-func TestStreamState_TaskWithInputRequiredEmitsConfirmation(t *testing.T) {
- cap := &captureHandler{}
- const toolCallID = "call-abc"
- state := newStreamState("conv-1", toolCallID, "", cap.handle)
-
- question := "Save flask_server.py to /tmp/flask_server.py?"
- task := &a2a.Task{
- ID: "task-2",
- ContextID: "conv-1",
- Status: a2a.TaskStatus{
- State: a2a.TaskStateInputRequired,
- Message: &a2a.Message{
- Role: a2a.MessageRoleAgent,
- Parts: []*a2a.Part{a2a.NewTextPart(question)},
- },
- },
- }
-
- stop, err := state.handleEvent(task)
- if err != nil {
- t.Fatalf("handleEvent returned error: %v", err)
- }
- if !stop {
- t.Fatal("handleEvent: expected stop=true for INPUT_REQUIRED, got false")
- }
-
- conf := cap.findConfirmation()
- if conf == nil {
- t.Fatal("expected a ConfirmationContent emission, got none")
- }
- if conf.Id != toolCallID {
- t.Errorf("ConfirmationContent.Id: got %q, want %q (planner's ToolCall.Id)", conf.Id, toolCallID)
- }
- if !strings.Contains(conf.Question, question) {
- t.Errorf("ConfirmationContent.Question: got %q, want it to contain %q", conf.Question, question)
- }
-
- convID, taskID, ok := cap.findStateMarker()
- if !ok {
- t.Fatal("expected a state marker emission, got none")
- }
- if convID != "conv-1" {
- t.Errorf("state marker conversationID: got %q, want %q", convID, "conv-1")
- }
- if taskID != "task-2" {
- t.Errorf("state marker activeTaskID: got %q, want %q", taskID, "task-2")
- }
-}
-
-func TestStreamState_TaskWithCompletedDoesNotEmitConfirmation(t *testing.T) {
- // A completed Task event should mark terminal=true and emit any
- // artifacts but NOT emit a ConfirmationContent or stop the loop.
- cap := &captureHandler{}
- state := newStreamState("conv-1", "call-abc", "", cap.handle)
-
- task := &a2a.Task{
- ID: "task-3",
- ContextID: "conv-1",
- Status: a2a.TaskStatus{State: a2a.TaskStateCompleted},
- Artifacts: []*a2a.Artifact{
- {
- ID: "a1",
- Name: "result",
- Parts: []*a2a.Part{a2a.NewTextPart("done")},
- },
- },
- }
-
- stop, err := state.handleEvent(task)
- if err != nil {
- t.Fatalf("handleEvent returned error: %v", err)
- }
- if stop {
- t.Fatal("handleEvent: expected stop=false for COMPLETED task event, got true")
- }
- if !state.terminal {
- t.Error("expected state.terminal=true after a completed Task event")
- }
- if cap.findConfirmation() != nil {
- t.Error("did not expect a ConfirmationContent emission for a completed task")
- }
- // Artifact should have been emitted.
- if len(cap.allMessages()) == 0 {
- t.Error("expected the artifact to be emitted to the client")
- }
-}
-
-func TestStreamState_TaskStatusUpdateInputRequiredEmitsConfirmation(t *testing.T) {
- // The streaming path: INPUT_REQUIRED arrives as a
- // TaskStatusUpdateEvent. The bridge should emit a single
- // ConfirmationContent.
- cap := &captureHandler{}
- state := newStreamState("conv-1", "call-xyz", "", cap.handle)
-
- question := "Save flask_server.py?"
- evt := &a2a.TaskStatusUpdateEvent{
- ContextID: "conv-1",
- TaskID: "task-2",
- Status: a2a.TaskStatus{
- State: a2a.TaskStateInputRequired,
- Message: &a2a.Message{
- Role: a2a.MessageRoleAgent,
- Parts: []*a2a.Part{a2a.NewTextPart(question)},
- },
- },
- }
-
- stop, err := state.handleEvent(evt)
- if err != nil {
- t.Fatalf("handleEvent returned error: %v", err)
- }
- if !stop {
- t.Fatal("handleEvent: expected stop=true for INPUT_REQUIRED, got false")
- }
-
- conf := cap.findConfirmation()
- if conf == nil {
- t.Fatal("expected a ConfirmationContent emission, got none")
- }
- if !strings.Contains(conf.Question, question) {
- t.Errorf("ConfirmationContent.Question: got %q, want it to contain %q", conf.Question, question)
- }
-
- // Verify the question text was NOT also emitted as a separate
- // TextContent (the de-duplication fix from a prior round).
- textOnlyEmissions := 0
- for _, msg := range cap.allMessages() {
- if msg.GetContent().GetText() != nil && strings.Contains(msg.GetContent().GetText().Text, question) {
- textOnlyEmissions++
- }
- }
- if textOnlyEmissions > 0 {
- t.Errorf("INPUT_REQUIRED status message should NOT be emitted as a standalone TextContent (got %d such emissions)", textOnlyEmissions)
- }
-}
diff --git a/internal/experimental/a2abridge/a2a_internal_state.go b/internal/experimental/a2abridge/a2a_internal_state.go
deleted file mode 100644
index 2e0b674..0000000
--- a/internal/experimental/a2abridge/a2a_internal_state.go
+++ /dev/null
@@ -1,98 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package a2abridge
-
-import (
- "encoding/json"
- "fmt"
-
- "github.com/a2aproject/a2a-go/v2/a2a"
- "github.com/google/ax/proto"
-)
-
-// The role used by the bridge as the source of internal_only state-marker messages.
-const stateMarkerRole = "a2a_bridge"
-
-// a2aStatePayload is the JSON shape of the internal_only state marker's
-// TextContent payload. The marker is emitted as a Message with InternalOnly=true
-// so it persists in the ExecutionEvents log (for the bridge to recover on resume)
-// but is filtered out of the conversation log, the CLI display, and Gemini's view
-// of conversation history.
-type a2aStatePayload struct {
- ConversationID string `json:"conversation_id"`
- ActiveTaskID string `json:"active_task_id"`
- EmittedArtifactIDs []string `json:"emitted_artifact_ids,omitempty"`
-}
-
-func marshalA2AState(conversationID, activeTaskID string, emittedArtifactIDs []string) (*proto.Message, error) {
- payload := a2aStatePayload{
- ConversationID: conversationID,
- ActiveTaskID: activeTaskID,
- EmittedArtifactIDs: emittedArtifactIDs,
- }
- bytes, err := json.Marshal(payload)
- if err != nil {
- return nil, fmt.Errorf("marshal a2a state marker: %w", err)
- }
- return &proto.Message{
- Role: stateMarkerRole,
- InternalOnly: true,
- Content: &proto.Content{
- Type: &proto.Content_Text{
- Text: &proto.TextContent{Text: string(bytes)},
- },
- },
- }, nil
-}
-
-// RecoverA2AState scans the message history for the most recent A2A state
-// marker and returns its conversation_id, active_task_id, and the list
-// of artifact IDs already emitted by the prior bridge invocation. The
-// most recent marker wins so successive resume cycles see the latest state.
-func RecoverA2AState(msgs []*proto.Message) (conversationID, activeTaskID string, emittedArtifactIDs []string, found bool) {
- for i := len(msgs) - 1; i >= 0; i-- {
- if !isStateMarkerMessage(msgs[i]) {
- continue
- }
- t := msgs[i].GetContent().GetText()
- if t == nil {
- continue
- }
- var payload a2aStatePayload
- if err := json.Unmarshal([]byte(t.Text), &payload); err != nil {
- continue
- }
- return payload.ConversationID, payload.ActiveTaskID, payload.EmittedArtifactIDs, true
- }
- return "", "", nil, false
-}
-
-func emittedArtifactKeys(m map[a2a.ArtifactID]bool) []string {
- if len(m) == 0 {
- return nil
- }
- out := make([]string, 0, len(m))
- for id := range m {
- out = append(out, string(id))
- }
- return out
-}
-
-func isStateMarkerMessage(msg *proto.Message) bool {
- if msg == nil || !msg.GetInternalOnly() || msg.GetRole() != stateMarkerRole {
- return false
- }
- return msg.GetContent().GetText() != nil
-}
diff --git a/internal/experimental/a2abridge/a2a_internal_state_test.go b/internal/experimental/a2abridge/a2a_internal_state_test.go
deleted file mode 100644
index 615bee9..0000000
--- a/internal/experimental/a2abridge/a2a_internal_state_test.go
+++ /dev/null
@@ -1,97 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package a2abridge
-
-import (
- "testing"
-
- "github.com/google/ax/proto"
-)
-
-// buildStateMarker wraps marshalA2AState for tests; the inputs used here are
-// always JSON-marshalable (string + []string), so an error fails the test.
-func buildStateMarker(t *testing.T, conversationID, activeTaskID string, emittedArtifactIDs []string) *proto.Message {
- t.Helper()
- m, err := marshalA2AState(conversationID, activeTaskID, emittedArtifactIDs)
- if err != nil {
- t.Fatalf("marshalA2AState: %v", err)
- }
- return m
-}
-
-func TestStateMarkerRoundTrip(t *testing.T) {
- msg := buildStateMarker(t, "conv-abc", "task-xyz", []string{"art-1", "art-2"})
- if !isStateMarkerMessage(msg) {
- t.Fatal("isStateMarkerMessage: expected marker to be recognised")
- }
- conv, task, emitted, found := RecoverA2AState([]*proto.Message{msg})
- if !found {
- t.Fatal("RecoverA2AState: not found")
- }
- if conv != "conv-abc" {
- t.Errorf("conversationID: got %q, want %q", conv, "conv-abc")
- }
- if task != "task-xyz" {
- t.Errorf("activeTaskID: got %q, want %q", task, "task-xyz")
- }
- if !equalStrings(emitted, []string{"art-1", "art-2"}) {
- t.Errorf("emittedArtifactIDs: got %v, want [art-1 art-2]", emitted)
- }
-}
-
-func TestStateMarkerRoundTrip_NilEmittedArtifactIDs(t *testing.T) {
- msg := buildStateMarker(t, "conv", "task", nil)
- _, _, emitted, found := RecoverA2AState([]*proto.Message{msg})
- if !found {
- t.Fatal("RecoverA2AState: not found")
- }
- if emitted != nil {
- t.Errorf("emittedArtifactIDs: got %v, want nil", emitted)
- }
-}
-
-func TestRecoverA2AState_ReturnsMostRecentMarker(t *testing.T) {
- got := []*proto.Message{
- buildStateMarker(t, "conv-1", "task-1", []string{"art-old"}), // older
- modelTextMsg("did some work"),
- buildStateMarker(t, "conv-1", "", nil), // newer (clears the marker)
- }
- conv, task, emitted, found := RecoverA2AState(got)
- if !found {
- t.Fatal("RecoverA2AState: not found")
- }
- if conv != "conv-1" {
- t.Errorf("conversationID: got %q, want %q", conv, "conv-1")
- }
- if task != "" {
- t.Errorf("activeTaskID: got %q, want empty (cleared)", task)
- }
- if emitted != nil {
- t.Errorf("emittedArtifactIDs: got %v, want nil (most recent marker is cleared)", emitted)
- }
-}
-
-func TestIsStateMarkerMessage_RejectsForeignInternalOnlyText(t *testing.T) {
- foreign := &proto.Message{
- Role: "future_subsystem",
- InternalOnly: true,
- Content: &proto.Content{
- Type: &proto.Content_Text{Text: &proto.TextContent{Text: "anything"}},
- },
- }
- if isStateMarkerMessage(foreign) {
- t.Error("expected isStateMarkerMessage to reject InternalOnly TextContent from non-bridge role")
- }
-}
diff --git a/internal/experimental/a2abridge/auth.go b/internal/experimental/a2abridge/auth.go
deleted file mode 100644
index 76c392a..0000000
--- a/internal/experimental/a2abridge/auth.go
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package a2abridge
-
-import (
- "context"
- "errors"
-
- "github.com/a2aproject/a2a-go/v2/a2a"
- "github.com/a2aproject/a2a-go/v2/a2aclient"
- "github.com/google/ax/internal/auth"
-)
-
-// apiKeyHeaderFromCard looks up the api_key header name from an
-// AgentCard's APIKeySecurityScheme.
-// Returns ("", error) when the card declares no APIKeySecurityScheme
-// with Location=header.
-func apiKeyHeaderFromCard(card *a2a.AgentCard) (string, error) {
- if card != nil {
- for _, scheme := range card.SecuritySchemes {
- apiKey, ok := scheme.(a2a.APIKeySecurityScheme)
- if !ok {
- continue
- }
- if apiKey.Location == a2a.APIKeySecuritySchemeLocationHeader && apiKey.Name != "" {
- return apiKey.Name, nil
- }
- }
- }
- return "", errors.New(
- `auth.api_key: AgentCard does not declare an APIKeySecurityScheme ` +
- `with Location=header; specify the API key header via headers.env instead`)
-}
-
-// interceptor implements a2aclient.CallInterceptor and writes a fixed map
-// of headers directly to req.ServiceParams on every outgoing request. The
-// transport (HTTP / JSON-RPC / REST / gRPC) serialises ServiceParams into
-// headers per its protocol binding.
-type interceptor struct {
- headers map[string]string
-}
-
-// NewInterceptor builds an a2aclient.CallInterceptor that injects the
-// merged auth + user headers on every outgoing call. Returns (nil, nil)
-// when no headers are configured.
-func NewInterceptor(card *a2a.AgentCard, a auth.Auth, h auth.Headers) (a2aclient.CallInterceptor, error) {
- apiKeyHeader := ""
- if a.Type == "api_key" {
- name, err := apiKeyHeaderFromCard(card)
- if err != nil {
- return nil, err
- }
- apiKeyHeader = name
- }
- headers, err := auth.MergeAllHeaders(a, h, apiKeyHeader)
- if err != nil {
- return nil, err
- }
- if len(headers) == 0 {
- return nil, nil
- }
- return &interceptor{headers: headers}, nil
-}
-
-// Before implements a2aclient.CallInterceptor.
-func (i *interceptor) Before(ctx context.Context, req *a2aclient.Request) (context.Context, any, error) {
- if len(i.headers) == 0 {
- return ctx, nil, nil
- }
- if req.ServiceParams == nil {
- req.ServiceParams = make(a2aclient.ServiceParams)
- }
- for k, v := range i.headers {
- // Set semantics (overwrite existing entry for the same key).
- req.ServiceParams[k] = []string{v}
- }
- return ctx, nil, nil
-}
-
-// After implements a2aclient.CallInterceptor.
-func (i *interceptor) After(_ context.Context, _ *a2aclient.Response) error {
- return nil
-}
diff --git a/internal/experimental/a2abridge/auth_test.go b/internal/experimental/a2abridge/auth_test.go
deleted file mode 100644
index 914c83d..0000000
--- a/internal/experimental/a2abridge/auth_test.go
+++ /dev/null
@@ -1,130 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package a2abridge
-
-import (
- "context"
- "strings"
- "testing"
-
- "github.com/a2aproject/a2a-go/v2/a2a"
- "github.com/a2aproject/a2a-go/v2/a2aclient"
- "github.com/google/ax/internal/auth"
-)
-
-// cardWithAPIKey returns an AgentCard declaring a single APIKeySecurityScheme
-// at the given location.
-func cardWithAPIKey(name string, location a2a.APIKeySecuritySchemeLocation) *a2a.AgentCard {
- return &a2a.AgentCard{
- SecuritySchemes: a2a.NamedSecuritySchemes{
- "apikey": a2a.APIKeySecurityScheme{Name: name, Location: location},
- },
- }
-}
-
-// ----- apiKeyHeaderFromCard -----
-
-func TestApiKeyHeaderFromCard_Found(t *testing.T) {
- card := cardWithAPIKey("X-API-Key", a2a.APIKeySecuritySchemeLocationHeader)
- name, err := apiKeyHeaderFromCard(card)
- if err != nil {
- t.Fatalf("got err=%v, want nil", err)
- }
- if name != "X-API-Key" {
- t.Errorf("name=%q, want %q", name, "X-API-Key")
- }
-}
-
-func TestApiKeyHeaderFromCard_NoMatchingScheme(t *testing.T) {
- cases := map[string]*a2a.AgentCard{
- "nil": nil, // no card at all
- "empty": {}, // no SecuritySchemes
- "cookie": cardWithAPIKey("session", a2a.APIKeySecuritySchemeLocationCookie),
- "querystr": cardWithAPIKey("api_key", a2a.APIKeySecuritySchemeLocationQuery),
- }
- for label, card := range cases {
- t.Run(label, func(t *testing.T) {
- _, err := apiKeyHeaderFromCard(card)
- if err == nil {
- t.Fatal("got nil err, want non-nil")
- }
- if !strings.Contains(err.Error(), "APIKeySecurityScheme") {
- t.Errorf("err should mention APIKeySecurityScheme; got: %v", err)
- }
- })
- }
-}
-
-// ----- NewInterceptor -----
-
-func TestNewInterceptor_NilWhenEmpty(t *testing.T) {
- got, err := NewInterceptor(nil, auth.Auth{}, auth.Headers{})
- if err != nil {
- t.Fatalf("got err=%v, want nil", err)
- }
- if got != nil {
- t.Errorf("got non-nil interceptor, want nil for empty config")
- }
-}
-
-func TestNewInterceptor_PropagatesError(t *testing.T) {
- t.Setenv("MY_TOKEN", "abc123")
- _, err := NewInterceptor(nil,
- auth.Auth{Type: "bearer", CredentialEnv: "MY_TOKEN"},
- auth.Headers{Literal: map[string]string{"Authorization": "Bearer manual"}},
- )
- if err == nil {
- t.Fatal("got nil err, want non-nil for collision")
- }
-}
-
-// ----- interceptor (CallInterceptor implementation) -----
-
-func TestInterceptor_BeforeWritesToRequestServiceParams(t *testing.T) {
- in := &interceptor{
- headers: map[string]string{
- "Authorization": "Bearer abc",
- "X-Organization-Id": "acme",
- },
- }
- req := &a2aclient.Request{ServiceParams: make(a2aclient.ServiceParams)}
- if _, _, err := in.Before(context.Background(), req); err != nil {
- t.Fatalf("got err=%v, want nil", err)
- }
- if got := req.ServiceParams["Authorization"]; len(got) != 1 || got[0] != "Bearer abc" {
- t.Errorf("Authorization=%v, want [Bearer abc]", got)
- }
- if got := req.ServiceParams["X-Organization-Id"]; len(got) != 1 || got[0] != "acme" {
- t.Errorf("X-Organization-Id=%v, want [acme]", got)
- }
-}
-
-func TestInterceptor_BeforeOverwritesExistingValue(t *testing.T) {
- in := &interceptor{headers: map[string]string{"Authorization": "Bearer correct"}}
- req := &a2aclient.Request{ServiceParams: a2aclient.ServiceParams{
- "Authorization": []string{"Bearer stale"},
- }}
- if _, _, err := in.Before(context.Background(), req); err != nil {
- t.Fatalf("got err=%v, want nil", err)
- }
- if got := req.ServiceParams["Authorization"]; len(got) != 1 || got[0] != "Bearer correct" {
- t.Errorf("Authorization=%v, want [Bearer correct] (overwrite)", got)
- }
-}
-
-// Ensure the unexported interceptor still implements the SDK's
-// CallInterceptor interface. If the SDK changes its method set, this
-// fails to compile rather than at runtime.
-var _ a2aclient.CallInterceptor = (*interceptor)(nil)
diff --git a/internal/experimental/a2abridge/card.go b/internal/experimental/a2abridge/card.go
deleted file mode 100644
index 5929725..0000000
--- a/internal/experimental/a2abridge/card.go
+++ /dev/null
@@ -1,52 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package a2abridge
-
-import (
- "fmt"
- "net/url"
-
- "github.com/a2aproject/a2a-go/v2/a2a"
-)
-
-// OverrideCardHosts rewrites the host:port portion of every URL in
-// card.SupportedInterfaces[] to match the host:port of addr.
-// Used for A2A agents whose AgentCard typically declares localhost URLs
-// that must be redirected to the actual worker address discovered at
-// connect time.
-func OverrideCardHosts(card *a2a.AgentCard, addr string) error {
- if card == nil {
- return nil
- }
- addrURL, err := url.Parse(addr)
- if err != nil {
- return fmt.Errorf("OverrideCardHosts: parse addr %q: %w", addr, err)
- }
- if addrURL.Host == "" {
- return fmt.Errorf("OverrideCardHosts: addr %q has no host", addr)
- }
- for i, iface := range card.SupportedInterfaces {
- if iface == nil {
- continue
- }
- u, err := url.Parse(iface.URL)
- if err != nil {
- return fmt.Errorf("OverrideCardHosts: parse SupportedInterfaces[%d].URL %q: %w", i, iface.URL, err)
- }
- u.Host = addrURL.Host
- iface.URL = u.String()
- }
- return nil
-}
diff --git a/internal/experimental/a2abridge/card_test.go b/internal/experimental/a2abridge/card_test.go
deleted file mode 100644
index 36f222c..0000000
--- a/internal/experimental/a2abridge/card_test.go
+++ /dev/null
@@ -1,116 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package a2abridge
-
-import (
- "strings"
- "testing"
-
- "github.com/a2aproject/a2a-go/v2/a2a"
-)
-
-func TestOverrideCardHosts_RewritesEverySupportedInterface(t *testing.T) {
- card := &a2a.AgentCard{
- SupportedInterfaces: []*a2a.AgentInterface{
- {URL: "http://localhost:8080/jsonrpc"},
- {URL: "http://localhost:8080/rest"},
- {URL: "http://localhost:50051"},
- },
- }
- if err := OverrideCardHosts(card, "http://10.0.1.5:8080"); err != nil {
- t.Fatalf("got err=%v, want nil", err)
- }
- want := []string{
- "http://10.0.1.5:8080/jsonrpc",
- "http://10.0.1.5:8080/rest",
- "http://10.0.1.5:8080",
- }
- for i, iface := range card.SupportedInterfaces {
- if iface.URL != want[i] {
- t.Errorf("SupportedInterfaces[%d].URL = %q, want %q", i, iface.URL, want[i])
- }
- }
-}
-
-func TestOverrideCardHosts_PreservesSchemeAndPath(t *testing.T) {
- card := &a2a.AgentCard{
- SupportedInterfaces: []*a2a.AgentInterface{
- {URL: "https://example.com/v2/agent?foo=bar"},
- },
- }
- if err := OverrideCardHosts(card, "https://1.2.3.4:443"); err != nil {
- t.Fatalf("got err=%v, want nil", err)
- }
- got := card.SupportedInterfaces[0].URL
- if got != "https://1.2.3.4:443/v2/agent?foo=bar" {
- t.Errorf("URL = %q, want scheme/path/query preserved with new host", got)
- }
-}
-
-func TestOverrideCardHosts_NilCardNoOp(t *testing.T) {
- if err := OverrideCardHosts(nil, "http://10.0.1.5:8080"); err != nil {
- t.Errorf("got err=%v, want nil for nil card", err)
- }
-}
-
-func TestOverrideCardHosts_EmptyInterfacesNoOp(t *testing.T) {
- card := &a2a.AgentCard{}
- if err := OverrideCardHosts(card, "http://10.0.1.5:8080"); err != nil {
- t.Errorf("got err=%v, want nil for empty interfaces", err)
- }
-}
-
-func TestOverrideCardHosts_RejectsAddrWithoutHost(t *testing.T) {
- card := &a2a.AgentCard{
- SupportedInterfaces: []*a2a.AgentInterface{{URL: "http://localhost:8080"}},
- }
- err := OverrideCardHosts(card, "")
- if err == nil {
- t.Fatal("got nil err, want non-nil for empty addr")
- }
- if !strings.Contains(err.Error(), "no host") {
- t.Errorf("err should mention missing host; got: %v", err)
- }
-}
-
-func TestOverrideCardHosts_RejectsMalformedURL(t *testing.T) {
- card := &a2a.AgentCard{
- SupportedInterfaces: []*a2a.AgentInterface{
- {URL: "://bad-url"},
- },
- }
- err := OverrideCardHosts(card, "http://10.0.1.5:8080")
- if err == nil {
- t.Fatal("got nil err, want non-nil for malformed URL")
- }
- if !strings.Contains(err.Error(), "SupportedInterfaces[0]") {
- t.Errorf("err should mention which interface failed; got: %v", err)
- }
-}
-
-func TestOverrideCardHosts_SkipsNilInterface(t *testing.T) {
- card := &a2a.AgentCard{
- SupportedInterfaces: []*a2a.AgentInterface{
- nil,
- {URL: "http://localhost:8080"},
- },
- }
- if err := OverrideCardHosts(card, "http://10.0.1.5:8080"); err != nil {
- t.Fatalf("got err=%v, want nil", err)
- }
- if card.SupportedInterfaces[1].URL != "http://10.0.1.5:8080" {
- t.Errorf("non-nil interface should be rewritten; got %q", card.SupportedInterfaces[1].URL)
- }
-}
diff --git a/internal/experimental/a2abridge/mappings.go b/internal/experimental/a2abridge/mappings.go
deleted file mode 100644
index 4d7133a..0000000
--- a/internal/experimental/a2abridge/mappings.go
+++ /dev/null
@@ -1,106 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package a2abridge
-
-import (
- "github.com/a2aproject/a2a-go/v2/a2a"
- "github.com/google/ax/proto"
-)
-
-// ----- enum <-> wire-string MIME mapping tables -----
-//
-// content.proto encodes canonical MIME wire strings (e.g. "image/png")
-// as annotations on each enum value. We maintain the forward (string -> enum)
-// tables here and derive the inverse (enum -> string) maps via invertMap.
-//
-// These tables are the single source of truth for the bridge's typed-
-// content conversion in both directions. A test guards that they stay in sync
-// with the content.proto annotations.
-
-var imageMimeFromString = map[string]proto.ImageContent_MimeType{
- "image/png": proto.ImageContent_TYPE_PNG,
- "image/jpeg": proto.ImageContent_TYPE_JPEG,
- "image/webp": proto.ImageContent_TYPE_WEBP,
- "image/heic": proto.ImageContent_TYPE_HEIC,
- "image/heif": proto.ImageContent_TYPE_HEIF,
- "image/gif": proto.ImageContent_TYPE_GIF,
- "image/bmp": proto.ImageContent_TYPE_BMP,
- "image/tiff": proto.ImageContent_TYPE_TIFF,
-}
-
-var audioMimeFromString = map[string]proto.AudioContent_MimeType{
- "audio/wav": proto.AudioContent_TYPE_WAV,
- "audio/mp3": proto.AudioContent_TYPE_MP3,
- "audio/aiff": proto.AudioContent_TYPE_AIFF,
- "audio/aac": proto.AudioContent_TYPE_AAC,
- "audio/ogg": proto.AudioContent_TYPE_OGG,
- "audio/flac": proto.AudioContent_TYPE_FLAC,
- "audio/mpeg": proto.AudioContent_TYPE_MPEG,
- "audio/m4a": proto.AudioContent_TYPE_M4A,
- "audio/l16": proto.AudioContent_TYPE_L16,
- "audio/s16le": proto.AudioContent_TYPE_S16LE,
- "audio/opus": proto.AudioContent_TYPE_OPUS,
- "audio/alaw": proto.AudioContent_TYPE_ALAW,
- "audio/mulaw": proto.AudioContent_TYPE_MULAW,
-}
-
-var videoMimeFromString = map[string]proto.VideoContent_MimeType{
- "video/mp4": proto.VideoContent_TYPE_MP4,
- "video/mpeg": proto.VideoContent_TYPE_MPEG,
- "video/mpg": proto.VideoContent_TYPE_MPG,
- "video/mov": proto.VideoContent_TYPE_MOV,
- "video/avi": proto.VideoContent_TYPE_AVI,
- "video/x-flv": proto.VideoContent_TYPE_X_FLV,
- "video/webm": proto.VideoContent_TYPE_WEBM,
- "video/wmv": proto.VideoContent_TYPE_WMV,
- "video/3gpp": proto.VideoContent_TYPE_3GPP,
-}
-
-var documentMimeFromString = map[string]proto.DocumentContent_MimeType{
- "application/pdf": proto.DocumentContent_TYPE_PDF,
- "application/json": proto.DocumentContent_TYPE_JSON,
- "text/x-python": proto.DocumentContent_TYPE_PYTHON,
-}
-
-var (
- imageMimeToString = invertMap(imageMimeFromString)
- audioMimeToString = invertMap(audioMimeFromString)
- videoMimeToString = invertMap(videoMimeFromString)
- documentMimeToString = invertMap(documentMimeFromString)
-)
-
-// ----- role mapping -----
-//
-// stringToA2ARole is the strict source-of-truth map for role translation
-// between AX (string) and A2A (typed enum). The inverse (a2aRoleToString)
-// is derived via invertMap so adding an entry here automatically
-// propagates to both directions.
-var stringToA2ARole = map[string]a2a.MessageRole{
- "unspecified": a2a.MessageRoleUnspecified,
- "user": a2a.MessageRoleUser,
- "agent": a2a.MessageRoleAgent,
-}
-
-var a2aRoleToString = invertMap(stringToA2ARole)
-
-// invertMap returns a new map with keys and values swapped. If two keys
-// map to the same value, last write wins per Go map iteration order.
-func invertMap[K, V comparable](in map[K]V) map[V]K {
- out := make(map[V]K, len(in))
- for k, v := range in {
- out[v] = k
- }
- return out
-}
diff --git a/internal/experimental/a2abridge/mappings_test.go b/internal/experimental/a2abridge/mappings_test.go
deleted file mode 100644
index 8ec46d6..0000000
--- a/internal/experimental/a2abridge/mappings_test.go
+++ /dev/null
@@ -1,70 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package a2abridge
-
-import (
- "testing"
-
- "github.com/google/ax/proto"
- "google.golang.org/protobuf/reflect/protoreflect"
-)
-
-// TestMimeTableCoverage verifies that every non-UNSPECIFIED MIME enum
-// value declared in proto/content.proto has a corresponding wire-string
-// entry in mime_map.go's forward table.
-func TestMimeTableCoverage(t *testing.T) {
- t.Run("ImageContent_MimeType", func(t *testing.T) {
- assertMimeCoverage(t, proto.ImageContent_MimeType(0).Descriptor(), func(n int32) bool {
- _, ok := imageMimeToString[proto.ImageContent_MimeType(n)]
- return ok
- })
- })
- t.Run("AudioContent_MimeType", func(t *testing.T) {
- assertMimeCoverage(t, proto.AudioContent_MimeType(0).Descriptor(), func(n int32) bool {
- _, ok := audioMimeToString[proto.AudioContent_MimeType(n)]
- return ok
- })
- })
- t.Run("VideoContent_MimeType", func(t *testing.T) {
- assertMimeCoverage(t, proto.VideoContent_MimeType(0).Descriptor(), func(n int32) bool {
- _, ok := videoMimeToString[proto.VideoContent_MimeType(n)]
- return ok
- })
- })
- t.Run("DocumentContent_MimeType", func(t *testing.T) {
- assertMimeCoverage(t, proto.DocumentContent_MimeType(0).Descriptor(), func(n int32) bool {
- _, ok := documentMimeToString[proto.DocumentContent_MimeType(n)]
- return ok
- })
- })
-}
-
-func assertMimeCoverage(t *testing.T, desc protoreflect.EnumDescriptor, has func(int32) bool) {
- t.Helper()
- var missing []string
- values := desc.Values()
- for i := 0; i < values.Len(); i++ {
- v := values.Get(i)
- if int32(v.Number()) == 0 {
- continue // UNSPECIFIED; intentionally not mapped
- }
- if !has(int32(v.Number())) {
- missing = append(missing, string(v.Name()))
- }
- }
- if len(missing) > 0 {
- t.Errorf("mime_map missing wire-string entries for: %v (add the wire MIME string to the corresponding forward map in mime_map.go)", missing)
- }
-}
diff --git a/internal/experimental/agent/a2a.go b/internal/experimental/agent/a2a.go
deleted file mode 100644
index 1fd5b8e..0000000
--- a/internal/experimental/agent/a2a.go
+++ /dev/null
@@ -1,313 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package agent
-
-import (
- "context"
- "errors"
- "fmt"
- "strings"
-
- "github.com/a2aproject/a2a-go/v2/a2a"
- "github.com/a2aproject/a2a-go/v2/a2aclient"
- "github.com/a2aproject/a2a-go/v2/a2aclient/agentcard"
- "github.com/google/ax/internal/agent"
- "github.com/google/ax/internal/auth"
- "github.com/google/ax/internal/experimental/a2abridge"
- "github.com/google/ax/proto"
-)
-
-// A2AAgentConfig is the per-agent configuration needed to construct an
-// A2AAgent.
-//
-// Stateless controls how the bridge composes outgoing A2A messages:
-//
-// - false (default, "stateful"): the bridge sends only the new user
-// input each turn and relies on the agent server using contextId to
-// load conversation history from its own session store. This matches
-// the A2A protocol convention.
-//
-// - true: the bridge sends the full AX message history on every call.
-// Use this when targeting an A2A agent that does not maintain its
-// own per-context state.
-type A2AAgentConfig struct {
- ID string
- Address string
- Auth auth.Auth
- Headers auth.Headers
- Stateless bool
- OverrideCardHosts bool
-}
-
-// A2AAgent bridges AX's Agent interface to an A2A-protocol agent.
-type A2AAgent struct {
- id string
- client *a2aclient.Client
- card *a2a.AgentCard
- stateless bool
-}
-
-func NewA2AAgent(ctx context.Context, config A2AAgentConfig) (*A2AAgent, error) {
- if config.Address == "" {
- return nil, errors.New("a2a agent: address is required")
- }
-
- addr := config.Address
- if !strings.Contains(addr, "://") {
- addr = "http://" + addr
- }
-
- card, err := agentcard.DefaultResolver.Resolve(ctx, addr)
- if err != nil {
- return nil, fmt.Errorf("a2a agent %s: resolve AgentCard: %w", config.ID, err)
- }
-
- if config.OverrideCardHosts {
- if err := a2abridge.OverrideCardHosts(card, addr); err != nil {
- return nil, fmt.Errorf("a2a agent %s: %w", config.ID, err)
- }
- }
-
- interceptor, err := a2abridge.NewInterceptor(card, config.Auth, config.Headers)
- if err != nil {
- return nil, fmt.Errorf("a2a agent %s: %w", config.ID, err)
- }
-
- var opts []a2aclient.FactoryOption
- if interceptor != nil {
- opts = append(opts, a2aclient.WithCallInterceptors(interceptor))
- }
-
- client, err := a2aclient.NewFromCard(ctx, card, opts...)
- if err != nil {
- return nil, fmt.Errorf("a2a agent %s: create client: %w", config.ID, err)
- }
-
- return &A2AAgent{
- id: config.ID,
- client: client,
- card: card,
- stateless: config.Stateless,
- }, nil
-}
-
-// Card returns the resolved AgentCard for this agent.
-func (a *A2AAgent) Card() *a2a.AgentCard {
- return a.card
-}
-
-// Connect bridges one AX execution to one A2A operation.
-//
-// Two paths:
-//
-// 1. Resume an existing in-flight task.
-// This covers HITL continuation: the user has supplied an answer to a
-// ConfirmationContent we previously emitted.
-//
-// 2. New A2A operation.
-func (a *A2AAgent) Connect(
- ctx context.Context,
- conversationID string,
- execID string,
- start *proto.AgentStart,
- e agent.Executor,
- o agent.OutputHandler,
-) error {
- // Compute the planner's ToolCallID for this delegation.
- // Empty when the A2A agent is invoked directly.
- toolCallID := a2abridge.FindToolCallID(a.id, start.Messages)
-
- // Recover any persisted state from prior calls on this exec_id.
- markerConv, activeTaskID, recoveredEmitted, found := a2abridge.RecoverA2AState(start.Messages)
- if found && markerConv != conversationID {
- found = false
- activeTaskID = ""
- recoveredEmitted = nil
- }
-
- if found && activeTaskID != "" {
- return a.resumeTask(ctx, conversationID, toolCallID, a2a.TaskID(activeTaskID), recoveredEmitted, start, o)
- }
- return a.newOperation(ctx, conversationID, toolCallID, start, o)
-}
-
-// Resumes an in-flight task. It checks the server-side state via GetTask
-// and either continues a HITL flow, picks up completed artifacts, surfaces
-// a failure, or resumes streaming for a still-active task.
-func (a *A2AAgent) resumeTask(
- ctx context.Context,
- conversationID string,
- toolCallID string,
- taskID a2a.TaskID,
- recoveredEmitted []string,
- start *proto.AgentStart,
- o agent.OutputHandler,
-) error {
- task, err := a.client.GetTask(ctx, &a2a.GetTaskRequest{ID: taskID})
- if err != nil {
- // If the server has dropped the task (TTL, admin action, etc.)
- // the marker is stale: clear it so the next exec starts fresh,
- // then surface the situation as an explicit error.
- if errors.Is(err, a2a.ErrTaskNotFound) {
- _ = a2abridge.ClearStateMarker(conversationID, o)
- return fmt.Errorf("a2a agent %s: task %s no longer exists on server (state marker cleared; retry to start a new operation)", a.id, taskID)
- }
- return fmt.Errorf("a2a agent %s: GetTask(%s): %w", a.id, taskID, err)
- }
-
- switch task.Status.State {
- case a2a.TaskStateCompleted:
- // Task already done on the server side; emit any artifacts the
- // client hasn't seen yet, then drop the now-stale marker.
- if err := a2abridge.EmitTaskArtifacts(task, o); err != nil {
- return err
- }
- return a2abridge.ClearStateMarker(conversationID, o)
-
- case a2a.TaskStateFailed, a2a.TaskStateCanceled, a2a.TaskStateRejected:
- _ = a2abridge.ClearStateMarker(conversationID, o)
- return fmt.Errorf("a2a agent %s: task %s ended with state %s", a.id, taskID, task.Status.State)
-
- case a2a.TaskStateAuthRequired:
- // Server is asking for refreshed credentials. Now returns an error.
- // TODO(wjjclaud): implement credential refresh.
- _ = a2abridge.ClearStateMarker(conversationID, o)
- return a2abridge.AuthRequiredError(a.id, taskID, task.Status.Message)
-
- case a2a.TaskStateInputRequired:
- // HITL: scan the resumed history for an answer to the
- // confirmation we previously emitted. If the user has answered,
- // forward to the same A2A task; if not, re-emit the confirmation
- // prompt so the client sees it again.
- matchID := toolCallID
- if matchID == "" {
- matchID = string(taskID)
- }
- answered, approved := a2abridge.FindConfirmationAnswer(start.Messages, matchID)
- if !answered {
- return a2abridge.EmitConfirmation(conversationID, toolCallID, taskID, task, recoveredEmitted, o)
- }
- return a.sendFollowUp(ctx, conversationID, toolCallID, taskID, approved, o)
-
- default:
- // Working / Submitted: subscribe back to the
- // task's event stream and process events normally.
- return a.subscribeAndProcess(ctx, conversationID, toolCallID, taskID, recoveredEmitted, o)
- }
-}
-
-// Handles a fresh A2A operation. It sends the AX messages to the agent and
-// processes the resulting event stream.
-//
-// The outgoing message depends on the agent's mode:
-//
-// - Stateful (default): only the latest user-input parts are sent.
-// The agent server is expected to reconstruct prior conversation
-// context from contextId via its own session store.
-//
-// - Stateless: the full AX history is sent every turn. Necessary
-// for agents that do not maintain their own per-context state.
-func (a *A2AAgent) newOperation(
- ctx context.Context,
- conversationID string,
- toolCallID string,
- start *proto.AgentStart,
- o agent.OutputHandler,
-) error {
- var parts []*a2a.Part
- if a.stateless {
- parts = a2abridge.MessagesToA2AParts(start.Messages)
- } else {
- parts = a2abridge.LatestUserInputParts(start.Messages)
- }
- if len(parts) == 0 {
- return fmt.Errorf("a2a agent %s: no user-input parts to send", a.id)
- }
-
- msg := &a2a.Message{
- ID: a2a.NewMessageID(),
- ContextID: conversationID,
- Role: a2a.MessageRoleUser,
- Parts: parts,
- }
- // SendStreamingMessage auto-falls-back to non-streaming SendMessage
- // when the agent does not support streaming. a2abridge.IterateStream
- // consumes both shapes uniformly.
- stream := a.client.SendStreamingMessage(ctx, &a2a.SendMessageRequest{Message: msg})
- return a2abridge.IterateStream(ctx, a.client, a.id, conversationID, toolCallID, stream, o)
-}
-
-// sendFollowUp sends the user's reply (yes/no) to a paused HITL task and
-// processes the subsequent event stream.
-func (a *A2AAgent) sendFollowUp(
- ctx context.Context,
- conversationID string,
- toolCallID string,
- taskID a2a.TaskID,
- approved bool,
- o agent.OutputHandler,
-) error {
- answer := "yes"
- if !approved {
- answer = "no"
- }
- msg := &a2a.Message{
- ID: a2a.NewMessageID(),
- ContextID: conversationID,
- TaskID: taskID,
- Role: a2a.MessageRoleUser,
- Parts: []*a2a.Part{a2a.NewTextPart(answer)},
- }
- stream := a.client.SendStreamingMessage(ctx, &a2a.SendMessageRequest{Message: msg})
- return a2abridge.IterateStream(ctx, a.client, a.id, conversationID, toolCallID, stream, o)
-}
-
-// subscribeAndProcess re-subscribes to a task's event stream (for resuming a
-// task that was still working when the bridge previously disconnected).
-//
-// toolCallID is passed through so that any HITL emitted via the resumed
-// stream uses the planner's ToolCallID for ConfirmationContentID.
-//
-// alreadyEmitted is forwarded to a2abridge.PollUntilTerminal for dedup
-// seeding when we fall back to polling.
-func (a *A2AAgent) subscribeAndProcess(
- ctx context.Context,
- conversationID string,
- toolCallID string,
- taskID a2a.TaskID,
- alreadyEmitted []string,
- o agent.OutputHandler,
-) error {
- if a.card != nil && a.card.Capabilities.Streaming {
- stream := a.client.SubscribeToTask(ctx, &a2a.SubscribeToTaskRequest{ID: taskID})
- return a2abridge.IterateStream(ctx, a.client, a.id, conversationID, toolCallID, stream, o)
- }
- return a2abridge.PollUntilTerminal(ctx, a.client, a.id, conversationID, toolCallID, taskID, nil, alreadyEmitted, o)
-}
-
-// HealthCheck performs a lightweight call to verify the agent is reachable.
-// Uses GetExtendedAgentCard which is supported by all A2A-compliant agents.
-func (a *A2AAgent) HealthCheck(ctx context.Context) error {
- _, err := a.client.GetExtendedAgentCard(ctx, &a2a.GetExtendedAgentCardRequest{})
- return err
-}
-
-// Close releases the underlying A2A client's resources.
-func (a *A2AAgent) Close() error {
- if a.client == nil {
- return nil
- }
- return a.client.Destroy()
-}