session_a2a.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. """Profile forwarding through the canonical owner, with exact conversation identity."""
  2. import asyncio
  3. from contextvars import ContextVar
  4. from dataclasses import asdict, replace
  5. from functools import partial
  6. import hashlib
  7. import json
  8. import logging
  9. from pathlib import Path
  10. from gateway.session_contract import SessionRef, Submission
  11. from hermes_state_runtime import RuntimeStoreError
  12. logger = logging.getLogger(__name__)
  13. _forward_identity = ContextVar('a2a_forward_identity', default=None)
  14. def build_forward_policy(params, config, *, private_secrets):
  15. """Only the forwarding handler can mint this policy, never session.create JSON."""
  16. from gateway.session_policy import build_policy
  17. identity = _forward_identity.get()
  18. if identity is None or set(params) != {'source', 'request_id'}:
  19. raise RuntimeStoreError('invalid_params')
  20. policy = build_policy(dict(params, source='cli'), config, private_secrets=private_secrets)
  21. request = json.loads(policy.request_json)
  22. request.update(source='a2a', a2a_identity=identity)
  23. return replace(policy, source='a2a', platform='a2a', request_json=json.dumps(request, sort_keys=True))
  24. def is_forward_policy(policy):
  25. if policy is None or policy.source != 'a2a' or policy.platform != 'a2a':
  26. return False
  27. try:
  28. request = json.loads(policy.request_json)
  29. identity = request['a2a_identity']
  30. return (request['source'] == 'a2a' and isinstance(identity, list) and len(identity) == 4
  31. and all(isinstance(value, str) for value in identity))
  32. except (ValueError, KeyError, TypeError):
  33. return False
  34. def forward_author(policy):
  35. """The authenticated peer wrote a forwarded turn, not the local principal hosting it."""
  36. if not is_forward_policy(policy):
  37. return None
  38. peer = json.loads(policy.request_json)['a2a_identity'][2]
  39. return {'id': peer, 'name': peer, 'is_bot': True}
  40. def storage_source(db, source, session_id, fallback):
  41. """Retain the owner's creation label when its LOCAL transport refreshes peer metadata."""
  42. from gateway.config import Platform
  43. if source.platform != Platform.LOCAL:
  44. return fallback
  45. if not str(source.chat_id).startswith('local-'):
  46. # An adopted pre-authority row keeps its historical id as the route (session_local_migration).
  47. from hermes_state_local_migration import LEGACY_PREFIX
  48. with db._read_ctx() as conn:
  49. if conn.execute('SELECT 1 FROM state_meta WHERE key=?', (LEGACY_PREFIX + str(source.chat_id),)).fetchone() is None:
  50. return fallback
  51. from hermes_state_local import local_receipt
  52. receipt = local_receipt(db, source.chat_id)
  53. if session_id not in receipt.get('lineage', [receipt['session_id']]):
  54. raise RuntimeStoreError('admission_conflict')
  55. # Producer labels (a2a, cron, kanban, bot_room, ``--source tool``, finite ``oneshot`` runs) survive the
  56. # refresh: pickers filter on them (kanban/tool/oneshot hidden, cron in its own section). Interactive
  57. # surfaces keep the transport's ``local``, outside the state-owned stale-open sweeps keyed on cli/tui/acp.
  58. label = receipt['policy']['source']
  59. # An adopted pre-authority row (main's cli/tui/gui history) keeps the label main wrote: its
  60. # ``sessions list --source``, ``-c`` and stale-open sweeps key on it, as they did before the upgrade.
  61. # That is the adopted row's own label, which adoption never rewrites: the policy's creation source
  62. # folds main's ``desktop`` into ``gui``, so a Desktop chat (a Bot Chat) was re-sourced on its first turn.
  63. if 'legacy_session_id' in receipt:
  64. root = db.get_session(receipt['legacy_session_id'])
  65. return (root or {}).get('source') or label
  66. from gateway.session_policy import STORED_AS_LOCAL
  67. return fallback if label in STORED_AS_LOCAL else label
  68. async def forward(connection, params):
  69. authority, actor = connection.authority, connection.actor
  70. if actor.profile_id != authority.profile_id:
  71. raise RuntimeStoreError('profile_mismatch')
  72. if not {'session:create', 'session:submit', 'session:read'} <= actor.capabilities:
  73. raise RuntimeStoreError('permission_denied')
  74. fields = {'agent', 'tenant', 'peer', 'context_id', 'input_id', 'text'}
  75. if (set(params) != fields or any(not isinstance(params[k], str) for k in fields)
  76. or any(not params[k] for k in fields - {'tenant'})
  77. or any(len(params[k]) > 1024 for k in fields - {'text'})
  78. or len(params['text']) > 1_048_576):
  79. raise RuntimeStoreError('invalid_params')
  80. identity = [params[k] for k in ('agent', 'tenant', 'peer', 'context_id')]
  81. key = 'a2a:' + hashlib.sha256(json.dumps(identity, separators=(',', ':')).encode()).hexdigest()
  82. from gateway.session_local_recovery import local_identity, restore_local_session
  83. from gateway.session_local import stage_local_session
  84. from gateway.session_runtime_workers import tracked_write
  85. from hermes_state_local import commit_local_session, local_receipt
  86. from hermes_state_mutation_retirement import first_generation
  87. from hermes_state_terminal import identity_key
  88. # A context whose session the user deleted continues on its next generation (the deleted id
  89. # stays retired). An exact retry of an input the deleted session took stays on it and is
  90. # refused there, never run again.
  91. base = key
  92. request_id = lambda n: base if n == 0 else f'{base}:{n}'
  93. pinned = lambda conn, sid: conn.execute('SELECT 1 FROM state_meta WHERE key=?', (
  94. identity_key(actor.subject, sid, params['input_id']),)).fetchone() is not None
  95. generation, sid = first_generation(
  96. authority.db, lambda n: local_identity(authority.profile_id, actor.subject, request_id(n)), pinned=pinned)
  97. key = request_id(generation)
  98. authority._require_admission_open()
  99. if authority.db.get_session(sid) is not None:
  100. receipt = local_receipt(authority.db, sid)
  101. if json.loads(receipt['policy']['request_json']).get('a2a_identity') != identity:
  102. raise RuntimeStoreError('admission_conflict')
  103. ref = restore_local_session(authority, sid)
  104. else:
  105. # Historical `a2a-{agent}-{slug}` titles discarded peer/tenant identity and collapsed
  106. # context characters, and those `hermes chat --source a2a` rows stored no origin, so a
  107. # titled row never proves it belongs to this exact conversation. Never adopt or retitle
  108. # it (that would hand one peer another's history), and never refuse every peer whose
  109. # slug collides: start this identity's own canonical session and leave the old row be.
  110. from plugins.platforms.a2a.adapter import _safe_context_slug
  111. title = f'a2a-{params["agent"]}-{_safe_context_slug(params["context_id"])}'
  112. legacy = authority.db.get_session_by_title(title)
  113. if legacy is not None:
  114. logger.warning('A2A: pre-authority session %s titled %r has no peer identity; '
  115. 'forwarding into a new session instead of adopting it', legacy['id'], title)
  116. token = _forward_identity.set(identity)
  117. try:
  118. ref = stage_local_session(authority, actor, {'source': 'a2a', 'request_id': key})
  119. finally:
  120. _forward_identity.reset(token)
  121. if isinstance(ref, dict): # the creation commit runs off the owner loop (N90); a duplicate converges
  122. await tracked_write(authority, partial(commit_local_session, authority.db, epoch=authority.epoch, receipt=ref))
  123. ref = restore_local_session(authority, ref['session_id'])
  124. if ref.session_id not in connection.subscriptions:
  125. await connection.resume(ref, {})
  126. receipt = await authority.submit(actor, Submission(params['input_id'], ref, {'text': params['text']}, 'queue'))
  127. from gateway.session_results import admission_result
  128. saved = admission_result(authority.db, receipt.admission_id)
  129. return dict(asdict(receipt), session_id=ref.session_id,
  130. result=saved['result'] if saved is not None else None)
  131. async def forward_to_owner(home, *, agent, tenant, peer, context_id, input_id, text, timeout):
  132. """Transport-only caller; a timeout never cancels or re-identifies accepted work."""
  133. from hermes_cli.gateway_client import (GATEWAY_WS_PROTOCOL, GatewayClient, GatewayClientError,
  134. _session_ticket, gateway_ws_target)
  135. from hermes_cli.gateway_runtime import ensure_gateway_runtime
  136. from websockets.asyncio.client import connect
  137. home = await asyncio.to_thread(Path(home).resolve)
  138. async with asyncio.timeout(timeout):
  139. ready = await asyncio.to_thread(ensure_gateway_runtime, home)
  140. if ready.state != 'ready' or ready.endpoint is None:
  141. raise GatewayClientError(f'gateway_{ready.state}:{ready.reason_code or "not_ready"}')
  142. ticket = await asyncio.to_thread(_session_ticket, home, ready.endpoint)
  143. url, protocols = gateway_ws_target(ready.endpoint, ticket)
  144. # Loopback authority dial: never through HTTP(S)_PROXY (websockets>=14 honours it by default).
  145. async with connect(url, subprotocols=protocols, open_timeout=10, max_size=8 * 1024 * 1024,
  146. proxy=None) as ws:
  147. if ws.subprotocol != GATEWAY_WS_PROTOCOL:
  148. raise GatewayClientError('gateway_protocol_mismatch')
  149. async with GatewayClient(ws) as client:
  150. params = dict(agent=agent, tenant=tenant, peer=peer, context_id=context_id, input_id=input_id, text=text)
  151. backoff = .25
  152. while True:
  153. receipt = await client.rpc('a2a.forward', **params)
  154. if receipt['status'] == 'unknown':
  155. raise GatewayClientError('unknown_execution')
  156. if receipt['status'] == 'terminal':
  157. return receipt
  158. # The forward subscribed this socket to the session: wait for the admission's
  159. # completion frame, re-reading the exact durable receipt on a backed-off
  160. # safety tick (a frame lost to a replay gap) instead of a fixed 100 ms poll.
  161. try:
  162. async with asyncio.timeout(backoff):
  163. await _completion(client, receipt['admission_id'])
  164. except TimeoutError:
  165. backoff = min(backoff * 2, 5.0)
  166. async def _completion(client, admission_id):
  167. """Consume projections until this admission's completion frame; a transport error raises."""
  168. while True:
  169. event = await client.events.get()
  170. if isinstance(event, Exception):
  171. raise event
  172. frame = event.get('params') or {}
  173. if frame.get('type') == 'message.complete' and (frame.get('payload') or {}).get('admission_id') == admission_id:
  174. return