The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): forwarded A2A turns and managed-worker turns carry their author
erosika20754c0f3881
diff --git a/agent/managed_worker.py b/agent/managed_worker.pyindex 04c052fe92c..8396fc163cd 100644--- a/agent/managed_worker.py+++ b/agent/managed_worker.py@@ -12,7 +12,7 @@ import threadingMAX_FRAME = 4 * 1024 * 1024BOOTSTRAP_FIELDS = {'version', 'home', 'scope', 'policy', 'api_key', 'text', 'route', 'user_id', 'chat_id',- 'safe_mode', 'ignore_user_config'}+ 'turn_author', 'safe_mode', 'ignore_user_config'}def read_frame(stream):@@ -47,6 +47,10 @@ def validate_bootstrap(frame):or (frame['safe_mode'] and not frame['ignore_user_config'])or (frame['api_key'] is not None and not isinstance(frame['api_key'], str))):raise ValueError('invalid_managed_worker_bootstrap')+ from agent.turn_author import parse_turn_author+ if frame['turn_author'] is not None and (not isinstance(frame['turn_author'], dict)+ or parse_turn_author(frame['turn_author']) is None):+ raise ValueError('invalid_managed_worker_bootstrap')return framediff --git a/gateway/session_a2a.py b/gateway/session_a2a.pyindex 49169f95d7c..89d55b6205d 100644--- a/gateway/session_a2a.py+++ b/gateway/session_a2a.py@@ -36,6 +36,14 @@ def is_forward_policy(policy):return False+def forward_author(policy):+ """The authenticated peer wrote a forwarded turn, not the local principal hosting it."""+ if not is_forward_policy(policy):+ return None+ peer = json.loads(policy.request_json)['a2a_identity'][2]+ return {'id': peer, 'name': peer, 'is_bot': True}++def storage_source(db, source, session_id, fallback):"""Retain the owner's native label when its transport refreshes peer metadata."""from gateway.config import Platformdiff --git a/gateway/session_ingress.py b/gateway/session_ingress.pyindex b8a58bd92b4..4ace58dc6e7 100644--- a/gateway/session_ingress.py+++ b/gateway/session_ingress.py@@ -21,12 +21,25 @@ async def admit_message(authority, event):return await asyncio.shield(waiter)+def row_turn_author(policy, row):+ """Who wrote the admitted input, for memory attribution only: the producer's stamp when it+ left one, else the forwarded peer bound into the session policy; never grants anything."""+ payload = row['payload']+ for key in ('local_automation_v1', 'api_turn_v1'):+ author = (payload.get(key) or {}).get('turn_author')+ if author is not None:+ return author+ from gateway.session_a2a import forward_author+ return forward_author(policy)++async def execute_admission(authority, ref, row):from gateway.session_policy import policy_for_sourcepolicy = policy_for_source(authority.runner, authority.sessions[ref.session_id].source)if policy is not None and policy.source == 'cron':from gateway.session_cron import executereturn await execute(authority, ref, row, policy)+ local_policy = policyfrom gateway.session_managed_worker import managed_policy, execute_managedpolicy = managed_policy(authority, ref)if policy is not None:@@ -60,7 +73,8 @@ async def execute_admission(authority, ref, row):from gateway.session_api_turn import api_execution, prepare_api_executionfrom gateway.session_results import execution_resultis_api = live.source.platform == Platform.API_SERVER- author_token = admission_author.set(event.metadata.get('turn_author'))+ author = event.metadata.get('turn_author')+ author_token = admission_author.set(author if author is not None else row_turn_author(local_policy, row))api_token = api_execution.set(None)captured = {}result_token = execution_result.set(captured)diff --git a/gateway/session_kanban.py b/gateway/session_kanban.pyindex 8b02ec139f5..42931750e76 100644--- a/gateway/session_kanban.py+++ b/gateway/session_kanban.py@@ -162,7 +162,9 @@ def bind_worker_context(frame):def run_worker_turns(agent, frame, history):context = json.loads(frame['policy'].get('kanban_json') or 'null')if context is None:- return agent.run_conversation(frame['text'], conversation_history=history)+ author = frame.get('turn_author')+ return agent.run_conversation(frame['text'], conversation_history=history,+ **({'turn_author': author} if author is not None else {}))from hermes_cli.kanban_db import KANBAN_RATE_LIMIT_EXIT_CODEcode = 1try:diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.pyindex ec3a10ee57f..529d0fc9b52 100644--- a/gateway/session_managed_worker.py+++ b/gateway/session_managed_worker.py@@ -42,6 +42,7 @@ def managed_policy(authority, ref):def _bootstrap(authority, ref, row, policy, scope):+ from gateway.session_ingress import row_turn_authorfrom gateway.session_policy import launch_keyfrom gateway.session_policy_credentials import recover_config_secretsterminal = json.loads(policy.terminal_json)@@ -57,6 +58,7 @@ def _bootstrap(authority, ref, row, policy, scope):'text': row['payload']['text'], 'route': live.route,**({'attachments_v1': row['payload']['attachments_v1']} if 'attachments_v1' in row['payload'] else {}),'user_id': live.source.user_id, 'chat_id': live.source.chat_id,+ 'turn_author': row_turn_author(policy, row),'safe_mode': policy.safe_mode, 'ignore_user_config': policy.ignore_user_config}diff --git a/tests/gateway/test_managed_worker_turn_author.py b/tests/gateway/test_managed_worker_turn_author.pynew file mode 100644index 00000000000..b74ab72ba13--- /dev/null+++ b/tests/gateway/test_managed_worker_turn_author.py@@ -0,0 +1,48 @@+"""A managed worker's turn carries its author so memory providers attribute it like the owner path."""+import json+import os+from types import SimpleNamespace++import pytest+++def _policy(tmp_path):+ from gateway.session_local import _bypass_policy+ return _bypass_policy({'cwd': str(tmp_path), 'model': 'safe-fixture', 'provider': 'custom',+ 'base_url': 'http://127.0.0.1:9/v1', 'ignore_user_config': True}, private_secrets={})+++def test_bootstrap_frame_carries_the_admitted_author(tmp_path, monkeypatch):+ from gateway import session_managed_worker as smw+ from agent.managed_worker import validate_bootstrap++ monkeypatch.setattr('gateway.session_policy.launch_key', lambda authority, policy: None)+ live = SimpleNamespace(source=SimpleNamespace(user_id='u', chat_id='c'), route='route')+ authority = SimpleNamespace(sessions={'sid': live}, runner=None, profile_id=str(tmp_path))+ ref = SimpleNamespace(session_id='sid')+ scope = {'profile_id': str(tmp_path), 'session_id': 'sid', 'execution_id': 'x', 'generation': 1,+ 'pid': os.getpid(), 'birth': 0, 'secret': 's', 'epoch': 1}+ author = {'id': 'bot-7', 'name': 'Seven', 'is_bot': True}+ row = {'payload': {'text': 'hi', 'local_automation_v1': {'turn_author': author}}}+ frame = smw._bootstrap(authority, ref, row, _policy(tmp_path), scope)+ assert frame['turn_author'] == author+ wire = json.loads(json.dumps(frame))+ assert validate_bootstrap(wire) is wire+ plain = smw._bootstrap(authority, ref, {'payload': {'text': 'hi'}}, _policy(tmp_path), scope)+ assert plain['turn_author'] is None+ assert validate_bootstrap(json.loads(json.dumps(plain)))['turn_author'] is None+ for bad in ('bot-7', {}, {'is_bot': True}):+ with pytest.raises(ValueError):+ validate_bootstrap({**wire, 'turn_author': bad})+++def test_worker_turn_passes_the_author_to_run_conversation():+ from gateway.session_kanban import run_worker_turns++ seen = []+ agent = SimpleNamespace(run_conversation=lambda text, **kw: seen.append((text, kw)) or {'final_response': 'ok'})+ author = {'id': 'alice', 'name': 'alice', 'is_bot': True}+ run_worker_turns(agent, {'policy': {'kanban_json': None}, 'text': 'hello', 'turn_author': author}, [])+ run_worker_turns(agent, {'policy': {'kanban_json': None}, 'text': 'again', 'turn_author': None}, [])+ assert seen == [('hello', {'conversation_history': [], 'turn_author': author}),+ ('again', {'conversation_history': []})]diff --git a/tests/gateway/test_session_a2a.py b/tests/gateway/test_session_a2a.pyindex 1a2c2153de4..d9de6b17cee 100644--- a/tests/gateway/test_session_a2a.py+++ b/tests/gateway/test_session_a2a.py@@ -106,3 +106,48 @@ async def test_forwarding_does_not_merge_lossy_context_or_peer_identity(tmp_pathawait conn.close()await denied.close()db.close()+++async def test_forwarded_turns_are_authored_by_the_peer_for_memory_attribution(tmp_path, monkeypatch):+ """The owner binds the exact peer into the policy; memory providers must see that peer as the+ bot author of every forwarded turn, not the local principal that hosts the session."""+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_a2a import forward_author+ from gateway.session_ingress import row_turn_author+ from agent.turn_author import a2a_key+ from hermes_state_runtime import list_session_admissions+ 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 = run.GatewayRunner.__new__(run.GatewayRunner)+ runner.adapters = {}+ runner.session_store = store+ runner._session_db = store._db+ runner._draining = False+ authority = await initialize_session_authority(runner, profile_id='target', instance_id='test')+ authority._schedule = lambda ref: None+ conn = AuthorityConnection(authority, SimpleNamespace(write=lambda frame: None), {'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+ sid = response['result']['session_id']+ policy = runner.adapters[next(iter(runner.adapters))].policies[sid]+ author = forward_author(policy)+ assert author == {'id': 'alice', 'name': 'alice', 'is_bot': True}+ assert a2a_key(author) == 'a2a:alice'+ row = list_session_admissions(authority.db, session_id=sid)[0]+ assert row_turn_author(policy, row) == author+ # A producer's own stamp wins; an ordinary local policy names nobody.+ stamped = {**row, 'payload': {**row['payload'], 'local_automation_v1': {'turn_author': {'id': 'bot-7', 'is_bot': True}}}}+ assert row_turn_author(policy, stamped) == {'id': 'bot-7', 'is_bot': True}+ from gateway.session_policy import build_policy+ plain = build_policy({'cwd': str(tmp_path), 'model': 'm'}, {'platform_toolsets': {'cli': []}})+ assert row_turn_author(plain, row) is None+ await conn.close()+ authority.db.close()