adapter.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. """A2A inbound adapter: stdlib http.server (daemon thread) serving the Agent Card, /metrics and
  2. JSON-RPC (message/send, message/stream SSE, tasks/*, push-config CRUD). Inbound tasks are framed
  3. (security.wrap_inbound) and routed into the LIVE gateway session; ``send()`` fulfils the per-task
  4. Future the HTTP handler blocks on. No token configured => binds 127.0.0.1 only."""
  5. from __future__ import annotations
  6. import asyncio
  7. import contextlib
  8. import hashlib
  9. import json
  10. import logging
  11. import os
  12. import re
  13. import socket
  14. import threading
  15. import time
  16. import urllib.parse
  17. import urllib.request
  18. from collections import OrderedDict, deque
  19. from concurrent.futures import Future
  20. from concurrent.futures import TimeoutError as FuturesTimeout
  21. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  22. from typing import Any, Dict, Optional
  23. from gateway.platforms.base import BasePlatformAdapter, SendResult
  24. from gateway.platforms.event import MessageEvent, MessageType, ProcessingOutcome
  25. from gateway.config import Platform
  26. from gateway.platforms._shared import coerce_port as _to_int, get_scoped_secret as _get_scoped_secret
  27. from . import protocol, security
  28. logger = logging.getLogger(__name__)
  29. _DEFAULT_PORT = 9900
  30. # seconds: orphan grace floor / ceiling / watchdog period. The ceiling keeps the sweep
  31. # meaningful when A2A_REPLY_TIMEOUT is absurd (1e18 would never fail an orphan).
  32. _MIN_ORPHAN_TIMEOUT, _MAX_ORPHAN_TIMEOUT, _WATCHDOG_INTERVAL = 300, 86400, 60
  33. _MAX_BODY = 1_048_576 # 1MB max request body — prevents DoS via memory exhaustion
  34. _SSE_KEEPALIVE = 5 # seconds between SSE keepalive comments
  35. _DEFAULT_DESCRIPTION = "Hermes Agent — a general-purpose agent reachable over A2A."
  36. _ok = protocol.jsonrpc_result
  37. _err = protocol.jsonrpc_error
  38. # (adapter handler, v1.0 PascalCase method per §5.3/§9.4, *legacy slash aliases still accepted)
  39. _METHOD_TABLE = (
  40. ("_rpc_message_send", "SendMessage", "message/send"),
  41. ("_rpc_message_stream", "SendStreamingMessage", "message/stream"),
  42. ("_rpc_tasks_get", "GetTask", "tasks/get"),
  43. ("_rpc_tasks_list", "ListTasks", "tasks/list"),
  44. ("_rpc_tasks_cancel", "CancelTask", "tasks/cancel"),
  45. ("_rpc_tasks_subscribe", "SubscribeToTask", "tasks/subscribe"),
  46. ("_rpc_push_config_create", "CreateTaskPushNotificationConfig", "tasks/pushNotificationConfig/create",
  47. "tasks/pushNotificationConfig/set", "tasks/pushNotification/set"),
  48. ("_rpc_push_config_get", "GetTaskPushNotificationConfig", "tasks/pushNotificationConfig/get"),
  49. ("_rpc_push_config_list", "ListTaskPushNotificationConfigs", "tasks/pushNotificationConfig/list"),
  50. ("_rpc_push_config_delete", "DeleteTaskPushNotificationConfig", "tasks/pushNotificationConfig/delete"),
  51. )
  52. # JSON-RPC method -> (adapter handler name, is_v1)
  53. _METHODS: dict[str, tuple[str, bool]] = {
  54. m: (handler, i == 0) for handler, *methods in _METHOD_TABLE for i, m in enumerate(methods)
  55. }
  56. def _reply_timeout() -> float:
  57. """Seconds to wait for the agent to answer an inbound task."""
  58. try:
  59. return max(1.0, float(os.getenv("A2A_REPLY_TIMEOUT", "300")))
  60. except (ValueError, TypeError):
  61. return 300.0
  62. def _orphan_timeout() -> float:
  63. """Orphan grace must never expire before a configured reply window, but stays bounded."""
  64. return min(float(_MAX_ORPHAN_TIMEOUT), max(float(_MIN_ORPHAN_TIMEOUT), _reply_timeout()))
  65. def _default_agent_name() -> str:
  66. # Scope-aware: a secondary multiplex profile must not borrow the default profile's A2A_AGENT_NAME.
  67. name = _get_scoped_secret("A2A_AGENT_NAME", "").strip()
  68. if name:
  69. return name
  70. try:
  71. import socket
  72. return f"hermes-{socket.gethostname()}"
  73. except Exception:
  74. return "hermes-agent"
  75. def _clean_slug(value: str) -> str:
  76. """URL-safe-ish single-segment slug for a served agent ("" for the root agent)."""
  77. slug = str(value or "").strip().strip("/")
  78. return "" if slug in ("", "default", "root") else slug.split("/")[0]
  79. def _join_url(base: str, prefix: str) -> str:
  80. base = (base or "").strip() or "/"
  81. base = base if base.endswith("/") else base + "/"
  82. prefix = (prefix or "").strip("/")
  83. return urllib.parse.urljoin(base, prefix + "/") if prefix else base
  84. def _active_profile_name() -> str:
  85. try:
  86. from hermes_cli.profiles import get_active_profile_name
  87. return get_active_profile_name() or "default"
  88. except Exception:
  89. return os.getenv("HERMES_PROFILE", "default") or "default"
  90. def _profile_home(profile: str) -> Optional[str]:
  91. with contextlib.suppress(Exception):
  92. from hermes_cli.profiles import get_profile_dir
  93. return str(get_profile_dir(profile))
  94. if profile and profile != "default":
  95. return os.path.expanduser(f"~/.hermes/profiles/{profile}")
  96. with contextlib.suppress(Exception):
  97. from hermes_cli.config import get_hermes_home
  98. return str(get_hermes_home())
  99. return None
  100. class _ThreadingHTTPServerV6(ThreadingHTTPServer):
  101. """IPv6 listener. ``V6ONLY=0`` makes the ``::`` wildcard dual-stack (IPv4 peers arrive as
  102. ``::ffff:a.b.c.d``), so one socket serves IPv6-only private networks and IPv4 alike."""
  103. address_family = socket.AF_INET6
  104. def server_bind(self):
  105. with contextlib.suppress(OSError, AttributeError): # no IPV6_V6ONLY: the bind stays v6-only
  106. self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
  107. super().server_bind()
  108. def _http_server_class(host: str) -> type:
  109. """``ThreadingHTTPServer`` is AF_INET only, so an IPv6 bind (``::1``, ``::``) needs the v6 family."""
  110. return _ThreadingHTTPServerV6 if ":" in host else ThreadingHTTPServer
  111. def _daemon_thread(target, name: str) -> threading.Thread:
  112. t = threading.Thread(target=target, name=name, daemon=True)
  113. t.start()
  114. return t
  115. def _safe_context_slug(value: str, max_len: int = 96) -> str:
  116. """Sanitize attacker-provided context ids before using in session titles."""
  117. slug = re.sub(r"[^A-Za-z0-9_.-]+", "-", str(value or "")).strip("-._")
  118. return (slug or "ctx")[:max_len]
  119. class A2ARequestHandler(BaseHTTPRequestHandler):
  120. """HTTP handler for the A2A JSON-RPC surface; all state lives on ``self.server.adapter``."""
  121. @property
  122. def adapter(self) -> A2AAdapter:
  123. return self.server.adapter # type: ignore[attr-defined]
  124. def parse_request(self) -> bool:
  125. """Without a token, refuse any request whose ``Host`` is not a loopback name, before a route
  126. runs: a page on a hostname re-resolved to 127.0.0.1 (DNS rebinding) is same-origin to this
  127. listener and could otherwise read its served-agent list and Agent Card."""
  128. if not super().parse_request():
  129. return False
  130. adapter = self.adapter
  131. if adapter._security_context.localhost_only() and not security.is_loopback_host_header(
  132. self.headers.get("Host"), adapter._public_url):
  133. self._error(403, None, protocol.ERR_UNAUTHORIZED,
  134. "Host must be a loopback name or the A2A_PUBLIC_URL host (no A2A token configured)")
  135. return False
  136. return True
  137. def log_message(self, format, *args):
  138. logger.debug("A2A http: " + format, *args) # silence the default stderr access log
  139. def _json(self, code: int, payload: dict):
  140. body = json.dumps(payload).encode("utf-8")
  141. self.send_response(code)
  142. for k, v in (("Content-Type", "application/json"), ("Content-Length", str(len(body)))):
  143. self.send_header(k, v)
  144. self.end_headers()
  145. self.wfile.write(body)
  146. def _error(self, http_code: int, req_id: Any, code: int, message: str):
  147. self._json(http_code, _err(req_id, code, message))
  148. def _client_ip(self) -> str:
  149. """The peer's address; an IPv4 peer of a dual-stack ``::`` bind keeps its plain IPv4 identity."""
  150. ip = self.client_address[0] if self.client_address else ""
  151. return ip.removeprefix("::ffff:") if ip.startswith("::ffff:") and "." in ip else ip
  152. def _request_public_url(self) -> str:
  153. """A2A_PUBLIC_URL > X-Forwarded-Host / Host (scheme from X-Forwarded-Proto) > "" (bind host).
  154. Empty means "caller has no info, fall back to bind host". See #41711.
  155. A2A_PUBLIC_URL is read from ``self.adapter`` (captured at construction time, inside profile
  156. scope) rather than os.getenv here: do_GET/do_POST run on ThreadingHTTPServer's per-connection
  157. OS threads, which never inherit the profile scope contextvar, so a secondary multiplex
  158. profile's own A2A_PUBLIC_URL would otherwise resolve to the default profile's env value.
  159. """
  160. explicit = self.adapter._public_url
  161. if explicit:
  162. return explicit
  163. host = (self.headers.get("X-Forwarded-Host", "") or self.headers.get("Host", "")).split(",")[0].strip()
  164. scheme = (self.headers.get("X-Forwarded-Proto", "") or "http").split(",")[0].strip()
  165. return f"{scheme}://{host}/" if host else ""
  166. def do_GET(self):
  167. adapter = self.adapter
  168. route = adapter._route_for_path(self.path)
  169. agent = route["agent"]
  170. subpath = route["subpath"].rstrip("/") or "/"
  171. public_url = self._request_public_url() or None
  172. if subpath in ("/.well-known/agent.json", "/.well-known/agent-card.json"):
  173. return self._json(200, adapter._build_card(public_url, agent=agent))
  174. if subpath == "/metrics":
  175. return self._json(200, protocol.metrics.snapshot())
  176. if subpath not in ("/", "/health"):
  177. return self._json(404, {"error": "not found"})
  178. payload = {"status": "ok", "agent": agent.get("name") or adapter.agent_name}
  179. # Agent Cards are public; profile/tenant topology is not leaked on remote unauthenticated GETs.
  180. sec = adapter._security_context
  181. if sec.localhost_only() or sec.authenticate(self.headers.get("Authorization"), self._client_ip()) is not None:
  182. payload["served_agents"] = adapter._served_agent_summary(public_url=public_url)
  183. self._json(200, payload)
  184. def do_POST(self):
  185. adapter = self.adapter
  186. # Identity comes from the credential (or the socket in localhost-only mode) — never the body.
  187. identity = adapter._security_context.authenticate(self.headers.get("Authorization"), self._client_ip())
  188. if identity is None:
  189. return self._error(401, None, protocol.ERR_UNAUTHORIZED, "unauthorized")
  190. if adapter._security_context.localhost_only() and (refusal := security.browser_post_refusal(self.headers)):
  191. return self._error(403, None, protocol.ERR_UNAUTHORIZED, refusal)
  192. try:
  193. length = int(self.headers.get("Content-Length", 0))
  194. if length > _MAX_BODY:
  195. return self._error(413, None, protocol.ERR_PARSE, "payload too large")
  196. req = json.loads((self.rfile.read(length) if length else b"{}").decode("utf-8"))
  197. except Exception:
  198. return self._error(400, None, protocol.ERR_PARSE, "parse error")
  199. if not isinstance(req, dict):
  200. return self._error(400, None, protocol.ERR_INVALID_PARAMS, "JSON-RPC request must be an object")
  201. req_id, method = req.get("id"), str(req.get("method", ""))
  202. params = req["params"] if req.get("params") is not None else {}
  203. version = (self.headers.get("A2A-Version") or "").strip()
  204. route = adapter._route_for_request(self.path, params) if isinstance(params, dict) else {}
  205. handler_name, is_v1 = _METHODS.get(method, ("", False))
  206. # Ordered, lazily-evaluated checks -> (http status, error code, message); first failure wins
  207. # (the rate limiter must not be consulted for requests rejected before it).
  208. checks = (
  209. (lambda: not isinstance(params, dict), 200, protocol.ERR_INVALID_PARAMS, "params must be an object"),
  210. (lambda: version and version not in {"1.0", "1.0.0"}, 200, protocol.ERR_INVALID_PARAMS, f"unsupported A2A-Version: {version}"),
  211. (lambda: route.get("error"), 400, protocol.ERR_INVALID_PARAMS, route.get("error")),
  212. (lambda: not adapter._rate_limiter.allow(identity), 429, protocol.ERR_RATE_LIMITED, "rate limit exceeded"),
  213. (lambda: not adapter._security_context.is_trusted_peer(identity), 403, protocol.ERR_UNTRUSTED_PEER, f"peer '{identity}' not trusted"),
  214. (lambda: not handler_name, 200, protocol.ERR_METHOD_NOT_FOUND, f"method not found: {method}"),
  215. )
  216. for failed, http, code, msg in checks:
  217. if failed():
  218. if code == protocol.ERR_RATE_LIMITED:
  219. protocol.metrics.rate_limit_triggers += 1
  220. return self._error(http, req_id, code, msg)
  221. agent = route["agent"]
  222. if handler_name == "_rpc_message_send":
  223. self._json(200, adapter._rpc_message_send(req_id, params, identity, agent=agent, v1_response=is_v1))
  224. elif handler_name == "_rpc_message_stream":
  225. adapter._rpc_message_stream(self, req_id, params, identity, agent=agent)
  226. elif handler_name == "_rpc_tasks_subscribe":
  227. adapter._rpc_tasks_subscribe(self, req_id, params, agent=agent)
  228. else: # plain JSON task / push-config queries
  229. self._json(200, getattr(adapter, handler_name)(req_id, params, agent=agent))
  230. class A2AAdapter(BasePlatformAdapter):
  231. """Inbound A2A server adapter."""
  232. def __init__(self, config, **kwargs):
  233. super().__init__(config=config, platform=Platform("a2a"))
  234. extra = getattr(config, "extra", {}) or {}
  235. # Scope-aware: a secondary multiplex profile must not borrow the default profile's bridged
  236. # A2A_PORT (falls closed to the module default). advertised_toolsets is deliberately unscoped.
  237. # (advertised_toolsets has the same env-leak shape but is left unscoped here — see the "Scope note"
  238. # in this fix's PR description: open PR #98937 is actively rewriting this field's None-vs-empty-list
  239. # semantics.)
  240. self._security_context = security.A2ASecurityContext.capture()
  241. _port_env = _get_scoped_secret("A2A_PORT")
  242. self.port = int(_port_env or extra.get("port", _DEFAULT_PORT))
  243. self.host = self._security_context.resolve_bind_host()
  244. self.agent_name = _default_agent_name()
  245. configured_toolsets = list(extra.get("advertised_toolsets") or []) or _get_scoped_secret("A2A_ADVERTISED_TOOLSETS", "").split(",")
  246. self._advertised_toolsets = [t.strip() for t in configured_toolsets if str(t).strip()]
  247. self._active_profile = _active_profile_name()
  248. # Captured here (construction runs inside _profile_runtime_scope), not read at request time:
  249. # do_GET/do_POST run on ThreadingHTTPServer's per-connection OS threads, which never inherit
  250. # the profile scope contextvar (same class as A2A_PORT above).
  251. self._public_url = _get_scoped_secret("A2A_PUBLIC_URL", "").strip()
  252. self._agents = self._load_served_agents(extra)
  253. self._httpd: Optional[ThreadingHTTPServer] = None
  254. self._server_thread = self._watchdog_thread = None # type: Optional[threading.Thread]
  255. self._loop: Optional[asyncio.AbstractEventLoop] = None
  256. self._watchdog_stop = threading.Event()
  257. # Per-adapter protocol state (not module-global).
  258. self.tasks, self._turns, self._rate_limiter = protocol.TaskStore(), protocol.TurnTracker(), protocol.RateLimiter()
  259. # Pending reply futures: task_id -> (context_id, Future). _pending_order keeps per-context
  260. # FIFO so adapter.send() — which only knows the context — resolves the oldest task.
  261. self._pending: dict[str, tuple[str, Future]] = {}
  262. self._pending_order: dict[str, deque[str]] = {}
  263. # Request ownership outlives reply Futures and also covers synchronous profile forwards.
  264. self._active_tasks: set[str] = set()
  265. # Admission ids this process already forwarded; a resend of one is a retry, not a new turn.
  266. self._forwarded_inputs: OrderedDict[str, None] = OrderedDict()
  267. self._pending_lock = threading.Lock()
  268. @property
  269. def name(self) -> str:
  270. return "A2A"
  271. @property
  272. def authorization_is_upstream(self) -> bool:
  273. """Requests are authenticated in ``do_POST``; the gateway's A2A_ALLOWED_USERS list would
  274. otherwise reject peers (identity is a token-derived name or IP). Wrong credentials still 401.
  275. This is authorization delegated to the A2A bearer-token transport, not a fail-open: every request is
  276. 401'd if the credential is wrong. Reported by kuangmi-bit (PR #41711 comment, Jun 27).
  277. """
  278. return True
  279. async def connect(self, **_kwargs) -> bool:
  280. # Capture the gateway loop so the HTTP thread can marshal events via run_coroutine_threadsafe.
  281. self._loop = asyncio.get_running_loop()
  282. try:
  283. self._httpd = _http_server_class(self.host)((self.host, self.port), A2ARequestHandler)
  284. except OSError as e:
  285. logger.error("A2A: could not bind %s:%s — %s", self.host, self.port, e)
  286. self._set_fatal_error("bind_failed", f"A2A bind failed: {e}", retryable=True)
  287. return False
  288. self._httpd.daemon_threads = True
  289. self._httpd.adapter = self # type: ignore[attr-defined]
  290. self._server_thread = _daemon_thread(self._httpd.serve_forever, "a2a-http")
  291. self._watchdog_stop.clear() # disconnect sets it; reset for reconnection
  292. self._watchdog_thread = _daemon_thread(self._watchdog_loop, "a2a-watchdog")
  293. self._mark_connected()
  294. logger.info("A2A: serving Agent Card + JSON-RPC on http://%s:%s (%s) as %r; %d routed agent(s)", self.host, self.port,
  295. "localhost-only" if self._security_context.localhost_only() else "REMOTE (bearer auth)", self.agent_name, len(self._agents))
  296. sec = self._security_context
  297. if sec.dispatch_fails_closed():
  298. logger.error("A2A: exposed on non-loopback bind %s with no A2A_TRUSTED_PEERS; every dispatch will be refused (403). "
  299. "Set A2A_TRUSTED_PEERS, or A2A_ALLOW_ALL_USERS=true for a trusted network.", self.host)
  300. self._wire_plugin_handlers(None) # plugin-registered native handlers
  301. return True
  302. async def disconnect(self) -> None:
  303. self._mark_disconnected()
  304. self._watchdog_stop.set()
  305. if self._httpd is not None:
  306. with contextlib.suppress(Exception):
  307. self._httpd.shutdown()
  308. self._httpd.server_close()
  309. self._httpd = None
  310. # Fail any in-flight replies so blocked HTTP threads don't hang.
  311. with self._pending_lock:
  312. for tid in list(self._pending):
  313. self._resolve_locked(tid, protocol.STATE_FAILED, "[agent shutting down]")
  314. self._pending.clear()
  315. self._pending_order.clear()
  316. self._active_tasks.clear()
  317. def _watchdog_loop(self) -> None:
  318. """Background thread that fails orphaned tasks (keeps them queryable)."""
  319. while not self._watchdog_stop.wait(_WATCHDOG_INTERVAL):
  320. try:
  321. self._fail_orphans_once()
  322. except Exception:
  323. logger.debug("A2A: watchdog error", exc_info=True)
  324. def _fail_orphans_once(self) -> list[str]:
  325. """Fail stale tasks that no request still owns."""
  326. with self._pending_lock:
  327. active_tasks = set(self._active_tasks)
  328. timeout = _orphan_timeout()
  329. failed = self.tasks.fail_orphans(timeout, exclude=active_tasks)
  330. for tid in failed:
  331. logger.warning("A2A: orphaned task %s marked failed (timeout %gs)", tid, timeout)
  332. protocol.metrics.tasks_failed += 1
  333. return failed
  334. def _load_served_agents(self, extra: dict) -> dict[str, dict]:
  335. """Served-agent routing from ``platforms.a2a.extra.agents`` (top-level ``a2a_served_agents``
  336. fallback for scripts/tests). Root/default always maps to the live gateway session."""
  337. raw = extra.get("agents") or extra.get("served_agents")
  338. if raw is None:
  339. try:
  340. from hermes_cli.config import load_config
  341. cfg = load_config() or {}
  342. except Exception:
  343. cfg = {}
  344. cfg = cfg if isinstance(cfg, dict) else {}
  345. raw = cfg.get("a2a_served_agents") or (cfg.get("a2a") or {}).get("served_agents")
  346. # Scope-aware like port: a secondary profile must not inherit A2A_AGENT_DESCRIPTION.
  347. default_desc = _get_scoped_secret("A2A_AGENT_DESCRIPTION", _DEFAULT_DESCRIPTION)
  348. agents: dict[str, dict] = {"": {
  349. "slug": "", "path": "", "tenant": "", "profile": self._active_profile, "local": True,
  350. "name": self.agent_name, "description": default_desc, "advertised_toolsets": self._advertised_toolsets,
  351. }}
  352. reserved = {"health", "metrics", ".well-known"}
  353. tenants: dict[str, str] = {}
  354. items = raw.items() if isinstance(raw, dict) else enumerate(raw or []) if isinstance(raw, list) else []
  355. for key, val in items:
  356. if not isinstance(val, dict):
  357. continue
  358. slug = _clean_slug(str(val.get("slug") or val.get("id") or key))
  359. if not slug:
  360. continue
  361. path_segment = _clean_slug(str(val.get("path") or slug))
  362. if not path_segment or path_segment in reserved:
  363. logger.warning("A2A: ignoring served agent %r with reserved/invalid path %r", slug, path_segment)
  364. continue
  365. profile = str(val.get("profile") or slug).strip()
  366. toolsets = val.get("advertised_toolsets") or val.get("toolsets") or val.get("capabilities") or []
  367. if isinstance(toolsets, str):
  368. toolsets = [t.strip() for t in toolsets.split(",") if t.strip()]
  369. tenant = str(val.get("tenant") or slug).strip()
  370. if tenant:
  371. if tenant in tenants:
  372. logger.warning("A2A: ignoring served agent %r with duplicate tenant %r already used by %r",
  373. slug, tenant, tenants[tenant])
  374. continue
  375. tenants[tenant] = slug
  376. agents[slug] = {
  377. "slug": slug, "path": "/" + path_segment, "tenant": tenant, "profile": profile or slug,
  378. "local": bool(val.get("local")) or profile in ("", "default", self._active_profile),
  379. "name": str(val.get("name") or f"Hermes {slug}"),
  380. "description": str(val.get("description") or f"Hermes profile '{profile or slug}' exposed over A2A."),
  381. "advertised_toolsets": list(toolsets or []),
  382. "timeout": int(val.get("timeout") or _reply_timeout()),
  383. }
  384. return agents
  385. def _base_url(self, public_url: Optional[str]) -> str:
  386. host = f"[{self.host}]" if ":" in self.host else self.host # IPv6 literal
  387. return (public_url or "").strip() or f"http://{host}:{self.port}/"
  388. def _served_agent_summary(self, public_url: Optional[str] = None) -> list[dict]:
  389. base = self._base_url(public_url)
  390. return [{"slug": a["slug"] or "default", "name": a.get("name"), "url": _join_url(base, a.get("path", "")),
  391. "tenant": a.get("tenant") or None, "profile": a.get("profile"), "local": bool(a.get("local"))}
  392. for a in self._agents.values()]
  393. def _route_for_path(self, raw_path: str) -> dict:
  394. path = urllib.parse.urlsplit(raw_path or "/").path or "/"
  395. # Longest prefix wins. Default/root agent is the fallback.
  396. for agent in sorted(self._agents.values(), key=lambda a: len(a.get("path", "")), reverse=True):
  397. if (prefix := agent.get("path", "") or "") and (path == prefix or path.startswith(prefix + "/")):
  398. return {"agent": agent, "subpath": path[len(prefix):] or "/"}
  399. return {"agent": self._agents[""], "subpath": path}
  400. def _route_for_request(self, raw_path: str, params: dict) -> dict:
  401. route = self._route_for_path(raw_path)
  402. agent = route["agent"]
  403. tenant = str((params or {}).get("tenant") or "")
  404. # If no URL prefix chose a non-default agent, allow v1.0 tenant routing.
  405. if agent.get("slug") == "" and tenant and (matches := [a for a in self._agents.values() if a.get("tenant") == tenant]):
  406. agent = matches[0]
  407. route = {"agent": agent, "subpath": route["subpath"]}
  408. expected = str(agent.get("tenant") or "")
  409. if tenant and expected and tenant != expected:
  410. return {"error": f"tenant {tenant!r} does not match routed agent {agent.get('slug') or 'default'}"}
  411. return route
  412. def _build_card(self, public_url: Optional[str] = None, agent: Optional[dict] = None) -> dict:
  413. # Per-request public URL beats the bind host so peers behind a reverse proxy can call back.
  414. agent = agent or self._agents[""]
  415. return protocol.build_agent_card(
  416. name=agent.get("name") or self.agent_name, url=_join_url(self._base_url(public_url), agent.get("path", "")),
  417. description=agent.get("description") or _DEFAULT_DESCRIPTION, skills=self._advertised_skills(agent),
  418. streaming=bool(agent.get("local", True)), push_notifications=True,
  419. auth_required=not self._security_context.localhost_only(), tenant=str(agent.get("tenant") or ""),
  420. )
  421. def _advertised_skills(self, agent: Optional[dict] = None) -> list[dict]:
  422. """Agent Card skills from the live tool registry, restricted by ``advertised_toolsets``;
  423. static fallback without a registry."""
  424. configured = (agent or {}).get("advertised_toolsets") if agent else self._advertised_toolsets
  425. try:
  426. from tools.registry import registry as tool_registry
  427. allowed = set(configured or []) or None
  428. mapping = {n: tool_registry.get_tool_names_for_toolset(n)
  429. for n in tool_registry.get_registered_toolset_names() if allowed is None or n in allowed}
  430. if mapping:
  431. return protocol.skills_from_toolsets(mapping)
  432. except Exception:
  433. logger.debug("A2A: tool registry unavailable for Agent Card", exc_info=True)
  434. return protocol.skills_from_toolsets(configured or [])
  435. def _add_pending(self, task_id: str, context_id: str) -> Future:
  436. fut: Future = Future()
  437. with self._pending_lock:
  438. self._active_tasks.add(task_id)
  439. self._pending[task_id] = (context_id, fut)
  440. self._pending_order.setdefault(context_id, deque()).append(task_id)
  441. return fut
  442. def _activate_task(self, task_id: str) -> None:
  443. with self._pending_lock:
  444. self._active_tasks.add(task_id)
  445. _MAX_FORWARDED_INPUTS = 1000
  446. def _note_forwarded_input(self, input_id: str) -> bool:
  447. """Record a forwarded admission id; True when this process already sent it (a retry)."""
  448. with self._pending_lock:
  449. seen = input_id in self._forwarded_inputs
  450. self._forwarded_inputs[input_id] = None
  451. self._forwarded_inputs.move_to_end(input_id)
  452. while len(self._forwarded_inputs) > self._MAX_FORWARDED_INPUTS:
  453. self._forwarded_inputs.popitem(last=False)
  454. return seen
  455. def _forget_forwarded_input(self, input_id: Optional[str]) -> None:
  456. """Drop a fresh id a pre-admission guard refused, so its resend is refused again."""
  457. with self._pending_lock:
  458. self._forwarded_inputs.pop(input_id, None)
  459. def _pop_pending(self, task_id: str) -> None:
  460. with self._pending_lock:
  461. self._active_tasks.discard(task_id)
  462. entry = self._pending.pop(task_id, None)
  463. order = self._pending_order.get(entry[0]) if entry else None
  464. if order and task_id in order:
  465. order.remove(task_id)
  466. if order is not None and not order:
  467. self._pending_order.pop(entry[0], None)
  468. def _resolve_locked(self, task_id: str, state: str, text: str) -> bool:
  469. entry = self._pending.get(task_id)
  470. if not entry or entry[1].done():
  471. return False
  472. entry[1].set_result((state, text))
  473. return True
  474. def _resolve_task(self, task_id: str, state: str, text: str) -> bool:
  475. with self._pending_lock:
  476. return self._resolve_locked(task_id, state, text)
  477. def _resolve_oldest_for_context(self, context_id: str, state: str, text: str) -> bool:
  478. with self._pending_lock:
  479. return any(self._resolve_locked(tid, state, text) for tid in self._pending_order.get(context_id, ()))
  480. def _scope_for_agent(self, agent: Optional[dict]) -> tuple[str, str]:
  481. return tuple(str((agent or self._agents[""]).get(k) or "") for k in ("slug", "tenant"))
  482. def _end_task(self, rec: dict, state: str, text: str, stored_reply: str = "") -> tuple[dict, None]:
  483. """Complete a task immediately (rejected / not ready) and build its terminal Task."""
  484. self.tasks.complete(rec["task_id"], state, stored_reply)
  485. protocol.metrics.tasks_failed += state == protocol.STATE_FAILED
  486. return protocol.build_task(rec["task_id"], rec["context_id"], state, text, created_at=rec["created_iso"]), None
  487. def _prepare_task(self, params: dict, peer: str, agent: Optional[dict] = None) -> tuple[Optional[dict], Optional[dict]]:
  488. """Validate, register, and dispatch an inbound message (HTTP worker thread). Returns
  489. (terminal_task, None) when it ends immediately, else (None, pending) with the future to wait on."""
  490. agent = agent or self._agents[""]
  491. text = protocol.extract_text(params)
  492. forwarded = not agent.get("local", True)
  493. message_id = protocol.extract_message_id(params) if forwarded else ""
  494. context_id = protocol.extract_context_id(params)
  495. if not context_id:
  496. # A retry of a first send repeats the messageId and omits the contextId it never received.
  497. scope = "\0".join((*self._scope_for_agent(agent), peer))
  498. context_id = protocol.message_context_id(scope, message_id) if message_id else protocol.new_context_id()
  499. # A retry after a timeout must find its accepted work, not queue a second turn.
  500. input_id = ("a2a-msg:" + hashlib.sha256(f"{context_id}\0{message_id}".encode()).hexdigest()
  501. if message_id else None)
  502. # The process LRU answers concurrent resends atomically; the durable context log answers
  503. # one whose id the LRU evicted or a restart forgot.
  504. retry = input_id is not None and (self._note_forwarded_input(input_id)
  505. or protocol.logged_input(context_id, input_id))
  506. task_id = protocol.new_task_id()
  507. # The owner answers a resend from the accepted admission; it is not another turn of the loop.
  508. turn = 0 if retry else self._turns.track(context_id)
  509. max_turns = protocol.max_pingpong_turns()
  510. rec = self.tasks.create(task_id, context_id, peer, *self._scope_for_agent(agent),
  511. input_id=(input_id or task_id) if forwarded else "")
  512. if not retry and (turn > max_turns or not text):
  513. self._forget_forwarded_input(input_id)
  514. if turn > max_turns:
  515. protocol.metrics.anti_loop_triggers += 1
  516. logger.warning("A2A: anti-loop triggered for context %s (turn %d > %d)", context_id, turn, max_turns)
  517. return self._end_task(rec, protocol.STATE_REJECTED, f"Anti-loop protection: context {context_id} exceeded "
  518. f"{max_turns} turns. Start a new context or increase A2A_MAX_PINGPONG_TURNS.")
  519. if not text:
  520. return self._end_task(rec, protocol.STATE_REJECTED, "Empty task — nothing to do.")
  521. framed = security.wrap_inbound(peer, text)
  522. security.audit("inbound", peer, task_id, text)
  523. if not retry:
  524. protocol.persist_message(context_id, "user", text, task_id, input_id=input_id or "")
  525. protocol.metrics.inbound_total += 1
  526. self._register_inline_push(task_id, params, agent=agent)
  527. if forwarded:
  528. self._activate_task(task_id)
  529. try:
  530. reply, state = self._forward_to_profile(agent, peer, context_id, framed, input_id=input_id or task_id)
  531. self._record_outcome(task_id, context_id, peer, state, reply)
  532. return protocol.build_task(task_id, context_id, state, reply, created_at=rec["created_iso"]), None
  533. finally:
  534. self._pop_pending(task_id)
  535. if self._loop is None or self._message_handler is None:
  536. return self._end_task(rec, protocol.STATE_FAILED, "Agent gateway not ready to accept A2A tasks.")
  537. fut = self._add_pending(task_id, context_id)
  538. event = MessageEvent(text=framed, message_type=MessageType.TEXT, message_id=task_id,
  539. source=self.build_source(chat_id=context_id, chat_name=f"a2a:{peer}", chat_type="dm", user_id=peer, user_name=peer))
  540. try:
  541. asyncio.run_coroutine_threadsafe(self.handle_message(event), self._loop)
  542. except Exception as e:
  543. msg = security.redact_outbound(f"Dispatch failed: {e}")
  544. try:
  545. return self._end_task(rec, protocol.STATE_FAILED, msg, stored_reply=msg)
  546. finally:
  547. self._pop_pending(task_id)
  548. self.tasks.set_state(task_id, protocol.STATE_WORKING)
  549. return None, {"task_id": task_id, "context_id": context_id, "peer": peer, "future": fut, "created_iso": rec["created_iso"], "started": time.time()}
  550. def _forward_to_profile(self, agent: dict, peer: str, context_id: str, framed_text: str,
  551. *, input_id: Optional[str] = None) -> tuple[str, str]:
  552. """Forward to the destination owner; never open its canonical database here."""
  553. from gateway.session_a2a import forward_to_owner
  554. profile = str(agent.get("profile") or agent.get("slug") or "").strip()
  555. home = _profile_home(profile)
  556. if not home:
  557. return "[profile unavailable]", protocol.STATE_FAILED
  558. try:
  559. receipt = asyncio.run(forward_to_owner(
  560. home, agent=str(agent.get("slug") or profile or "agent"),
  561. tenant=str(agent.get("tenant") or ""), peer=peer, context_id=context_id,
  562. input_id=input_id or protocol.new_task_id(), text=framed_text,
  563. timeout=int(agent.get("timeout") or _reply_timeout())))
  564. except TimeoutError:
  565. return "[profile reply unverified; accepted work was not cancelled]", protocol.STATE_FAILED
  566. except Exception as exc:
  567. # Boundary for a network peer: the full error stays in the local log, the reply is redacted.
  568. logger.warning("A2A: dispatch to profile %r unverified", profile, exc_info=True)
  569. return security.redact_outbound(f"Profile dispatch unverified: {exc}"), protocol.STATE_FAILED
  570. result = receipt.get('result') or {}
  571. completed = receipt.get('outcome') == 'completed' and not result.get('failed')
  572. return (security.redact_outbound(result.get('final_response') or ''),
  573. protocol.STATE_COMPLETED if completed else protocol.STATE_FAILED)
  574. def _record_outcome(self, task_id: str, context_id: str, peer: str, state: str, reply: str,
  575. started: Optional[float] = None) -> None:
  576. """Persist + audit + count a finished task, mark it terminal, and fire its push callback."""
  577. protocol.persist_message(context_id, "agent", reply, task_id)
  578. security.audit("outbound", peer, task_id, reply)
  579. m = protocol.metrics
  580. if state in (protocol.STATE_COMPLETED, protocol.STATE_INPUT_REQUIRED):
  581. m.outbound_total, m.tasks_completed = m.outbound_total + 1, m.tasks_completed + 1
  582. if started is not None:
  583. m.record_latency(time.time() - started)
  584. else:
  585. m.tasks_failed += 1
  586. self.tasks.complete(task_id, state, reply)
  587. self._send_push_notification(task_id, context_id, reply, state)
  588. def _finalize_task(self, pending: dict, state: str, reply: str) -> tuple[str, str]:
  589. """Record a dispatched task's outcome; returns (state, reply) after redaction and
  590. input-required detection (a leading marker flags a clarification request)."""
  591. task_id, context_id, peer = pending["task_id"], pending["context_id"], pending["peer"]
  592. try:
  593. reply = security.redact_outbound(reply or "")
  594. stripped = reply.lstrip()
  595. if state == protocol.STATE_COMPLETED and stripped.upper().startswith(protocol.INPUT_REQUIRED_MARKER):
  596. state, reply = protocol.STATE_INPUT_REQUIRED, stripped[len(protocol.INPUT_REQUIRED_MARKER):].strip()
  597. self._record_outcome(task_id, context_id, peer, state, reply, started=pending["started"])
  598. return state, reply
  599. finally:
  600. self._pop_pending(task_id)
  601. @staticmethod
  602. def _await_future(fut: Future, deadline: float, keepalive, on_timeout: tuple[str, str]) -> tuple[str, str]:
  603. """Block until ``fut`` resolves or ``deadline`` passes (-> ``on_timeout``). ``keepalive`` runs
  604. every _SSE_KEEPALIVE seconds while waiting; if it raises, the client is gone and we stop."""
  605. while True:
  606. try:
  607. return fut.result(timeout=_SSE_KEEPALIVE if keepalive else max(0.0, deadline - time.time()))
  608. except FuturesTimeout:
  609. if time.time() >= deadline:
  610. return on_timeout
  611. if keepalive:
  612. try:
  613. keepalive()
  614. except Exception:
  615. return (protocol.STATE_FAILED, "[client disconnected]")
  616. except Exception:
  617. return on_timeout
  618. def _await_reply(self, pending: dict, keepalive=None) -> tuple[str, str]:
  619. return self._await_future(pending["future"], pending["started"] + _reply_timeout(), keepalive,
  620. (protocol.STATE_FAILED, "[agent did not reply in time]"))
  621. def _rpc_message_send(self, req_id: Any, params: dict, peer: str, agent: Optional[dict] = None, v1_response: bool = False) -> dict:
  622. task, pending = self._prepare_task(params, peer, agent=agent)
  623. if task is None:
  624. state, reply = self._finalize_task(pending, *self._await_reply(pending))
  625. task = protocol.build_task(pending["task_id"], pending["context_id"], state, reply, created_at=pending["created_iso"])
  626. return _ok(req_id, protocol.send_message_response(task) if v1_response else task)
  627. @staticmethod
  628. def _sse_headers(handler) -> None:
  629. handler.send_response(200)
  630. for k, v in (("Content-Type", "text/event-stream"), ("Cache-Control", "no-cache")):
  631. handler.send_header(k, v)
  632. handler.end_headers()
  633. handler.close_connection = True # v1.0: stream closure signals the terminal state
  634. @staticmethod
  635. def _sse_write(handler, chunk: str) -> None:
  636. handler.wfile.write(chunk.encode("utf-8"))
  637. handler.wfile.flush()
  638. @classmethod
  639. def _keepalive(cls, handler):
  640. return lambda: cls._sse_write(handler, ": keepalive\n\n")
  641. def _emit_terminal(self, handler, task_id: str, context_id: str, state: str, reply: str, req_id: Any = None) -> None:
  642. """Emit the final artifact/status events and the closure marker. ``req_id`` threads into the
  643. JSON-RPC SSE envelope (§9.4)."""
  644. completed = bool(reply) and state == protocol.STATE_COMPLETED
  645. events = ([protocol.artifact_update(task_id, context_id, reply)] if completed else []) + [
  646. protocol.status_update(task_id, context_id, state, "" if completed else reply)]
  647. for ev in events:
  648. self._sse_write(handler, protocol.sse_data(ev, req_id))
  649. self._sse_write(handler, protocol.sse_done())
  650. def _rpc_message_stream(self, handler, req_id: Any, params: dict, peer: str, agent: Optional[dict] = None) -> None:
  651. """message/stream as an SSE response of JSON-RPC-wrapped StreamResponse events (§9.4)."""
  652. protocol.metrics.streams_started += 1
  653. self._sse_headers(handler)
  654. pending = None
  655. try:
  656. terminal, pending = self._prepare_task(params, peer, agent=agent)
  657. if terminal is not None:
  658. return self._emit_terminal(handler, terminal["id"], terminal["contextId"], terminal["status"]["state"],
  659. protocol.extract_text(terminal.get("status", {}).get("message", {}) or {}), req_id=req_id)
  660. task_id, context_id = pending["task_id"], pending["context_id"]
  661. submitted = protocol.build_task(task_id, context_id, protocol.STATE_SUBMITTED, created_at=pending["created_iso"])
  662. self._sse_write(handler, protocol.sse_data(protocol.stream_task(submitted), req_id))
  663. self._sse_write(handler, protocol.sse_data(protocol.status_update(task_id, context_id, protocol.STATE_WORKING), req_id))
  664. state, reply = self._finalize_task(pending, *self._await_reply(pending, keepalive=self._keepalive(handler)))
  665. pending = None
  666. self._emit_terminal(handler, task_id, context_id, state, reply, req_id=req_id)
  667. except (BrokenPipeError, ConnectionResetError):
  668. if pending is not None:
  669. self._finalize_task(pending, protocol.STATE_FAILED, "[client disconnected]")
  670. logger.debug("A2A: stream client disconnected")
  671. def _rpc_tasks_subscribe(self, handler, req_id: Any, params: dict, agent: Optional[dict] = None) -> None:
  672. """Reconnect to an existing task's stream (v1.0 SubscribeToTask)."""
  673. task_id, rec, error = self._find_task(req_id, params, agent)
  674. if error:
  675. return handler._json(200, error)
  676. self._sse_headers(handler)
  677. try:
  678. if (fut := self.tasks.watch(task_id, *self._scope_for_agent(agent))) is None:
  679. return self._sse_write(handler, protocol.sse_done())
  680. state, reply = self._await_future(fut, time.time() + _reply_timeout(), self._keepalive(handler),
  681. (rec["state"], rec.get("reply", "")))
  682. self._emit_terminal(handler, task_id, rec["context_id"], state, reply, req_id=req_id)
  683. except (BrokenPipeError, ConnectionResetError):
  684. logger.debug("A2A: subscribe client disconnected")
  685. def _find_task(self, req_id: Any, params: dict, agent: Optional[dict]) -> tuple[str, Optional[dict], Optional[dict]]:
  686. """(task_id, record, None) for a visible task, else (task_id, None, jsonrpc_error)."""
  687. task_id = str(params.get("taskId") or params.get("id") or "")
  688. rec = self.tasks.get(task_id, *self._scope_for_agent(agent))
  689. return task_id, rec, None if rec else _err(req_id, protocol.ERR_TASK_NOT_FOUND, f"task not found: {task_id}")
  690. def _rpc_tasks_get(self, req_id: Any, params: dict, agent: Optional[dict] = None) -> dict:
  691. _task_id, rec, error = self._find_task(req_id, params, agent)
  692. return error or _ok(req_id, protocol.TaskStore.to_task(rec))
  693. def _rpc_tasks_list(self, req_id: Any, params: dict, agent: Optional[dict] = None) -> dict:
  694. offset = _to_int(params.get("pageToken") or 0, 0)
  695. page_size = _to_int(params.get("pageSize") or 50, 50)
  696. agent_slug, tenant = self._scope_for_agent(agent)
  697. recs, next_offset, total = self.tasks.list(
  698. context_id=str(params.get("contextId") or ""), state=str(params.get("status") or params.get("state") or ""),
  699. page_size=page_size, offset=max(0, offset), agent_slug=agent_slug, tenant=tenant, with_total=True)
  700. include_artifacts = bool(params.get("includeArtifacts", False))
  701. return _ok(req_id, {"tasks": [protocol.TaskStore.to_task(r, include_artifacts=include_artifacts) for r in recs],
  702. "nextPageToken": str(next_offset) if next_offset else "",
  703. "pageSize": max(1, min(page_size, 100)), "totalSize": total})
  704. def _rpc_tasks_cancel(self, req_id: Any, params: dict, agent: Optional[dict] = None) -> dict:
  705. task_id, rec, error = self._find_task(req_id, params, agent)
  706. if error:
  707. return error
  708. if rec["state"] in protocol.TERMINAL_STATES:
  709. return _err(req_id, protocol.ERR_TASK_NOT_CANCELABLE, f"task {task_id} already {rec['state']}")
  710. self.tasks.complete(task_id, protocol.STATE_CANCELED, "")
  711. self._turns.reset(rec["context_id"])
  712. self._resolve_task(task_id, protocol.STATE_CANCELED, "")
  713. rec = self.tasks.get(task_id, *self._scope_for_agent(agent)) or rec
  714. return _ok(req_id, protocol.TaskStore.to_task(rec))
  715. def _register_inline_push(self, task_id: str, params: dict, agent: Optional[dict] = None) -> None:
  716. """v1.0: message/send can carry configuration.taskPushNotificationConfig."""
  717. cfg = (params.get("configuration") or {}).get("taskPushNotificationConfig") or {}
  718. url = (cfg.get("url") or (cfg.get("pushNotificationConfig") or {}).get("url") or "") if isinstance(cfg, dict) else ""
  719. if url:
  720. self.tasks.set_push_config(task_id, str(url), *self._scope_for_agent(agent))
  721. def _rpc_push_config_create(self, req_id: Any, params: dict, agent: Optional[dict] = None) -> dict:
  722. task_id = str(params.get("taskId") or "")
  723. url = str((params.get("pushNotificationConfig") or params.get("config") or {}).get("url") or "")
  724. if not task_id or not url:
  725. return _err(req_id, protocol.ERR_INVALID_PARAMS, "taskId and pushNotificationConfig.url required")
  726. stored = self.tasks.set_push_config(task_id, url, *self._scope_for_agent(agent))
  727. return _ok(req_id, stored) if stored is not None else _err(req_id, protocol.ERR_TASK_NOT_FOUND, f"task not found: {task_id}")
  728. def _push_config_op(self, req_id: Any, params: dict, agent: Optional[dict], op, render) -> dict:
  729. """Shared get/list/delete: ``op(task_id, config_id, slug, tenant)`` falsy => not found."""
  730. task_id = str(params.get("taskId") or "")
  731. if not task_id:
  732. return _err(req_id, protocol.ERR_INVALID_PARAMS, "taskId required")
  733. found = op(task_id, str(params.get("id") or params.get("configId") or ""), *self._scope_for_agent(agent))
  734. return _ok(req_id, render(found)) if found else _err(req_id, protocol.ERR_TASK_NOT_FOUND, f"push config not found for task: {task_id}")
  735. def _rpc_push_config_get(self, req_id: Any, params: dict, agent: Optional[dict] = None) -> dict:
  736. return self._push_config_op(req_id, params, agent, self.tasks.get_push_config, lambda cfg: cfg)
  737. def _rpc_push_config_list(self, req_id: Any, params: dict, agent: Optional[dict] = None) -> dict:
  738. # An empty list is a valid (non-error) result, hence the ``or [[]]`` sentinel through the shared op.
  739. return self._push_config_op(req_id, params, agent, lambda tid, _cid, *scope: self.tasks.list_push_configs(tid, *scope) or [[]],
  740. lambda found: {"configs": [c for c in found if c], "nextPageToken": ""})
  741. def _rpc_push_config_delete(self, req_id: Any, params: dict, agent: Optional[dict] = None) -> dict:
  742. return self._push_config_op(req_id, params, agent, self.tasks.delete_push_config, lambda _: {"deleted": True})
  743. def _send_push_notification(self, task_id: str, context_id: str, reply: str, state: str) -> None:
  744. """POST a v1.0 StreamResponse payload to the task's registered callback (SSRF-checked URL)."""
  745. def fail(msg: str, *args) -> None:
  746. protocol.metrics.push_failed += 1
  747. logger.warning("A2A: push notification for task %s " + msg, task_id, *args)
  748. callback_url = self.tasks.pop_push_url(task_id)
  749. if not callback_url:
  750. return
  751. if not security.is_safe_callback_url(callback_url, localhost_mode=self._security_context.localhost_only()):
  752. return fail("blocked — unsafe callback URL: %s", callback_url)
  753. payload = protocol.status_update(task_id, context_id, state, (reply or "")[:2000])
  754. headers = {"Content-Type": "application/json"}
  755. if signature := self._security_context.sign_push_payload(payload):
  756. headers["X-A2A-Signature"] = signature
  757. try:
  758. req = urllib.request.Request(callback_url, data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST")
  759. with urllib.request.urlopen(req, timeout=10) as resp:
  760. status = resp.status
  761. except Exception as e:
  762. return fail("failed: %s", e)
  763. if not 200 <= status < 300:
  764. return fail("got HTTP %d", status)
  765. protocol.metrics.push_sent += 1
  766. logger.debug("A2A: push notification sent for task %s", task_id)
  767. async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[dict[str, Any]] = None):
  768. """Fulfil the oldest pending reply Future for this context (``chat_id`` = A2A context id).
  769. Only sends carrying ``metadata['notify']`` (the base adapter's final-reply marker) satisfy
  770. the caller; progress/status/preview sends must not."""
  771. if not (metadata or {}).get("notify"):
  772. logger.debug("A2A: ignoring non-final send for context %s", chat_id)
  773. elif not self._resolve_oldest_for_context(chat_id, protocol.STATE_COMPLETED, content or ""):
  774. logger.debug("A2A: send() for context %s had no pending waiter", chat_id) # late chunk / out-of-band
  775. return SendResult(success=True, message_id=str(int(time.time() * 1000)))
  776. async def send_typing(self, chat_id: str, metadata=None) -> None:
  777. return None
  778. async def get_chat_info(self, chat_id: str) -> dict[str, Any]:
  779. return {"name": f"a2a:{chat_id}", "type": "dm"}
  780. async def on_processing_complete(self, event: MessageEvent, outcome: ProcessingOutcome) -> None:
  781. """Resolve the task future when processing ends without a reply send (failures,
  782. cancellations, empty runs, or a reply the gateway already streamed to the user) so the
  783. HTTP thread returns promptly."""
  784. task_id = str(getattr(event, "message_id", "") or "")
  785. if task_id:
  786. # A streamed turn never calls send() with notify=True (the gateway suppresses the
  787. # normal final send once streaming delivered the body), so the SUCCESS default must
  788. # not resolve with "" — that strands every A2A streaming reply as an empty completed
  789. # task (#116944). _streamed_final_response is the same stash _final_text_for_post_turn_hooks
  790. # reads for /goal and /loop.
  791. _streamed = getattr(event, "_streamed_final_response", "")
  792. default = (protocol.STATE_COMPLETED, _streamed if isinstance(_streamed, str) else "")
  793. self._resolve_task(task_id, *{
  794. ProcessingOutcome.FAILURE: (protocol.STATE_FAILED, "[agent processing failed]"),
  795. ProcessingOutcome.CANCELLED: (protocol.STATE_CANCELED, ""),
  796. }.get(outcome, default))