The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(a2a): a resend without a contextId reopens its context and spends no turn
Erosika11f90272424e
diff --git a/plugins/platforms/a2a/adapter.py b/plugins/platforms/a2a/adapter.pyindex 4a9f810a829..e5da9db2eb7 100644--- a/plugins/platforms/a2a/adapter.py+++ b/plugins/platforms/a2a/adapter.py@@ -16,7 +16,7 @@ import threadingimport timeimport urllib.parseimport urllib.request-from collections import deque+from collections import OrderedDict, dequefrom concurrent.futures import Futurefrom concurrent.futures import TimeoutError as FuturesTimeoutfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServer@@ -274,6 +274,8 @@ class A2AAdapter(BasePlatformAdapter):self._pending_order: Dict[str, deque[str]] = {}# Request ownership outlives reply Futures and also covers synchronous profile forwards.self._active_tasks: set[str] = set()+ # Admission ids this process already forwarded; a resend of one is a retry, not a new turn.+ self._forwarded_inputs: "OrderedDict[str, None]" = OrderedDict()self._pending_lock = threading.Lock()@property@@ -464,6 +466,18 @@ class A2AAdapter(BasePlatformAdapter):with self._pending_lock:self._active_tasks.add(task_id)+ _MAX_FORWARDED_INPUTS = 1000++ def _note_forwarded_input(self, input_id: str) -> bool:+ """Record a forwarded admission id; True when this process already sent it (a retry)."""+ with self._pending_lock:+ seen = input_id in self._forwarded_inputs+ self._forwarded_inputs[input_id] = None+ self._forwarded_inputs.move_to_end(input_id)+ while len(self._forwarded_inputs) > self._MAX_FORWARDED_INPUTS:+ self._forwarded_inputs.popitem(last=False)+ return seen+def _pop_pending(self, task_id: str) -> None:with self._pending_lock:self._active_tasks.discard(task_id)@@ -503,9 +517,20 @@ class A2AAdapter(BasePlatformAdapter):(terminal_task, None) when it ends immediately, else (None, pending) with the future to wait on."""agent = agent or self._agents[""]text = protocol.extract_text(params)- context_id = protocol.extract_context_id(params) or protocol.new_context_id()+ forwarded = not agent.get("local", True)+ message_id = protocol.extract_message_id(params) if forwarded else ""+ context_id = protocol.extract_context_id(params)+ if not context_id:+ # A retry of a first send repeats the messageId and omits the contextId it never received.+ scope = "\0".join((*self._scope_for_agent(agent), peer))+ context_id = protocol.message_context_id(scope, message_id) if message_id else protocol.new_context_id()+ # A retry after a timeout must find its accepted work, not queue a second turn.+ input_id = ("a2a-msg:" + hashlib.sha256(f"{context_id}\0{message_id}".encode()).hexdigest()+ if message_id else None)+ retry = input_id is not None and self._note_forwarded_input(input_id)task_id = protocol.new_task_id()- turn = self._turns.track(context_id)+ # The owner answers a resend from the accepted admission; it is not another turn of the loop.+ turn = 0 if retry else self._turns.track(context_id)max_turns = protocol.max_pingpong_turns()rec = self.tasks.create(task_id, context_id, peer, *self._scope_for_agent(agent))if turn > max_turns:@@ -517,17 +542,14 @@ class A2AAdapter(BasePlatformAdapter):return self._end_task(rec, protocol.STATE_REJECTED, "Empty task — nothing to do.")framed = security.wrap_inbound(peer, text)security.audit("inbound", peer, task_id, text)- protocol.persist_message(context_id, "user", text, task_id)- protocol.metrics.inbound_total += 1+ if not retry:+ protocol.persist_message(context_id, "user", text, task_id)+ protocol.metrics.inbound_total += 1self._register_inline_push(task_id, params, agent=agent)- if not agent.get("local", True):- # A retry after a timeout must find its accepted work, not queue a second turn.- message_id = protocol.extract_message_id(params)- input_id = ("a2a-msg:" + hashlib.sha256(f"{context_id}\0{message_id}".encode()).hexdigest()- if message_id else task_id)+ if forwarded:self._activate_task(task_id)try:- reply, state = self._forward_to_profile(agent, peer, context_id, framed, input_id=input_id)+ reply, state = self._forward_to_profile(agent, peer, context_id, framed, input_id=input_id or task_id)self._record_outcome(task_id, context_id, peer, state, reply)return protocol.build_task(task_id, context_id, state, reply, created_at=rec["created_iso"]), Nonefinally:diff --git a/plugins/platforms/a2a/protocol.py b/plugins/platforms/a2a/protocol.pyindex db6f2f2bd45..1649e5624c7 100644--- a/plugins/platforms/a2a/protocol.py+++ b/plugins/platforms/a2a/protocol.py@@ -5,6 +5,7 @@ Stdlib only. ``extract_text`` stays tolerant of v0.3 peers."""from __future__ import annotations+import hashlibimport jsonimport osimport threading@@ -127,6 +128,12 @@ def new_context_id() -> str:return "ctx-" + uuid.uuid4().hex[:16]+def message_context_id(scope: str, message_id: str) -> str:+ """The context a first message without a ``contextId`` opens. Named by the message, so a retry+ of that send after a timeout reopens the same context instead of a fresh one."""+ return "ctx-" + hashlib.sha256(f"{scope}\0{message_id}".encode()).hexdigest()[:16]++def text_part(text: str) -> dict:"""v1.0 text Part (member-presence discriminated, no ``kind``)."""return {"text": text, "mediaType": "text/plain"}diff --git a/tests/plugins/test_a2a_plugin.py b/tests/plugins/test_a2a_plugin.pyindex 4304cf1f5f1..6d874d5a5fe 100644--- a/tests/plugins/test_a2a_plugin.py+++ b/tests/plugins/test_a2a_plugin.py@@ -1411,6 +1411,74 @@ class TestMultiAgentRouting:"peer-x", agent=agent)assert not seen[4].startswith("a2a-msg:")+ def test_forwarded_retry_without_a_context_reopens_the_same_context(self):+ """A first send is retried with the same messageId and no contextId, because the peer never+ received one. It must land in the same context and admission as the first attempt."""+ from plugins.platforms.a2a.adapter import A2AAdapter+ from gateway.config import PlatformConfig++ adapter = A2AAdapter(PlatformConfig(enabled=True, extra={+ "agents": {"dev": {"profile": "dev", "tenant": "dev"}}+ }))+ agent = adapter._agents["dev"]+ seen = []++ def fake_forward(agent_arg, peer, context_id, framed_text, *, input_id):+ seen.append((context_id, input_id))+ return "dev reply", protocol.STATE_COMPLETED++ adapter._forward_to_profile = fake_forward # type: ignore+ message = protocol.text_message(protocol.ROLE_USER, "hello")+ assert "contextId" not in message+ first, _ = adapter._prepare_task({"tenant": "dev", "message": dict(message)}, "peer-x", agent=agent)+ second, _ = adapter._prepare_task({"tenant": "dev", "message": dict(message)}, "peer-x", agent=agent)+ assert seen[0] == seen[1]+ assert first["contextId"] == second["contextId"] == seen[0][0]+ assert first["contextId"].startswith("ctx-")+ # A different first message opens its own context; so does another peer repeating the id.+ adapter._prepare_task({"tenant": "dev", "message": protocol.text_message(protocol.ROLE_USER, "hello")},+ "peer-x", agent=agent)+ adapter._prepare_task({"tenant": "dev", "message": dict(message)}, "peer-y", agent=agent)+ assert len({context for context, _ in seen}) == 3+ # Without a messageId there is nothing to retry by; the context stays random.+ bare = {"role": "user", "parts": [{"text": "hi"}]}+ one, _ = adapter._prepare_task({"tenant": "dev", "message": dict(bare)}, "peer-x", agent=agent)+ two, _ = adapter._prepare_task({"tenant": "dev", "message": dict(bare)}, "peer-x", agent=agent)+ assert one["contextId"] != two["contextId"]++ def test_forwarded_retries_do_not_spend_the_turn_budget(self, monkeypatch):+ """The owner answers a resend from the accepted admission, so the anti-loop counter and the+ conversation log see the message once. Distinct messages in the context still count."""+ from plugins.platforms.a2a.adapter import A2AAdapter+ from gateway.config import PlatformConfig++ monkeypatch.setenv("A2A_MAX_PINGPONG_TURNS", "2")+ persisted = []+ monkeypatch.setattr(protocol, "persist_message", lambda context_id, role, text, task_id="": persisted.append(role))+ adapter = A2AAdapter(PlatformConfig(enabled=True, extra={+ "agents": {"dev": {"profile": "dev", "tenant": "dev"}}+ }))+ agent = adapter._agents["dev"]+ seen = []++ def fake_forward(agent_arg, peer, context_id, framed_text, *, input_id):+ seen.append(input_id)+ return "dev reply", protocol.STATE_COMPLETED++ adapter._forward_to_profile = fake_forward # type: ignore+ message = protocol.text_message(protocol.ROLE_USER, "hello", context_id="ctx-dev")+ tasks = [adapter._prepare_task({"tenant": "dev", "message": dict(message)}, "peer-x", agent=agent)[0]+ for _ in range(5)]+ assert [task["status"]["state"] for task in tasks] == [protocol.STATE_COMPLETED] * 5+ assert len(seen) == 5 and len(set(seen)) == 1+ assert persisted.count("user") == 1+ assert adapter._turns.track("ctx-dev") == 2+ # That track call was the second distinct turn; the third trips the guard as before.+ fresh = protocol.text_message(protocol.ROLE_USER, "again", context_id="ctx-dev")+ rejected, _ = adapter._prepare_task({"tenant": "dev", "message": fresh}, "peer-x", agent=agent)+ assert rejected["status"]["state"] == protocol.STATE_REJECTED+ assert len(seen) == 5+def test_forwarded_profile_task_completes_in_task_store(self, monkeypatch):from plugins.platforms.a2a.adapter import A2AAdapterfrom gateway.config import PlatformConfig