The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: forward A2A profile tasks through session authority
Teknium4e3a6bdbb732
diff --git a/gateway/session_a2a.py b/gateway/session_a2a.pynew file mode 100644index 00000000000..49169f95d7c--- /dev/null+++ b/gateway/session_a2a.py@@ -0,0 +1,125 @@+"""Profile forwarding through the canonical owner, with exact conversation identity."""+import asyncio+from contextvars import ContextVar+from dataclasses import asdict, replace+import hashlib+import json+from pathlib import Path++from gateway.session_contract import SessionRef, Submission+from hermes_state_runtime import RuntimeStoreError++_forward_identity = ContextVar('a2a_forward_identity', default=None)+++def build_forward_policy(params, config, *, private_secrets):+ """Only the forwarding handler can mint this policy, never session.create JSON."""+ from gateway.session_policy import build_policy+ identity = _forward_identity.get()+ if identity is None or set(params) != {'source', 'request_id'}:+ raise RuntimeStoreError('invalid_params')+ policy = build_policy(dict(params, source='cli'), config, private_secrets=private_secrets)+ request = json.loads(policy.request_json)+ request.update(source='a2a', a2a_identity=identity)+ return replace(policy, source='a2a', platform='a2a', request_json=json.dumps(request, sort_keys=True))+++def is_forward_policy(policy):+ if policy.source != 'a2a' or policy.platform != 'a2a':+ return False+ try:+ request = json.loads(policy.request_json)+ identity = request['a2a_identity']+ return (request['source'] == 'a2a' and isinstance(identity, list) and len(identity) == 4+ and all(isinstance(value, str) for value in identity))+ except (ValueError, KeyError, TypeError):+ return False+++def storage_source(db, source, session_id, fallback):+ """Retain the owner's native label when its transport refreshes peer metadata."""+ from gateway.config import Platform+ if source.platform != Platform.LOCAL or not str(source.chat_id).startswith('local-'):+ return fallback+ from hermes_state_local import local_receipt+ receipt = local_receipt(db, source.chat_id)+ if session_id not in receipt.get('lineage', [receipt['session_id']]):+ raise RuntimeStoreError('admission_conflict')+ return 'a2a' if receipt['policy']['source'] == 'a2a' else fallback+++async def forward(connection, params):+ authority, actor = connection.authority, connection.actor+ if actor.profile_id != authority.profile_id:+ raise RuntimeStoreError('profile_mismatch')+ if not {'session:create', 'session:submit', 'session:read'} <= actor.capabilities:+ raise RuntimeStoreError('permission_denied')+ fields = {'agent', 'tenant', 'peer', 'context_id', 'input_id', 'text'}+ if (set(params) != fields or any(not isinstance(params[k], str) for k in fields)+ or any(not params[k] for k in fields - {'tenant'})+ or any(len(params[k]) > 1024 for k in fields - {'text'})+ or len(params['text']) > 1_048_576):+ raise RuntimeStoreError('invalid_params')+ identity = [params[k] for k in ('agent', 'tenant', 'peer', 'context_id')]+ key = 'a2a:' + hashlib.sha256(json.dumps(identity, separators=(',', ':')).encode()).hexdigest()+ from gateway.session_local_recovery import local_identity, restore_local_session+ from gateway.session_local import create_local_session+ from hermes_state_local import local_receipt+ sid = local_identity(authority.profile_id, actor.subject, key)+ authority._require_admission_open()+ if authority.db.get_session(sid) is not None:+ receipt = local_receipt(authority.db, sid)+ if json.loads(receipt['policy']['request_json']).get('a2a_identity') != identity:+ raise RuntimeStoreError('admission_conflict')+ ref = restore_local_session(authority, sid)+ else:+ # Historical titles discarded peer identity and collapsed context characters.+ # Never silently adopt somebody else's history or create a replacement for it.+ from plugins.platforms.a2a.adapter import _safe_context_slug+ legacy = authority.db.get_session_by_title(f'a2a-{params["agent"]}-{_safe_context_slug(params["context_id"])}')+ if legacy is not None:+ raise RuntimeStoreError('runtime_coordination_required')+ token = _forward_identity.set(identity)+ try:+ ref = create_local_session(authority, actor, {'source': 'a2a', 'request_id': key})+ finally:+ _forward_identity.reset(token)+ if ref.session_id not in connection.subscriptions:+ await connection.resume(ref, {})+ receipt = await authority.submit(actor, Submission(params['input_id'], ref, {'text': params['text']}, 'queue'))+ from gateway.session_results import admission_result+ saved = admission_result(authority.db, receipt.admission_id)+ return dict(asdict(receipt), session_id=ref.session_id,+ result=saved['result'] if saved is not None else None)+++async def forward_to_owner(home, *, agent, tenant, peer, context_id, input_id, text, timeout):+ """Transport-only caller; a timeout never cancels or re-identifies accepted work."""+ from hermes_cli.gateway_client import GatewayClient, GatewayClientError, _session_ticket+ from hermes_cli.gateway_runtime import ensure_gateway_runtime+ from websockets.asyncio.client import connect+ home = Path(home).resolve()+ async with asyncio.timeout(timeout):+ ready = await asyncio.to_thread(ensure_gateway_runtime, home)+ if ready.state != 'ready' or ready.endpoint is None:+ raise GatewayClientError(f'gateway_{ready.state}:{ready.reason_code or "not_ready"}')+ ticket = await asyncio.to_thread(_session_ticket, home, ready.endpoint)+ url = ready.endpoint.api_origin.replace('https:', 'wss:').replace('http:', 'ws:') + '/api/ws'+ protocols = ['hermes-gateway-v1', 'hermes-gateway-ticket.' + ticket]+ async with connect(url, subprotocols=protocols, open_timeout=10, max_size=8 * 1024 * 1024) as ws:+ if ws.subprotocol != protocols[0]:+ raise GatewayClientError('gateway_protocol_mismatch')+ async with GatewayClient(ws) as client:+ params = dict(agent=agent, tenant=tenant, peer=peer, context_id=context_id, input_id=input_id, text=text)+ while True:+ receipt = await client.rpc('a2a.forward', **params)+ if receipt['status'] == 'unknown':+ raise GatewayClientError('unknown_execution')+ if receipt['status'] == 'terminal':+ return receipt+ # Consume projections while polling the exact durable input receipt.+ while not client.events.empty():+ event = client.events.get_nowait()+ if isinstance(event, Exception):+ raise event+ await asyncio.sleep(.1)diff --git a/plugins/platforms/a2a/adapter.py b/plugins/platforms/a2a/adapter.pyindex 7a0af6dc032..aa86c2e547b 100644--- a/plugins/platforms/a2a/adapter.py+++ b/plugins/platforms/a2a/adapter.py@@ -11,8 +11,6 @@ import jsonimport loggingimport osimport re-import sqlite3-import subprocessimport threadingimport timeimport urllib.parse@@ -126,24 +124,6 @@ def _safe_context_slug(value: str, max_len: int = 96) -> str:return (slug or "ctx")[:max_len]-def _state_db(profile: str, sql: str, params: tuple, log_msg: str, *, commit: bool = False) -> str:- """Run one statement against a profile's state.db; first column of the first row or ""."""- home = _profile_home(profile)- db = os.path.join(home, "state.db") if home else ""- if not db or not os.path.exists(db):- return ""- try:- with contextlib.closing(sqlite3.connect(db, timeout=5)) as con:- cur = con.execute(sql, params)- row = None if commit else cur.fetchone()- if commit:- con.commit()- return str(row[0]) if row else ""- except Exception:- logger.debug(log_msg, exc_info=True)- return ""--class A2ARequestHandler(BaseHTTPRequestHandler):"""HTTP handler for the A2A JSON-RPC surface; all state lives on ``self.server.adapter``."""@@ -271,10 +251,6 @@ class A2AAdapter(BasePlatformAdapter):self._watchdog_stop = threading.Event()# Per-adapter protocol state (not module-global).self.tasks, self._turns, self._rate_limiter = protocol.TaskStore(), protocol.TurnTracker(), protocol.RateLimiter()- # Forwarded profile sessions: (profile, agent_slug, context_id) -> session_id.- self._profile_sessions: Dict[tuple[str, str, str], str] = {}- self._profile_session_locks: Dict[tuple[str, str, str], threading.Lock] = {}- self._profile_session_locks_guard = threading.Lock()# Pending reply futures: task_id -> (context_id, Future). _pending_order keeps per-context# FIFO so adapter.send() — which only knows the context — resolves the oldest task.self._pending: Dict[str, tuple[str, Future]] = {}@@ -481,10 +457,6 @@ class A2AAdapter(BasePlatformAdapter):def _scope_for_agent(self, agent: Optional[dict]) -> tuple[str, str]:return tuple(str((agent or self._agents[""]).get(k) or "") for k in ("slug", "tenant"))- def _forward_lock(self, key: tuple[str, str, str]) -> threading.Lock:- with self._profile_session_locks_guard:- return self._profile_session_locks.setdefault(key, threading.Lock())-def _end_task(self, rec: dict, state: str, text: str, stored_reply: str = "") -> tuple[dict, None]:"""Complete a task immediately (rejected / not ready) and build its terminal Task."""self.tasks.complete(rec["task_id"], state, stored_reply)@@ -514,7 +486,7 @@ class A2AAdapter(BasePlatformAdapter):protocol.metrics.inbound_total += 1self._register_inline_push(task_id, params, agent=agent)if not agent.get("local", True):- reply, state = self._forward_to_profile(agent, peer, context_id, framed)+ reply, state = self._forward_to_profile(agent, peer, context_id, framed, input_id=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"]), Noneif self._loop is None or self._message_handler is None:@@ -531,41 +503,28 @@ class A2AAdapter(BasePlatformAdapter):self.tasks.set_state(task_id, protocol.STATE_WORKING)return None, {"task_id": task_id, "context_id": context_id, "peer": peer, "future": fut, "created_iso": rec["created_iso"], "started": time.time()}- def _forward_to_profile(self, agent: dict, peer: str, context_id: str, framed_text: str) -> tuple[str, str]:- """Forward a routed task to another local profile via ``hermes chat``. First contact creates a- ``source=a2a`` session and titles it deterministically; later turns ``--resume`` that id."""+ def _forward_to_profile(self, agent: dict, peer: str, context_id: str, framed_text: str,+ *, input_id: Optional[str] = None) -> tuple[str, str]:+ """Forward to the destination owner; never open its canonical database here."""+ from gateway.session_a2a import forward_to_ownerprofile = str(agent.get("profile") or agent.get("slug") or "").strip()- slug = str(agent.get("slug") or profile or "agent")- safe_ctx = _safe_context_slug(context_id)- session_title = f"a2a-{slug}-{safe_ctx}"- key = (profile or "default", slug, safe_ctx)- timeout = int(agent.get("timeout") or _reply_timeout())- with self._forward_lock(key):- session_id = self._profile_sessions.get(key) or _state_db(- profile, "SELECT id FROM sessions WHERE title = ? ORDER BY started_at DESC LIMIT 1",- (session_title,), "A2A: could not lookup forwarded session")- cmd = ["hermes", "chat", "-q", framed_text, "-Q", "--source", "a2a"] + (["--resume", session_id] if session_id else [])- env = {**os.environ, "HERMES_A2A_PEER": peer}- if home := _profile_home(profile):- env["HERMES_HOME"] = home- start = time.time()- try:- proc = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace",- timeout=timeout, env=env, check=False, stdin=subprocess.DEVNULL)- except subprocess.TimeoutExpired:- return "[profile did not reply in time]", protocol.STATE_FAILED- except Exception as e:- return security.redact_outbound(f"Profile dispatch failed: {e}"), protocol.STATE_FAILED- if proc.returncode != 0:- msg = (proc.stderr or proc.stdout or f"profile exited {proc.returncode}").strip()- return security.redact_outbound(msg[-2000:]), protocol.STATE_FAILED- if not session_id and (session_id := _state_db(- profile, "SELECT id FROM sessions WHERE source = 'a2a' AND started_at >= ? ORDER BY started_at DESC LIMIT 1",- (start - 2.0,), "A2A: could not find latest forwarded session")):- self._profile_sessions[key] = session_id- _state_db(profile, "UPDATE sessions SET title = ? WHERE id = ?", (session_title, session_id),- "A2A: could not title forwarded session", commit=True)- return security.redact_outbound((proc.stdout or "").strip()), protocol.STATE_COMPLETED+ home = _profile_home(profile)+ if not home:+ return "[profile unavailable]", protocol.STATE_FAILED+ try:+ receipt = asyncio.run(forward_to_owner(+ home, agent=str(agent.get("slug") or profile or "agent"),+ tenant=str(agent.get("tenant") or ""), peer=peer, context_id=context_id,+ input_id=input_id or protocol.new_task_id(), text=framed_text,+ timeout=int(agent.get("timeout") or _reply_timeout())))+ except TimeoutError:+ return "[profile reply unverified; accepted work was not cancelled]", protocol.STATE_FAILED+ except Exception as exc:+ return security.redact_outbound(f"Profile dispatch unverified: {exc}"), protocol.STATE_FAILED+ result = receipt.get('result') or {}+ completed = receipt.get('outcome') == 'completed' and not result.get('failed')+ return (security.redact_outbound(result.get('final_response') or ''),+ protocol.STATE_COMPLETED if completed else protocol.STATE_FAILED)def _record_outcome(self, task_id: str, context_id: str, peer: str, state: str, reply: str,started: Optional[float] = None) -> None:diff --git a/tests/gateway/test_session_a2a.py b/tests/gateway/test_session_a2a.pynew file mode 100644index 00000000000..ed1ea3f9ff9--- /dev/null+++ b/tests/gateway/test_session_a2a.py@@ -0,0 +1,96 @@+"""Forwarded profile identity is owner-bound, not a title or latest-row guess."""+import json+from types import SimpleNamespace++import pytest++from gateway.session_controls import AuthorityConnection+++async def test_forwarded_identity_survives_reconnect_without_policy_override(tmp_path, monkeypatch):+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ import gateway.run as run+ from gateway.session_policy import build_policy+ from hermes_state_runtime import RuntimeStoreError++ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'model': {'default': 'fixture'}, 'platform_toolsets': {'cli': []}})+ monkeypatch.setattr(run, '_resolve_gateway_model', lambda config: 'fixture')+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ runner = SimpleNamespace(adapters={}, session_store=store, _session_db=store._db, _draining=False)+ authority = await initialize_session_authority(runner, profile_id='target', instance_id='test')+ db = authority.db+ authority._schedule = lambda ref: None+ transport = SimpleNamespace(write=lambda frame: None)+ conn = AuthorityConnection(authority, transport, {'user_id': 'producer'})+ params = dict(agent='dev', tenant='team', peer='alice', context_id='ctx/a', input_id='first', text='hello')+ response = await conn.dispatch({'id': 1, 'method': 'a2a.forward', 'params': params})+ assert 'result' in response, response+ first = response['result']+ sid = first['session_id']+ live = authority.sessions[sid]+ store._record_gateway_session_peer(sid, live.route, live.source)+ assert db.get_session(sid)['source'] == 'a2a'+ policy = runner.adapters[next(iter(runner.adapters))].policies[sid]+ assert policy.source == policy.platform == 'a2a'+ assert json.loads(policy.request_json)['a2a_identity'] == ['dev', 'team', 'alice', 'ctx/a']+ # Neither changed defaults nor a fresh transport may turn resume into a policy override.+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'model': {'default': 'changed'}})+ again = AuthorityConnection(authority, transport, {'user_id': 'producer'})+ repeated = await again.dispatch({'id': 2, 'method': 'a2a.forward', 'params': dict(params)})+ assert repeated['result']['admission_id'] == first['admission_id']+ second = await again.dispatch({'id': 3, 'method': 'a2a.forward', 'params': dict(params, input_id='second', text='again')})+ assert second['result']['session_id'] == sid+ assert second['result']['admission_id'] != first['admission_id']+ assert runner.adapters[next(iter(runner.adapters))].policies[sid] == policy+ # Source spelling alone must never grant producer policy.+ with pytest.raises(RuntimeStoreError):+ build_policy({'source': 'a2a'}, {})+ await conn.close()+ await again.close()+ db.close()+++async def test_forwarding_does_not_merge_lossy_context_or_peer_identity(tmp_path, monkeypatch):+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ import gateway.run as run++ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'model': {'default': 'fixture'}, 'platform_toolsets': {'cli': []}})+ monkeypatch.setattr(run, '_resolve_gateway_model', lambda config: 'fixture')+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ runner = SimpleNamespace(adapters={}, session_store=store, _session_db=store._db, _draining=False)+ authority = await initialize_session_authority(runner, profile_id='target', instance_id='test')+ db = authority.db+ authority._schedule = lambda ref: None+ conn = AuthorityConnection(authority, SimpleNamespace(write=lambda frame: None), {'user_id': 'producer'})+ ids = []+ for peer, context in [('alice', 'ctx/a'), ('alice', 'ctx-a'), ('bob', 'ctx/a')]:+ result = await conn.dispatch({'id': 1, 'method': 'a2a.forward', 'params': dict(+ agent='dev', tenant='team', peer=peer, context_id=context, input_id='first', text='hello')})+ assert 'result' in result, result+ ids.append(result['result']['session_id'])+ assert len(set(ids)) == len(ids)+ conflict = await conn.dispatch({'id': 2, 'method': 'a2a.forward', 'params': dict(+ agent='dev', tenant='team', peer='alice', context_id='ctx/a', input_id='first', text='changed')})+ assert conflict['error']['message'] == 'admission_conflict'+ db.create_session('legacy', source='a2a')+ db.set_session_title('legacy', 'a2a-dev-old-context')+ legacy = await conn.dispatch({'id': 3, 'method': 'a2a.forward', 'params': dict(+ agent='dev', tenant='team', peer='alice', context_id='old/context', input_id='first', text='hello')})+ assert legacy['error']['message'] == 'runtime_coordination_required'+ assert db.get_session('legacy')['title'] == 'a2a-dev-old-context'+ denied = AuthorityConnection(authority, SimpleNamespace(write=lambda frame: None),+ {'user_id': 'reader', 'capabilities': ['session:read']})+ result = await denied.dispatch({'id': 1, 'method': 'a2a.forward', 'params': dict(+ agent='dev', tenant='team', peer='alice', context_id='ctx/a', input_id='first', text='hello')})+ assert result['error']['message'] == 'permission_denied'+ await conn.close()+ await denied.close()+ db.close()diff --git a/tests/plugins/test_a2a_plugin.py b/tests/plugins/test_a2a_plugin.pyindex 6c19b80ddf9..1d4aadcd2e3 100644--- a/tests/plugins/test_a2a_plugin.py+++ b/tests/plugins/test_a2a_plugin.py@@ -1376,7 +1376,7 @@ class TestMultiAgentRouting:}))agent = adapter._agents["dev"]- def fake_forward(agent_arg, peer, context_id, framed_text):+ def fake_forward(agent_arg, peer, context_id, framed_text, *, input_id):assert agent_arg["slug"] == "dev"assert peer == "peer-x"assert "hello" in framed_text@@ -1581,54 +1581,31 @@ class TestV1SpecRegressionFixes:assert "one" in adapter._agentsassert "two" not in adapter._agents- def test_forward_to_profile_first_contact_creates_then_resumes_fake_hermes(self, monkeypatch, tmp_path):+ def test_forward_to_profile_uses_receipted_owner_not_local_writer(self, monkeypatch, tmp_path):from plugins.platforms.a2a.adapter import A2AAdapterfrom gateway.config import PlatformConfig+ from gateway import session_a2a- profile_home = tmp_path / "profile"- profile_home.mkdir()- db = profile_home / "state.db"- import sqlite3- con = sqlite3.connect(db)- con.execute("CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT, started_at REAL, title TEXT)")- con.commit(); con.close()-- fakebin = tmp_path / "bin"- fakebin.mkdir()- calls = tmp_path / "calls.jsonl"- hermes = fakebin / "hermes"- hermes.write_text("""#!/usr/bin/env python3-import json, os, sqlite3, sys, time-calls = os.environ['FAKE_HERMES_CALLS']-with open(calls, 'a') as f:- f.write(json.dumps(sys.argv[1:]) + '\\n')-home = os.environ['HERMES_HOME']-con = sqlite3.connect(os.path.join(home, 'state.db'))-if '--resume' not in sys.argv:- con.execute('INSERT INTO sessions (id, source, started_at, title) VALUES (?, ?, ?, ?)', ('sess-1', 'a2a', time.time(), None))- con.commit()-print('fake reply')-""")- hermes.chmod(0o755)- monkeypatch.setenv("PATH", str(fakebin) + os.pathsep + os.environ.get("PATH", ""))- monkeypatch.setenv("FAKE_HERMES_CALLS", str(calls))- monkeypatch.setattr("plugins.platforms.a2a.adapter._profile_home", lambda profile: str(profile_home))-+ calls = []+ async def owner(home, **params):+ calls.append((home, params))+ return {'status': 'terminal', 'outcome': 'completed',+ 'result': {'final_response': 'owner reply'}}+ monkeypatch.setattr(session_a2a, 'forward_to_owner', owner)+ monkeypatch.setattr('plugins.platforms.a2a.adapter._profile_home', lambda profile: str(tmp_path))adapter = A2AAdapter(PlatformConfig(enabled=True, extra={- "agents": {"dev": {"profile": "dev", "tenant": "dev", "timeout": 5}}+ 'agents': {'dev': {'profile': 'dev', 'tenant': 'team', 'timeout': 5}}}))- agent = adapter._agents["dev"]- reply, state = adapter._forward_to_profile(agent, "peer", "ctx/unsafe value", "hello")- assert (reply, state) == ("fake reply", protocol.STATE_COMPLETED)- reply2, state2 = adapter._forward_to_profile(agent, "peer", "ctx/unsafe value", "again")- assert (reply2, state2) == ("fake reply", protocol.STATE_COMPLETED)- argv_lines = [json.loads(line) for line in calls.read_text().splitlines()]- assert "--resume" not in argv_lines[0]- assert argv_lines[1][argv_lines[1].index("--resume") + 1] == "sess-1"- con = sqlite3.connect(db)- title = con.execute("SELECT title FROM sessions WHERE id='sess-1'").fetchone()[0]- con.close()- assert title == "a2a-dev-ctx-unsafe-value"+ reply, state = adapter._forward_to_profile(adapter._agents['dev'], 'peer', 'ctx/unsafe value', 'hello')+ assert (reply, state) == ('owner reply', protocol.STATE_COMPLETED)+ assert calls[0][0] == str(tmp_path)+ assert calls[0][1]['context_id'] == 'ctx/unsafe value'+ assert calls[0][1]['peer'] == 'peer'+ assert calls[0][1]['agent'] == 'dev'+ assert calls[0][1]['tenant'] == 'team'+ assert calls[0][1]['input_id']+ assert not (tmp_path / 'state.db').exists()+# --------------------------------------------------------------------------