protocol.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. """A2A protocol helpers — Agent Card, JSON-RPC framing, task store, conversation persistence.
  2. Wire shape is A2A v1.0: SCREAMING_SNAKE_CASE states/roles; Parts and StreamResponse events are
  3. discriminated by member presence (no ``kind``/``final``); SSE closure signals the terminal state.
  4. Stdlib only. ``extract_text`` stays tolerant of v0.3 peers."""
  5. from __future__ import annotations
  6. import hashlib
  7. import json
  8. import os
  9. import threading
  10. import time
  11. import uuid
  12. from collections import OrderedDict, defaultdict, deque
  13. from concurrent.futures import Future
  14. from datetime import datetime, timezone, UTC
  15. from pathlib import Path
  16. from typing import Any, Optional
  17. from gateway.platforms._shared import coerce_port as _coerce_int
  18. from hermes_constants import get_hermes_home
  19. PROTOCOL_VERSION = "1.0"
  20. # A2A v1.0 task lifecycle states + message roles.
  21. STATE_SUBMITTED, STATE_WORKING, STATE_INPUT_REQUIRED = "TASK_STATE_SUBMITTED", "TASK_STATE_WORKING", "TASK_STATE_INPUT_REQUIRED"
  22. STATE_COMPLETED, STATE_FAILED = "TASK_STATE_COMPLETED", "TASK_STATE_FAILED"
  23. STATE_CANCELED, STATE_REJECTED = "TASK_STATE_CANCELED", "TASK_STATE_REJECTED"
  24. TERMINAL_STATES = frozenset({STATE_COMPLETED, STATE_FAILED, STATE_CANCELED, STATE_REJECTED})
  25. ROLE_USER, ROLE_AGENT = "ROLE_USER", "ROLE_AGENT"
  26. # A reply starting with this marker is a clarification request -> TASK_STATE_INPUT_REQUIRED (marker stripped).
  27. INPUT_REQUIRED_MARKER = "[INPUT_REQUIRED]"
  28. # JSON-RPC / A2A error codes. -32001..-32003 are A2A spec-defined; custom errors
  29. # live at -32050..-32059 (implementation-defined space, clear of the A2A block).
  30. ERR_PARSE, ERR_INVALID_PARAMS, ERR_METHOD_NOT_FOUND = -32700, -32602, -32601
  31. ERR_TASK_NOT_FOUND, ERR_TASK_NOT_CANCELABLE = -32001, -32002 # A2A spec: TaskNotFoundError / TaskNotCancelableError
  32. ERR_UNAUTHORIZED, ERR_RATE_LIMITED, ERR_UNTRUSTED_PEER = -32050, -32051, -32052
  33. # Anti-loop: max inbound turns per context. A2A_MAX_PINGPONG_TURNS env, capped at 20.
  34. _DEFAULT_MAX_PINGPONG, _HARD_MAX_PINGPONG = 5, 20
  35. _RATE_LIMIT_DEFAULT, _RATE_WINDOW = 60, 60.0 # requests per minute, window seconds
  36. def _env_int(name: str, default: int) -> int:
  37. return _coerce_int(os.getenv(name, default), default)
  38. def max_pingpong_turns() -> int:
  39. v = _env_int("A2A_MAX_PINGPONG_TURNS", _DEFAULT_MAX_PINGPONG)
  40. return max(1, min(v, _HARD_MAX_PINGPONG))
  41. def now_iso() -> str:
  42. """ISO 8601 UTC timestamp with millisecond precision (A2A v1.0)."""
  43. return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
  44. def build_agent_card(*, name: str, url: str, description: str, skills: Optional[list[dict]] = None,
  45. streaming: bool = False, push_notifications: bool = False, auth_required: bool = False,
  46. tenant: str = "") -> dict:
  47. """A2A v1.0 Agent Card. ``tenant`` is the optional multi-tenancy routing key on
  48. AgentInterface; when present, clients MUST echo it in request params."""
  49. iface: dict[str, Any] = {"url": url, "protocolBinding": "JSONRPC", "protocolVersion": PROTOCOL_VERSION, **({"tenant": tenant} if tenant else {})}
  50. card: dict[str, Any] = {
  51. "name": name,
  52. "description": description,
  53. "url": url, # convenience for pre-1.0 clients; canonical is supportedInterfaces
  54. "version": "1.0.0",
  55. "provider": {"organization": os.getenv("A2A_PROVIDER_ORG", "Hermes Agent"), "url": os.getenv("A2A_PROVIDER_URL", "") or url},
  56. "supportedInterfaces": [iface],
  57. "capabilities": {"streaming": streaming, "pushNotifications": push_notifications,
  58. "stateTransitionHistory": False, "extendedAgentCard": False},
  59. "defaultInputModes": ["text/plain"], "defaultOutputModes": ["text/plain"], "skills": skills or [],
  60. }
  61. if auth_required:
  62. card["securitySchemes"] = {"bearer": {"type": "http", "scheme": "bearer"}}
  63. card["security"] = [{"bearer": []}]
  64. return card
  65. def skills_from_toolsets(toolsets: list[str] | dict[str, list[str]] | None) -> list[dict]:
  66. """A2A skill descriptors from toolset names or a toolset -> tool-names mapping (tool names
  67. become tags, max 10)."""
  68. if not isinstance(toolsets, dict):
  69. toolsets = {ts: [] for ts in set(toolsets or [])}
  70. skills = [{"id": f"toolset.{name}", "name": name, "description": f"Hermes '{name}' capabilities",
  71. "tags": [name] + [str(t) for t in (toolsets[name] or [])][:10]} for name in sorted(toolsets)]
  72. return skills or [{"id": "general", "name": "general", "description": "General-purpose conversational agent", "tags": ["general"]}]
  73. def jsonrpc_result(req_id: Any, result: Any) -> dict:
  74. return {"jsonrpc": "2.0", "id": req_id, "result": result}
  75. def jsonrpc_error(req_id: Any, code: int, message: str) -> dict:
  76. return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}}
  77. def send_message_response(payload: dict) -> dict:
  78. """v1.0 SendMessageResponse oneof: exactly one of ``task`` / ``message``."""
  79. if isinstance(payload, dict) and payload.get("status") and payload.get("id"):
  80. return {"task": payload}
  81. return {"message": payload}
  82. def unwrap_send_message_response(result: Any) -> Any:
  83. """Task/Message inside a v1.0 response; legacy bare payloads pass through."""
  84. if isinstance(result, dict):
  85. if isinstance(result.get("task"), dict):
  86. return result["task"]
  87. if isinstance(result.get("message"), dict):
  88. return result["message"]
  89. return result
  90. def stream_task(task: dict) -> dict:
  91. """v1.0 StreamResponse with a task member."""
  92. return {"task": task}
  93. def new_task_id() -> str:
  94. return "task-" + uuid.uuid4().hex[:16]
  95. def new_context_id() -> str:
  96. return "ctx-" + uuid.uuid4().hex[:16]
  97. def message_context_id(scope: str, message_id: str) -> str:
  98. """The context a first message without a ``contextId`` opens. Named by the message, so a retry
  99. of that send after a timeout reopens the same context instead of a fresh one."""
  100. return "ctx-" + hashlib.sha256(f"{scope}\0{message_id}".encode()).hexdigest()[:16]
  101. def text_part(text: str) -> dict:
  102. """v1.0 text Part (member-presence discriminated, no ``kind``)."""
  103. return {"text": text, "mediaType": "text/plain"}
  104. def text_message(role: str, text: str, context_id: str = "") -> dict:
  105. """A2A v1.0 Message with a single text Part."""
  106. msg: dict[str, Any] = {"role": role, "parts": [text_part(text)], "messageId": uuid.uuid4().hex}
  107. if context_id:
  108. msg["contextId"] = context_id
  109. return msg
  110. def _file_note(fname: str, body: str, mtype: str) -> str:
  111. label = f"[file: {fname}]" if fname else "[file]"
  112. return f"{label} {body}" + (f" ({mtype})" if mtype else "")
  113. def _json_or_str(data: Any) -> str:
  114. try:
  115. return json.dumps(data, ensure_ascii=False, default=str)
  116. except (TypeError, ValueError):
  117. return str(data)
  118. def extract_text(message_or_params: dict) -> str:
  119. """Concatenated text from an A2A Message / Task-result / params payload. v1.0, v0.3
  120. (``kind``) and pre-0.3 (``type``) Parts all carry ``text``; file Parts render as
  121. URL/filename (raw base64 noted, not decoded); data Parts render their JSON."""
  122. msg = message_or_params.get("message", message_or_params)
  123. chunks = []
  124. for part in msg.get("parts", []) if isinstance(msg, dict) else []:
  125. if not isinstance(part, dict):
  126. continue
  127. if isinstance(txt := part.get("text"), str):
  128. chunks.append(txt)
  129. elif isinstance(url := part.get("url"), str) and url:
  130. chunks.append(_file_note(part.get("filename") or part.get("name") or "", url,
  131. part.get("mediaType") or part.get("mimeType") or ""))
  132. elif isinstance(v03 := part.get("file"), dict) and isinstance(v03.get("fileWithUri"), str):
  133. chunks.append(_file_note(v03.get("name") or "", v03["fileWithUri"], v03.get("mimeType") or ""))
  134. elif isinstance(part.get("raw"), str):
  135. chunks.append(_file_note(part.get("filename") or "", f"{len(part['raw'])} bytes base64-encoded",
  136. part.get("mediaType") or ""))
  137. elif (data := part.get("data")) is not None:
  138. chunks.append(f"[data ({part.get('mediaType') or 'application/json'})]\n{_json_or_str(data)}")
  139. return "\n".join(chunks).strip()
  140. def extract_message_id(params: dict) -> str:
  141. """v1.0 puts messageId inside the Message; a peer retrying a send repeats it."""
  142. msg = params.get("message") or {}
  143. return str(msg.get("messageId") or "") if isinstance(msg, dict) else ""
  144. def extract_context_id(params: dict) -> str:
  145. """v1.0 puts contextId inside the Message; tolerate legacy top-level."""
  146. msg = params.get("message") or {}
  147. return (str(msg.get("contextId") or "") if isinstance(msg, dict) else "") or str(params.get("contextId") or "")
  148. def build_task(task_id: str, context_id: str, state: str, agent_text: str = "", *, created_at: str = "") -> dict:
  149. """A2A v1.0 Task. ``created_at`` is accepted but NOT serialized: the v1.0 Task proto has no
  150. createdAt and strict ProtoJSON parsers (a2a-sdk) reject unknown fields."""
  151. task: dict[str, Any] = {"id": task_id, "contextId": context_id, "status": {"state": state, "timestamp": now_iso()}}
  152. if agent_text:
  153. task["status"]["message"] = text_message(ROLE_AGENT, agent_text, context_id)
  154. if state == STATE_COMPLETED:
  155. task["artifacts"] = [{"artifactId": uuid.uuid4().hex, "parts": [text_part(agent_text)]}]
  156. return task
  157. def status_update(task_id: str, context_id: str, state: str, text: str = "") -> dict:
  158. """v1.0 StreamResponse with a statusUpdate member."""
  159. status: dict[str, Any] = {"state": state, "timestamp": now_iso()}
  160. if text:
  161. status["message"] = text_message(ROLE_AGENT, text, context_id)
  162. return {"statusUpdate": {"taskId": task_id, "contextId": context_id, "status": status}}
  163. def artifact_update(task_id: str, context_id: str, text: str) -> dict:
  164. """v1.0 StreamResponse with an artifactUpdate member."""
  165. artifact = {"artifactId": uuid.uuid4().hex, "parts": [text_part(text)]}
  166. return {"artifactUpdate": {"taskId": task_id, "contextId": context_id, "artifact": artifact}}
  167. def sse_data(payload: dict, req_id: Any = None) -> str:
  168. """One StreamResponse as an SSE data frame. §9.4 requires a full JSON-RPC envelope (a2a-sdk
  169. breaks on bare StreamResponses); ``req_id=None`` is the legacy no-envelope fallback."""
  170. envelope = jsonrpc_result(req_id, payload) if req_id is not None else payload
  171. return f"data: {json.dumps(envelope, ensure_ascii=False)}\n\n"
  172. def sse_done() -> str:
  173. """Stream-closure marker as an SSE *comment* — ``data: {}`` would make JSON-RPC clients parse."""
  174. return ": done\n\n"
  175. class TurnTracker:
  176. """Counts inbound turns per context_id; beyond max_pingpong_turns() the adapter rejects."""
  177. _TTL = 3600 # prune contexts idle longer than 1 hour
  178. def __init__(self) -> None:
  179. self._turns: dict[str, tuple[int, float]] = {} # context_id -> (count, last_seen)
  180. self._lock = threading.Lock()
  181. def track(self, context_id: str) -> int:
  182. """Increment and return the turn count; prunes stale contexts."""
  183. with self._lock:
  184. now = time.time()
  185. self._turns = {cid: v for cid, v in self._turns.items() if now - v[1] <= self._TTL}
  186. count = self._turns.get(context_id, (0, now))[0] + 1
  187. self._turns[context_id] = (count, now)
  188. return count
  189. def reset(self, context_id: str) -> None:
  190. with self._lock:
  191. self._turns.pop(context_id, None)
  192. class RateLimiter:
  193. """Sliding-window request limiter, one bucket per authenticated identity."""
  194. def __init__(self) -> None:
  195. self._buckets: dict[str, deque[float]] = defaultdict(deque)
  196. self._lock = threading.Lock()
  197. def allow(self, identity: str) -> bool:
  198. with self._lock:
  199. limit = max(1, _env_int("A2A_RATE_LIMIT", _RATE_LIMIT_DEFAULT))
  200. now = time.time()
  201. bucket = self._buckets[identity]
  202. while bucket and now - bucket[0] > _RATE_WINDOW:
  203. bucket.popleft()
  204. if len(bucket) >= limit:
  205. return False
  206. bucket.append(now)
  207. return True
  208. class Metrics:
  209. """Counters for A2A operations (module singleton ``metrics`` shared by the inbound adapter
  210. and outbound tools; not persisted)."""
  211. _COUNTERS = ("inbound_total", "outbound_total", "streams_started", "push_sent", "push_failed",
  212. "tasks_completed", "tasks_failed", "anti_loop_triggers", "rate_limit_triggers")
  213. def __init__(self) -> None:
  214. for name in self._COUNTERS:
  215. setattr(self, name, 0)
  216. self._start_time = time.time()
  217. self._latencies: deque[float] = deque(maxlen=100) # last 100 completed inbound tasks
  218. def record_latency(self, seconds: float) -> None:
  219. self._latencies.append(seconds)
  220. def avg_latency(self) -> float:
  221. return sum(self._latencies) / len(self._latencies) if self._latencies else 0.0
  222. def snapshot(self) -> dict[str, Any]:
  223. return {"uptime_seconds": round(time.time() - self._start_time, 1), **{n: getattr(self, n) for n in self._COUNTERS},
  224. "avg_latency_ms": round(self.avg_latency() * 1000, 1)}
  225. metrics = Metrics()
  226. class TaskStore:
  227. """In-memory A2A tasks, kept after completion for tasks/get. Records carry agent slug +
  228. tenant; readers pass a scope and get not-found outside it (spec authz rule)."""
  229. _MAX_TERMINAL = 500
  230. def __init__(self) -> None:
  231. self._tasks: OrderedDict[str, dict[str, Any]] = OrderedDict()
  232. self._watchers: dict[str, list[Future]] = {}
  233. self._lock = threading.Lock()
  234. @staticmethod
  235. def _in_scope(rec: dict, agent_slug: str = "", tenant: str = "") -> bool:
  236. return not ((agent_slug and rec.get("agent_slug", "") != agent_slug) or (tenant and rec.get("tenant", "") != tenant))
  237. def _scoped(self, task_id: str, agent_slug: str = "", tenant: str = "") -> Optional[dict]:
  238. """Live record if visible in scope. Caller holds the lock."""
  239. rec = self._tasks.get(task_id)
  240. return rec if rec and self._in_scope(rec, agent_slug, tenant) else None
  241. def _push_rec(self, task_id: str, config_id: str = "", agent_slug: str = "", tenant: str = "") -> Optional[dict]:
  242. """Scoped record that has a push config (matching ``config_id`` if given). Caller holds the lock."""
  243. rec = self._scoped(task_id, agent_slug, tenant)
  244. if rec and rec.get("push_url") and (not config_id or rec.get("push_config_id") == config_id):
  245. return rec
  246. return None
  247. @staticmethod
  248. def _push_config_view(rec: dict) -> dict:
  249. return {"configId": rec.get("push_config_id") or "", "taskId": rec["task_id"],
  250. "createdAt": rec.get("created_iso", ""), "pushNotificationConfig": {"url": rec.get("push_url") or ""}}
  251. def create(self, task_id: str, context_id: str, peer: str, agent_slug: str = "", tenant: str = "",
  252. input_id: str = "") -> dict:
  253. """``input_id``: the owner admission a forwarded task was sent as (empty for local tasks)."""
  254. rec = {"task_id": task_id, "context_id": context_id, "peer": peer, "agent_slug": agent_slug or "", "tenant": tenant or "",
  255. "input_id": input_id, "state": STATE_SUBMITTED, "reply": "", "created_at": time.time(), "created_iso": now_iso(), "push_url": "", "push_config_id": ""}
  256. with self._lock:
  257. self._tasks[task_id] = rec
  258. return dict(rec)
  259. def set_state(self, task_id: str, state: str) -> None:
  260. with self._lock:
  261. if (rec := self._tasks.get(task_id)) and rec["state"] not in TERMINAL_STATES:
  262. rec["state"] = state
  263. def set_push_config(self, task_id: str, url: str, agent_slug: str = "", tenant: str = "") -> Optional[dict]:
  264. """Attach a push notification config; returns the stored config or None."""
  265. with self._lock:
  266. if not (rec := self._scoped(task_id, agent_slug, tenant)):
  267. return None
  268. rec["push_url"], rec["push_config_id"] = url, "cfg-" + uuid.uuid4().hex[:12]
  269. return self._push_config_view(rec)
  270. def get_push_config(self, task_id: str, config_id: str = "", agent_slug: str = "", tenant: str = "") -> Optional[dict]:
  271. with self._lock:
  272. return self._push_config_view(rec) if (rec := self._push_rec(task_id, config_id, agent_slug, tenant)) else None
  273. def list_push_configs(self, task_id: str, agent_slug: str = "", tenant: str = "") -> list[dict]:
  274. cfg = self.get_push_config(task_id, "", agent_slug, tenant)
  275. return [cfg] if cfg else []
  276. def delete_push_config(self, task_id: str, config_id: str = "", agent_slug: str = "", tenant: str = "") -> bool:
  277. with self._lock:
  278. rec = self._push_rec(task_id, config_id, agent_slug, tenant)
  279. if rec:
  280. rec["push_url"] = rec["push_config_id"] = ""
  281. return rec is not None
  282. def pop_push_url(self, task_id: str) -> str:
  283. with self._lock:
  284. rec = self._tasks.get(task_id)
  285. if rec:
  286. url, rec["push_url"] = rec["push_url"], ""
  287. return url if rec else ""
  288. def get(self, task_id: str, agent_slug: str = "", tenant: str = "") -> Optional[dict]:
  289. with self._lock:
  290. return dict(rec) if (rec := self._scoped(task_id, agent_slug, tenant)) else None
  291. def complete(self, task_id: str, state: str, reply: str = "") -> Optional[dict]:
  292. """Transition a task to a terminal state. Idempotent."""
  293. with self._lock:
  294. rec = self._tasks.get(task_id)
  295. if not rec or rec["state"] in TERMINAL_STATES:
  296. return None
  297. rec.update(state=state, reply=reply, completed_at=time.time())
  298. watchers = self._watchers.pop(task_id, [])
  299. self._trim_locked()
  300. out = dict(rec)
  301. for fut in watchers:
  302. if not fut.done():
  303. fut.set_result((state, reply))
  304. return out
  305. def watch(self, task_id: str, agent_slug: str = "", tenant: str = "") -> Optional[Future]:
  306. with self._lock:
  307. if not (rec := self._scoped(task_id, agent_slug, tenant)):
  308. return None
  309. fut: Future = Future()
  310. if rec["state"] in TERMINAL_STATES:
  311. fut.set_result((rec["state"], rec.get("reply", "")))
  312. else:
  313. self._watchers.setdefault(task_id, []).append(fut)
  314. return fut
  315. def list(self, context_id: str = "", state: str = "", page_size: int = 50, offset: int = 0,
  316. agent_slug: str = "", tenant: str = "", with_total: bool = False):
  317. """Filtered task page (newest first) as ``(records, next_offset)``, or
  318. ``(records, next_offset, total)`` with ``with_total`` (v1.0 ListTasks totalSize)."""
  319. page_size = max(1, min(int(page_size or 50), 100))
  320. with self._lock:
  321. recs = [dict(r) for r in reversed(self._tasks.values())
  322. if self._in_scope(r, agent_slug, tenant)
  323. and (not context_id or r["context_id"] == context_id) and (not state or r["state"] == state)]
  324. total = len(recs)
  325. page = recs[offset:offset + page_size]
  326. next_offset = offset + page_size if offset + page_size < total else 0
  327. return (page, next_offset, total) if with_total else (page, next_offset)
  328. def fail_orphans(self, timeout_seconds: float = 300, *, exclude: set[str] | None = None) -> list[str]:
  329. excluded = exclude or set()
  330. with self._lock:
  331. stale = [tid for tid, rec in self._tasks.items()
  332. if tid not in excluded and rec["state"] not in TERMINAL_STATES
  333. and time.time() - rec["created_at"] > timeout_seconds]
  334. return [tid for tid in stale if self.complete(tid, STATE_FAILED, "[task orphaned — no reply produced]")]
  335. def _trim_locked(self) -> None:
  336. terminal = [tid for tid, rec in self._tasks.items() if rec["state"] in TERMINAL_STATES]
  337. for tid in terminal[:max(0, len(terminal) - self._MAX_TERMINAL)]:
  338. self._tasks.pop(tid, None)
  339. @staticmethod
  340. def to_task(rec: dict, include_artifacts: bool = True) -> dict:
  341. """Render a stored record as an A2A v1.0 Task."""
  342. task = build_task(rec["task_id"], rec["context_id"], rec["state"], rec.get("reply", ""),
  343. created_at=rec.get("created_iso", ""))
  344. if not include_artifacts:
  345. task.pop("artifacts", None)
  346. return task
  347. def _conv_path(context_id: str) -> Path:
  348. safe = "".join(c for c in (context_id or "default") if c.isalnum() or c in "-_") or "default"
  349. return get_hermes_home() / "a2a_conversations" / f"{safe}.jsonl"
  350. def persist_message(context_id: str, role: str, text: str, task_id: str = "", input_id: str = "") -> None:
  351. """Append one message to the context's on-disk conversation log. Never raises."""
  352. try:
  353. path = _conv_path(context_id)
  354. path.parent.mkdir(parents=True, exist_ok=True)
  355. entry = {"ts": time.time(), "role": role, "text": text, "task_id": task_id, **({"input_id": input_id} if input_id else {})}
  356. with path.open("a", encoding="utf-8") as fh:
  357. fh.write(json.dumps(entry, ensure_ascii=False) + "\n")
  358. except Exception:
  359. pass
  360. def logged_input(context_id: str, input_id: str) -> bool:
  361. """True when the context's durable log already holds the forwarded input ``input_id``."""
  362. # limit=0 slices out[-0:], i.e. every entry.
  363. return any(entry.get("input_id") == input_id for entry in load_conversation(context_id, limit=0))
  364. def load_conversation(context_id: str, limit: int = 50) -> list[dict]:
  365. """Last *limit* messages for a context (empty list if none / unreadable)."""
  366. try:
  367. lines = _conv_path(context_id).read_text(encoding="utf-8-sig").splitlines()
  368. except Exception:
  369. return []
  370. out: list[dict] = []
  371. for line in lines:
  372. if line.strip():
  373. try:
  374. entry = json.loads(line)
  375. except json.JSONDecodeError:
  376. continue
  377. if isinstance(entry, dict):
  378. out.append(entry)
  379. return out[-limit:]
  380. def list_conversations() -> list[str]:
  381. """Context-ids that have persisted conversations."""
  382. return sorted(p.stem for p in (get_hermes_home() / "a2a_conversations").glob("*.jsonl"))