feat: serve Executions over A2A with a pre-approved /generate

Increment 7 of .scratch/solution-architect-agent/spec.md.

- app/assembly.py: composition root building the engine from settings
  and the provider bundle (roles, ADK runtime, MCP catalog, Terraform
  tools, checkpointer, recorder).
- app/a2a: a2a-sdk 1.1 JSON-RPC server (v0.3 compatible) mapping tasks to
  Executions; questions, Approvals and permissions pause as
  input-required; Approvals accepted only as structured data; completed
  tasks return the guide and code as artifacts; agent card derived from
  the dependency graph.
- POST /generate runs a pre-approved Execution with the legacy keys.
- Specialist exceptions are relayed to the user; Orchestrator exceptions
  fail the task. Engine accepts a caller-chosen execution id.
- Dockerfile installs checksum-verified Terraform and ships agents,
  providers and skills; add mcp and a2a-sdk requirements.
- 17 new tests; full suite 206 passed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-16 10:23:24 +01:00
parent ed104e5697
commit ad371b2ec4
19 changed files with 1116 additions and 3 deletions

1
app/a2a/__init__.py Normal file
View File

@@ -0,0 +1 @@
"""A2A interface for interactive Executions (A2A 1.0, with v0.3 compatibility)."""

66
app/a2a/card.py Normal file
View File

@@ -0,0 +1,66 @@
"""The A2A agent card, derived from the dependency graph and settings."""
from __future__ import annotations
from a2a.types import (
AgentCapabilities,
AgentCard,
AgentInterface,
AgentProvider,
AgentSkill,
)
from app.config import Settings
from app.execution.deliverables import PHASE_ORDER, deliverables_in
A2A_PATH = "/a2a"
def build_agent_card(settings: Settings) -> AgentCard:
base_url = (
settings.A2A_PUBLIC_URL or f"http://{settings.A2A_HOST}:{settings.A2A_PORT}"
).rstrip("/")
phases = "; ".join(
f"{phase.value}: {', '.join(kind.value for kind in deliverables_in(phase))}"
for phase in PHASE_ORDER
)
return AgentCard(
name=settings.AGENT_NAME,
description=(
"Designs a cloud solution architecture with you: requirements discovery, "
"grounded product selection, diagram, design recommendations, "
"infrastructure-as-code and dry-run validation, packaged as a solution "
f"guide. Cloud provider: {settings.CLOUD_PROVIDER}."
),
version=settings.AGENT_VERSION,
provider=AgentProvider(
organization="Kyndryl Agent Builder", url="https://www.kyndryl.com"
),
supported_interfaces=[
AgentInterface(
url=f"{base_url}{A2A_PATH}",
protocol_binding="JSONRPC",
protocol_version="1.0",
)
],
capabilities=AgentCapabilities(streaming=True, push_notifications=False),
default_input_modes=["text/plain", "application/json"],
default_output_modes=["text/plain", "text/markdown", "application/json"],
skills=[
AgentSkill(
id="solution-architecture",
name="Cloud solution architecture",
description=(
"Interactive, multi-turn engagement. Phases and their Deliverables: "
f"{phases}. Each Phase needs your approval, sent as data."
),
tags=["architecture", "cloud", settings.CLOUD_PROVIDER, "terraform"],
examples=[
"Design a regional event ingestion platform on Google Cloud.",
"Migrate our on-premises order service to managed services.",
],
input_modes=["text/plain", "application/json"],
output_modes=["text/plain", "text/markdown", "application/json"],
)
],
)

146
app/a2a/executor.py Normal file
View File

@@ -0,0 +1,146 @@
"""Maps A2A tasks onto Executions: a task is an Execution, its context is the Session.
A new task starts an Execution; a message on an input-required task answers the
Execution's prompt. Approvals and permissions count only as structured data parts,
never as free text.
"""
from __future__ import annotations
import logging
from collections.abc import Mapping
from typing import Any
from a2a.helpers.proto_helpers import (
get_data_parts,
new_data_part,
new_task,
new_text_part,
)
from a2a.server.agent_execution import AgentExecutor, RequestContext
from a2a.server.events import EventQueue
from a2a.server.tasks import TaskUpdater
from a2a.types import TaskState
from google.protobuf import json_format
from app.execution.deliverables import DeliverableKind
from app.execution.engine import ExecutionEngine, Interaction
from app.execution.graph import GUIDE_FILENAME
from app.execution.presentation import describe_prompt
logger = logging.getLogger(__name__)
STRUCTURED_REPLY_KEYS = ("approval", "permission")
class SolutionArchitectExecutor(AgentExecutor):
def __init__(self, engine: ExecutionEngine) -> None:
self._engine = engine
async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
task_id = context.task_id or ""
updater = TaskUpdater(event_queue, task_id, context.context_id or "")
try:
if context.current_task is None:
history = [context.message] if context.message is not None else []
await event_queue.enqueue_event(
new_task(
task_id,
context.context_id or "",
TaskState.TASK_STATE_SUBMITTED,
history=history,
)
)
await updater.start_work()
options = _options(context)
interaction = await self._engine.start(
context.get_user_input(),
session_id=context.context_id,
execution_id=task_id,
pre_approved=bool(options.get("pre_approved", False)),
allow_cloud_read=options.get("allow_cloud_read"),
)
else:
await updater.start_work()
interaction = await self._engine.resume(task_id, _reply(context))
except Exception as exc:
logger.exception("Execution %s failed", task_id)
await updater.failed(
updater.new_agent_message(
[
new_text_part(
f"The Execution failed: {type(exc).__name__}: {exc}"
)
]
)
)
return
await self._publish(interaction, updater)
async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
# The checkpoint stays; cancelling only ends the A2A task.
updater = TaskUpdater(
event_queue, context.task_id or "", context.context_id or ""
)
await updater.cancel()
async def _publish(self, interaction: Interaction, updater: TaskUpdater) -> None:
if interaction.status == "awaiting_user" and interaction.prompt is not None:
prompt = dict(interaction.prompt)
await updater.requires_input(
updater.new_agent_message(
[
new_text_part(describe_prompt(prompt)),
new_data_part({"prompt": prompt}),
]
)
)
return
deliverables: Mapping[str, Mapping[str, Any]] = interaction.state.get(
"deliverables", {}
)
guide = deliverables.get(DeliverableKind.SOLUTION_GUIDE.value)
if guide:
await updater.add_artifact(
[new_text_part(guide["content"], media_type="text/markdown")],
name=GUIDE_FILENAME,
)
for kind, deliverable in deliverables.items():
for name, content in deliverable.get("attachments", {}).items():
await updater.add_artifact(
[new_text_part(content)], name=name, metadata={"deliverable": kind}
)
warnings = list(interaction.state.get("warnings", []))
summary = (
"The solution architecture is complete and approved."
if interaction.status == "completed"
else "The Execution ended with warnings: " + "; ".join(warnings)
)
await updater.complete(
updater.new_agent_message(
[
new_text_part(summary),
new_data_part({"status": interaction.status, "warnings": warnings}),
]
)
)
def _options(context: RequestContext) -> dict[str, Any]:
options: dict[str, Any] = {}
if context.message is not None and context.message.HasField("metadata"):
options.update(json_format.MessageToDict(context.message.metadata))
options.update(context.metadata)
return options
def _reply(context: RequestContext) -> dict[str, Any]:
if context.message is not None:
for data in get_data_parts(list(context.message.parts)):
if isinstance(data, Mapping) and any(
k in data for k in STRUCTURED_REPLY_KEYS
):
return {k: data[k] for k in STRUCTURED_REPLY_KEYS if k in data}
return {"reply": context.get_user_input()}

125
app/a2a/server.py Normal file
View File

@@ -0,0 +1,125 @@
"""The A2A server: JSON-RPC at /a2a, the agent card, health, and pre-approved /generate.
Run with: python -m app.a2a.server
"""
from __future__ import annotations
import logging
from collections.abc import AsyncIterator, Callable
from contextlib import AbstractAsyncContextManager, asynccontextmanager
import click
import uvicorn
from a2a.server.request_handlers.default_request_handler_v2 import (
DefaultRequestHandlerV2,
)
from a2a.server.routes.agent_card_routes import create_agent_card_routes
from a2a.server.routes.jsonrpc_routes import create_jsonrpc_routes
from a2a.server.tasks import InMemoryTaskStore
from a2a.utils.constants import AGENT_CARD_WELL_KNOWN_PATH
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route
from app.a2a.card import A2A_PATH, build_agent_card
from app.a2a.executor import SolutionArchitectExecutor
from app.assembly import Assembly, open_assembly
from app.config import Settings, get_settings
from app.execution.presentation import to_generate_response
logger = logging.getLogger(__name__)
AssemblyFactory = Callable[[Settings], AbstractAsyncContextManager[Assembly]]
LEGACY_CARD_PATH = "/.well-known/agent.json"
def create_app(
settings: Settings | None = None,
assembly_factory: AssemblyFactory = open_assembly,
) -> Starlette:
settings = settings or get_settings()
card = build_agent_card(settings)
async def health(request: Request) -> JSONResponse:
assembly: Assembly = request.app.state.assembly
return JSONResponse(
{
"status": "healthy",
"agent": settings.AGENT_NAME,
"version": settings.AGENT_VERSION,
"cloud_provider": assembly.bundle.name,
"mcp_discovery_gaps": assembly.mcp_gaps,
}
)
async def generate(request: Request) -> JSONResponse:
"""Pre-approved, one-shot Execution for batch and evaluation callers."""
assembly: Assembly = request.app.state.assembly
try:
body = await request.json()
except ValueError:
body = {}
workflow_request = str(body.get("request") or "").strip()
if not workflow_request:
return JSONResponse({"error": "'request' is required"}, status_code=400)
try:
interaction = await assembly.engine.start(
workflow_request,
session_id=body.get("session_id"),
pre_approved=True,
allow_cloud_read=bool(body.get("allow_cloud_read", False)),
)
except Exception as exc:
logger.exception("/generate failed")
return JSONResponse(
{"error": f"{type(exc).__name__}: {exc}"}, status_code=500
)
return JSONResponse(to_generate_response(interaction, assembly.roles))
@asynccontextmanager
async def lifespan(app: Starlette) -> AsyncIterator[None]:
async with assembly_factory(settings) as assembly:
handler = DefaultRequestHandlerV2(
agent_executor=SolutionArchitectExecutor(assembly.engine),
task_store=InMemoryTaskStore(),
agent_card=card,
)
app.state.assembly = assembly
app.state.request_handler = handler
app.router.routes.extend(
create_jsonrpc_routes(handler, A2A_PATH, enable_v0_3_compat=True)
)
try:
yield
finally:
await handler.aclose()
return Starlette(
routes=[
Route("/health", health, methods=["GET"]),
Route("/generate", generate, methods=["POST"]),
*create_agent_card_routes(card, card_url=AGENT_CARD_WELL_KNOWN_PATH),
*create_agent_card_routes(card, card_url=LEGACY_CARD_PATH),
],
lifespan=lifespan,
)
@click.command()
@click.option("--host", default=None, help="Host to bind (default A2A_HOST)")
@click.option("--port", default=None, type=int, help="Port (default A2A_PORT)")
def main(host: str | None, port: int | None) -> None:
"""Serve the solution architect agent over A2A."""
settings = get_settings()
logging.basicConfig(level=settings.LOG_LEVEL.upper())
uvicorn.run(
create_app(settings),
host=host or settings.A2A_HOST,
port=port or settings.A2A_PORT,
)
if __name__ == "__main__":
main()