This commit is contained in:
146
app/a2a_server.py
Normal file
146
app/a2a_server.py
Normal 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.agent import ExecutionEngine, Interaction
|
||||
from app.nodes.execution_nodes import GUIDE_FILENAME
|
||||
from app.presentation import describe_prompt
|
||||
from app.workflows.deliverables import DeliverableKind
|
||||
|
||||
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()}
|
||||
Reference in New Issue
Block a user