Agent-to-Agent Protocols › A worked example: an in-memory cooperative task exchange
Language AI HandbookAll chapters A local summarizer accepts a note in text form. It pauses to ask which format the caller wants, then the worker advances explicitly one step at a time. This lets us control the order of cancellation and completion without relying on clocks or network delays. The model of the worker is a finite state machine. Its results use immutable dataclasses so snapshots and events saved earlier remain valid when the worker changes state. The class interfaces are Python fixtures and are not serialized as A2A wire messages.
PythonIn [8]Expand
from dataclasses import dataclass, replace
from enum import Enum
from typing import Literal
class State(str, Enum):
SUBMITTED = "submitted"
INPUT_REQUIRED = "input-required"
WORKING = "working"
COMPLETED = "completed"
CANCELED = "canceled"
TERMINAL = {State.COMPLETED, State.CANCELED}
Format = Literal["text/plain", "application/json"]PythonIn [9]Expand
@dataclass(frozen=True)
class Skill:
skill_id: str
input_mode: str
output_modes: tuple[Format, ...]
@dataclass(frozen=True)
class Card:
name: str
skills: tuple[Skill, ...]
@dataclass(frozen=True)
class Submission:
message_id: str
skill_id: str
note: str
@dataclass(frozen=True)
class Summary:
text: str
word_count: int
@dataclass(frozen=True)
class Artifact:
artifact_id: str
media_type: Format
content: str | SummaryPythonIn [10]Expand
@dataclass(frozen=True)
class Task:
task_id: str
context_id: str
state: State
submitted: Submission
question: str | None = None
output_format: Format | None = None
artifacts: tuple[Artifact, ...] = ()
@dataclass(frozen=True)
class StatusEvent:
task_id: str
state: State
question: str | None
@dataclass(frozen=True)
class ArtifactEvent:
task_id: str
artifact: ArtifactThe card advertises the shapes we know how to handle. A Submission is the first caller message, with its own identifier. Task represents the remote record, with a different identifier. StatusEvent may carry a question. ArtifactEvent carries a typed piece of output. In this local fixture a structured summary is a Python object, not a string containing JSON. The Internet-facing interface would need a binding that serializes the equivalent data.
The remote agent: discovery and task handling
The worker keeps a map from accepted message IDs to tasks. This mock has one caller. A production service may have to scope those keys to an authenticated client or tenant. Putting the task ID and initial message ID in separate fields lets the caller replay an initial send even when the first response was lost. On a replay with changed contents, the original task remains unchanged and the worker raises an error.
The worker accepts three explicitly ordered steps in this fixture. request_format moves a submitted task to an interruption. answer accepts a supported format and moves it to working. finish publishes one artifact before storing the completed state. Keeping answer and finish distinct leaves a real working state in which cancellation can win. A status read by itself has no effect on the work.
PythonIn [11]Expand
class Worker:
def __init__(self, card: Card) -> None:
self.card = card
self.tasks: dict[str, Task] = {}
self.message_to_task: dict[str, str] = {}
self.events: list[StatusEvent | ArtifactEvent] = []
self.sequence = 0
def commit(self, task: Task) -> Task:
self.tasks[task.task_id] = task
self.events.append(StatusEvent(task.task_id, task.state, task.question))
return task
def get(self, task_id: str) -> Task:
return self.tasks[task_id]
def submit(self, message: Submission) -> Task:
existing_id = self.message_to_task.get(message.message_id)
if existing_id is not None:
existing = self.get(existing_id)
if message != existing.submitted:
raise ValueError("message ID reused with different contents")
return existing
if not any(
skill.skill_id == message.skill_id for skill in self.card.skills
):
raise ValueError("skill is not advertised")
self.sequence += 1
task = Task(
f"task-{self.sequence}",
f"context-{self.sequence}",
State.SUBMITTED,
message,
)
self.message_to_task[message.message_id] = task.task_id
return self.commit(task)
def request_format(self, task_id: str) -> Task:
task = self.get(task_id)
if task.state is not State.SUBMITTED:
return task
question = "Return a short text note or a structured summary?"
return self.commit(
replace(task, state=State.INPUT_REQUIRED, question=question)
)
def answer(self, task_id: str, output_format: Format) -> Task:
task = self.get(task_id)
if task.state in TERMINAL:
return task
if task.state is not State.INPUT_REQUIRED:
raise ValueError("task is not waiting for an answer")
skill = next(
s for s in self.card.skills if s.skill_id == task.submitted.skill_id
)
if output_format not in skill.output_modes:
raise ValueError("format is not advertised for this skill")
return self.commit(
replace(
task,
state=State.WORKING,
question=None,
output_format=output_format,
)
)
def finish(self, task_id: str) -> Task:
task = self.get(task_id)
if task.state is not State.WORKING:
return task
words = task.submitted.note.split()
short = " ".join(words[:4])
output_format = task.output_format
assert output_format is not None
body = (
Summary(short, len(words))
if output_format == "application/json"
else short
)
artifact = Artifact(f"result-{task_id}", output_format, body)
self.events.append(ArtifactEvent(task_id, artifact))
return self.commit(
replace(task, state=State.COMPLETED, artifacts=(artifact,))
)
def cancel(self, task_id: str) -> Task:
task = self.get(task_id)
if task.state in TERMINAL:
return task
return self.commit(replace(task, state=State.CANCELED, question=None))The separate event types make a useful invariant testable. The event log records publication of the result before the terminal status for this worker. Readers can check at the same time that canceled work has no new output and that terminal snapshots do not change. The implementation makes these updates in one process with sequential operations. A concurrent production service would need to protect the state transition and result publication together against other workers or persist both with a defined recovery rule.
The caller agent: discovery, delegation, and draining
Selection in this mock uses an exact skill ID plus input and output media types. It fails before submission when the caller cannot find a match. This demonstrates a contract check without pretending to establish the quality of the remote summarizer. The caller keeps the assigned task ID, polls the worker, and answers the one question needed by this policy.
PythonIn [12]Expand
def choose_skill(
card: Card, skill_id: str, input_mode: str, output_mode: Format
) -> Skill:
for skill in card.skills:
if (
skill.skill_id == skill_id
and skill.input_mode == input_mode
and output_mode in skill.output_modes
):
return skill
raise LookupError("no matching skill and media-type combination")PythonIn [13]Expand
def observe_until_terminal(
worker: Worker, task_id: str, output_format: Format, max_checks: int = 4
) -> Task:
for _ in range(max_checks):
current = worker.get(task_id)
if current.state in TERMINAL:
return current
if current.state is State.SUBMITTED:
worker.request_format(task_id)
elif current.state is State.INPUT_REQUIRED:
worker.answer(task_id, output_format)
elif current.state is State.WORKING:
worker.finish(task_id)
raise TimeoutError("the caller exhausted its local observation budget")Driving the mock worker from the caller's loop makes the example deterministic. In a deployed system the worker would progress separately, while a client polls or subscribes and sends a follow-up when needed. Here the budget counts reads. In the happy path the loop makes three progress operations and then one final read that observes completion. A budget of four permits those four reads, while a budget of one only observes the initial submitted snapshot before asking for the format. Reaching that budget reports a local timeout and does not silently assign a remote failure or cancel the task. That distinction also gives tests a way to inspect the unfinished state.
Running the happy path
We have the note “New reading room opens next Monday after inspection.” The first four words make a deterministic summary. Counting all words gives the structured artifact one additional field. A real summarization agent would use a model or another policy and need its own quality checks. The notebook checks this simple policy end to end so that delivery and state transitions are easy to verify.
PythonIn [14]Expand
card = Card(
"Notebook summarizer",
(Skill("summarize", "text/plain", ("text/plain", "application/json")),),
)
chosen = choose_skill(card, "summarize", "text/plain", "application/json")
message = Submission(
"message-1",
chosen.skill_id,
"New reading room opens next Monday after inspection.",
)
happy = Worker(card)
initial = happy.submit(message)
completed = observe_until_terminal(happy, initial.task_id, "application/json")
assert initial.state is State.SUBMITTED
assert completed.state is State.COMPLETED
assert completed.artifacts[0].content == Summary("New reading room opens", 8)
assert isinstance(happy.events[-2], ArtifactEvent)
assert isinstance(happy.events[-1], StatusEvent)ConsoleOut [15]Expand
Matched skill: summarize Task and context: task-1 context-1 Status events: ['submitted', 'input-required', 'working', 'completed'] Artifact media type: application/json Artifact content: Summary(text='New reading room opens', word_count=8)
The ordering of the worker's log shows the interruption and the later working and completed states. The returned structured summary is a separate value. Its contents could be wrong even when the worker accurately reports that it finished. In a production integration validate the shape and the result's suitability for the application.
Idempotent retry
Send the same message twice and check that the worker stores a single task. The response to the first send and second send can differ if work progressed in between. The promise is that they refer to the same task, and that retry does not submit work again. The assertion compares ID and number of state changes rather than relying on Python object identity.
PythonIn [16]Expand
retry_worker = Worker(card)
first = retry_worker.submit(message)
retry_worker.request_format(first.task_id)
second = retry_worker.submit(message)
assert first.task_id == second.task_id
assert first.state is State.SUBMITTED and second.state is State.INPUT_REQUIRED
assert len(retry_worker.tasks) == 1 and len(retry_worker.events) == 2
try:
retry_worker.submit(replace(message, note="Different content"))
except ValueError as conflict:
conflict_message = str(conflict)
else:
raise AssertionError("a changed request cannot reuse the same ID")
new = retry_worker.submit(replace(message, message_id="message-2"))
assert new.task_id != first.task_id and new.context_id != first.context_idConsoleOut [17]Expand
Retry refers to: task-1 task-1 Latest state on retry: input-required Conflicting reuse: message ID reused with different contents A fresh message starts: task-2 context-2
A different message identifier starts separate work in this fixture even if the note text is identical. It also gets a distinct context here because the mock has no multi-task conversation. The real protocol distinguishes context identity from task identity and permits related tasks to share one context. In this implementation only the initial local submit is deduplicated, and its mapping is process memory. A restart or another worker would require a shared durable idempotency policy to offer the same guarantee.
The cancel race, deterministically
In both cases the worker enters working before the race. First run the worker to completion and request a late cancel. Then cancel the working task in a fresh worker and try to finish it afterward. Both sequences use the same policy and the same input. Only the order of the two terminal operations differs.
PythonIn [18]Expand
def working_task() -> tuple[Worker, str]:
worker = Worker(card)
task_id = worker.submit(message).task_id
worker.request_format(task_id)
worker.answer(task_id, "application/json")
return worker, task_id
finish_first, a_id = working_task()
first_finished = finish_first.finish(a_id)
a_final = finish_first.cancel(a_id)
cancel_first, b_id = working_task()
first_canceled = cancel_first.cancel(b_id)
b_final = cancel_first.finish(b_id)
assert a_final == first_finished and a_final.state is State.COMPLETED
assert b_final == first_canceled and b_final.state is State.CANCELED
assert len(a_final.artifacts) == 1 and b_final.artifacts == ()
assert all(
not isinstance(event, ArtifactEvent) for event in cancel_first.events
)
assert cancel_first.answer(b_id, "text/plain") == b_finalPythonIn [19]Expand
limited = Worker(card)
limited_id = limited.submit(message).task_id
try:
observe_until_terminal(
limited, limited_id, "application/json", max_checks=1
)
except TimeoutError as expiry:
limit_message = str(expiry)
else:
raise AssertionError("one observation cannot complete the fixture")
assert limited.get(limited_id).state is State.INPUT_REQUIREDConsoleOut [20]Expand
Completion commits first: completed 1 artifact Cancel commits first: canceled 0 artifacts Local deadline: the caller exhausted its local observation budget Remote state remains: input-required
A late operation returns the saved terminal state in this mock. The versioned A2A cancel operation can return a not-cancelable error instead, so a real client reconciles with the authoritative task state. The last printed case distinguishes the local observation budget from the remote task state. It lets the caller stop waiting without claiming the remote work has ended.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!