The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: retain per-admission bot and API authors
Teknium61f75a775238
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 96a2d0d6839..0418874446b 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -609,8 +609,12 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):kwargs = {"conversation_history": agent_history, "task_id": ctx.session_id}if _accepts_keyword(agent.run_conversation, "turn_author"):# Sent on every transport: a provider gating durable writes needs the bot flag in a DM too.- kwargs["turn_author"] = {"id": ctx.source.user_id or None, "name": ctx.source.user_name or None,- "is_bot": bool(getattr(ctx.source, "is_bot", False))}+ from gateway.session_api_turn import api_execution+ from gateway.session_ingress import admission_author+ api = api_execution.get()+ kwargs["turn_author"] = (api.get('turn_author') if api is not None else+ admission_author.get() or {"id": ctx.source.user_id or None, "name": ctx.source.user_name or None,+ "is_bot": bool(getattr(ctx.source, "is_bot", False))})if persist_user_message_override is not None:kwargs["persist_user_message"] = persist_user_message_overrideelif observed_group_context:diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.pyindex b702f75bc2d..cae494aa9f2 100644--- a/gateway/session_api_turn.py+++ b/gateway/session_api_turn.py@@ -34,7 +34,9 @@ def check_api_turn(authority, ref, payload):raise RuntimeStoreError('runtime_draining')if 'api_turn_v1' in payload:data = payload['api_turn_v1']- if set(data) != {'history', 'settings'} or (data['history'] is not None and not isinstance(data['history'], list)):+ if (set(data) - {'history', 'settings', 'turn_author'}+ or not {'history', 'settings'} <= set(data)+ or (data['history'] is not None and not isinstance(data['history'], list))):raise RuntimeStoreError('invalid_params')if set(data['settings']) - set(_SETTING_KEYS):raise RuntimeStoreError('invalid_params')@@ -97,6 +99,12 @@ def admit_api_turn(adapter, **kwargs):settings['route'] = {k: v for k, v in route.items() if k != 'api_key'}payload = json.loads(_json({'text': kwargs['user_message'], 'api_turn_v1': {'history': None if kwargs.get('history_from_session') else kwargs['conversation_history'], 'settings': settings}}))+ if kwargs.get('turn_author') is not None:+ from agent.turn_author import parse_turn_author+ author = parse_turn_author(kwargs['turn_author'])+ if author is None:+ raise RuntimeStoreError('invalid_params')+ payload['api_turn_v1']['turn_author'] = authorrequest_id = kwargs.get('request_id') or kwargs.get('active_run_id') or uuid.uuid4().hexfrom hermes_state_terminal import retry_terminal_admissionrow = retry_terminal_admission(authority.db, epoch=authority.epoch, principal_id='api',@@ -186,7 +194,7 @@ def prepare_api_execution(authority, ref, payload):(_SETTINGS_PREFIX + ref.session_id, _json(settings)))authority.db._execute_write(write)return {'adapter': adapter, 'settings': settings, 'history': data['history'] if data else None,- 'content': payload['text']}+ 'content': payload['text'], 'turn_author': data.get('turn_author') if data else None}def publish_api_event(authority, session_id, event_type, payload):diff --git a/gateway/session_automation.py b/gateway/session_automation.pyindex f6f5591d252..c2989f7356a 100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@ -59,7 +59,7 @@ def snapshot_automation(authority, adapter, event, identity):if (not event.internal or event.message_type != MessageType.TEXT or event.is_command()or not isinstance(event.text, str) or not identityor event.media_urls or event.prompt_response or event.source.platform == Platform.API_SERVER- or set(event.metadata) - {'gateway_session_key', 'gateway_session_id', 'automation_identities'}):+ or set(event.metadata) - {'gateway_session_key', 'gateway_session_id', 'automation_identities', 'turn_author'}):raise RuntimeStoreError('invalid_params')entry = _owner(runner, event)if event.source.platform == Platform.LOCAL:@@ -114,6 +114,11 @@ def snapshot_local_automation(authority, adapter, event, identity, entry):raise RuntimeStoreError('permission_denied')descriptor = {'identity': identity, 'owner': ref.session_id,'route': entry.session_key, 'target': entry.session_id}+ if event.metadata.get('turn_author') is not None:+ from agent.turn_author import parse_turn_author+ descriptor['turn_author'] = parse_turn_author(event.metadata['turn_author'])+ if descriptor['turn_author'] is None:+ raise RuntimeStoreError('invalid_params')if event.metadata.get('automation_identities'):descriptor['identities'] = sorted(set(event.metadata['automation_identities']))if getattr(event, '_heartbeat_session_id', None):@@ -144,6 +149,8 @@ def restore_local_automation(authority, ref, row):event = MessageEvent(text=row['payload']['text'], source=live.source, internal=True,message_id=descriptor['identity'], metadata={'gateway_session_key': live.route,'gateway_session_id': entry.session_id})+ if descriptor.get('turn_author') is not None:+ event.metadata['turn_author'] = deepcopy(descriptor['turn_author'])if descriptor.get('heartbeat'):event._heartbeat_session_id = descriptor['heartbeat']return eventdiff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex cdd08fe3f29..c9a3d48f73e 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -6,6 +6,8 @@ admission is the only consumer; unknown execution is never retried as inference.import asynciofrom pathlib import Path+from agent.turn_author import parse_turn_author+from gateway.session_contract import Principal, SessionReffrom gateway.config import Platformfrom gateway.platforms.event import MessageEvent@@ -115,7 +117,7 @@ async def _migrate(authority, actor, home, root):_write(path, record)continueawait _admit(authority, actor, home, root, _delivery_id(record['delivery_id']),- record['message'], ref, live, entry, legacy=record)+ record['message'], ref, live, entry, author=parse_turn_author(record.get('author')), legacy=record)async def recover_bot_deliveries(authority):@@ -160,7 +162,7 @@ def _watch_reply(authority, home, key, admission_id):async def deliver(connection, params):authority, actor = connection.authority, connection.actorhome = _home(authority, actor, params.get('profile'))- if set(params) - {'id', 'profile', 'message', 'session_id'}:+ if set(params) - {'id', 'profile', 'message', 'session_id', 'author'}:raise RuntimeStoreError('invalid_params')try:key = _delivery_id(params.get('id'))@@ -169,19 +171,24 @@ async def deliver(connection, params):message = params.get('message')if not isinstance(message, str) or not message.strip() or len(message) > 16200:raise RuntimeStoreError('invalid_params')+ author = parse_turn_author(params.get('author'))+ if params.get('author') is not None and (not isinstance(params['author'], dict) or author is None):+ raise RuntimeStoreError('invalid_params')authority._require_admission_open()with _locked(home) as root:path = root / f'{key}.json'record = _read(path)if record is not None and record.get('admission_id'):- if record['message'] != message or record['principal_id'] != actor.subject:+ if (record['message'] != message or record['principal_id'] != actor.subject+ or record.get('author') != author):raise RuntimeStoreError('admission_conflict')authority.authorize(actor, SessionRef(authority.profile_id, record['session_id']), 'session:submit')return _result(authority, record)await _migrate(authority, actor, home, root)record = _read(path)if record is not None and record.get('admission_id'):- if record['message'] != message or record['principal_id'] != actor.subject:+ if (record['message'] != message or record['principal_id'] != actor.subject+ or record.get('author') != author):raise RuntimeStoreError('admission_conflict')authority.authorize(actor, SessionRef(authority.profile_id, record['session_id']), 'session:submit')return _result(authority, record)@@ -190,18 +197,22 @@ async def deliver(connection, params):ref, live, entry = _target(authority, actor)if params.get('session_id', entry.session_id) != entry.session_id:raise RuntimeStoreError('admission_conflict')- return await _admit(authority, actor, home, root, key, message, ref, live, entry)+ return await _admit(authority, actor, home, root, key, message, ref, live, entry, author=author)-async def _admit(authority, actor, home, root, key, message, ref, live, entry, legacy=None):+async def _admit(authority, actor, home, root, key, message, ref, live, entry, author=None, legacy=None):path = root / f'{key}.json'event = MessageEvent(text=message, source=live.source, internal=True,message_id='bot:' + key, metadata={'gateway_session_key': live.route,'gateway_session_id': entry.session_id})+ if author is not None:+ event.metadata['turn_author'] = dict(author)# Pin the physical target before committing. A process death in this# two-store window leaves an explicit unknown record, never a new target.record = dict(legacy or {}, delivery_id=key, profile_home=str(home), session_id=ref.session_id,principal_id=actor.subject, message=message, status='ambiguous')+ if author is not None:+ record['author'] = dict(author)_write(path, record)receipt = await authority.admit_automation(authority.runner._adapter_for_source(live.source), event, 'bot:' + key)record.update(status='canonical', admission_id=receipt.admission_id)diff --git a/gateway/session_ingress.py b/gateway/session_ingress.pyindex 7cb816e517c..cccb0488526 100644--- a/gateway/session_ingress.py+++ b/gateway/session_ingress.py@@ -7,6 +7,7 @@ from dataclasses import replacefrom gateway.platforms.event import MessageEventfrom gateway.session_envelope import restore_native+admission_author = ContextVar('admission_author', default=None)executing_admission = ContextVar('executing_admission', default=False)@@ -59,6 +60,7 @@ async def execute_admission(authority, ref, row):event.text = '\n'.join(part['text'] for part in event.text if part.get('type') == 'text')event.allow_gateway_control = Falseevent.internal = True # trust comes from the private binding and preclaim, never client JSON+ author_token = admission_author.set(event.metadata.get('turn_author'))api_token = api_execution.set(prepared)captured = {}result_token = execution_result.set(captured)@@ -79,6 +81,7 @@ async def execute_admission(authority, ref, row):executing_admission.reset(token)execution_result.reset(result_token)api_execution.reset(api_token)+ admission_author.reset(author_token)async def deliver_response(adapter, event, session_key, response):diff --git a/tests/gateway/fixtures/bot_authority_peer.py b/tests/gateway/fixtures/bot_authority_peer.pyindex a5f56af4a75..20084a0a1cc 100644--- a/tests/gateway/fixtures/bot_authority_peer.py+++ b/tests/gateway/fixtures/bot_authority_peer.py@@ -66,7 +66,8 @@ def probe(base):for key, status, text in [('b' * 32, 'queued', 'LEGACY_QUEUED_ONCE'),('c' * 32, 'claimed', 'LEGACY_CLAIMED_NEVER')]:_write(mailbox / f'{key}.json', dict(delivery_id=key, id=key, owner=legacy_owner,- **legacy_owner, message=text, status=status, created_at=1, sequence=1))+ **legacy_owner, message=text, status=status, created_at=1, sequence=1,+ author={'id': 'bot:legacy', 'name': 'Legacy', 'is_bot': True}))dm = home / 'local-dm.txt'dm.write_text('[Message from @local-sender] LOCAL_DM_ONCE')local = await asyncio.to_thread(_admit_live_dm, home, str(dm))@@ -77,7 +78,8 @@ def probe(base):migrated = _read(mailbox / ('b' * 32 + '.json'))unknown = _read(mailbox / ('c' * 32 + '.json'))assert migrated.get('admission_id') and unknown['status'] == 'ambiguous', (migrated, unknown)- params = {'id': 'a' * 32, 'profile': 'default', 'message': '[Message from @sender] BOT_DM_ONCE'}+ params = {'id': 'a' * 32, 'profile': 'default', 'message': '[Message from @sender] BOT_DM_ONCE',+ 'author': {'id': 'bot:peer/sender', 'name': 'Sender', 'is_bot': True}}wrong = await rpc(ws, 'bot_relay.deliver', **{**params, 'profile': 'wrong-profile'})assert wrong['error']['message'] == 'profile_mismatch', wrong# Discard an actual response at the socket boundary before reconnecting.@@ -92,6 +94,11 @@ def probe(base):assert conflict['error']['message'] == 'admission_conflict', conflictbot = [r for r in rows() if 'BOT_DM_ONCE' in r['payload_json']]assert len(bot) == 1 and bot[0]['target_session_id'] == sid and bot[0]['status'] == 'queued', bot+ changed = await rpc(observer, 'bot_relay.deliver', **{**params, 'author': {'id': 'other'}})+ assert changed['error']['message'] == 'admission_conflict', changed+ assert json.loads(bot[0]['payload_json'])['local_automation_v1']['turn_author'] == params['author']+ legacy = next(r for r in rows() if 'LEGACY_QUEUED_ONCE' in r['payload_json'])+ assert json.loads(legacy['payload_json'])['local_automation_v1']['turn_author']['id'] == 'bot:legacy'model.release.set()await wait(lambda: all(r['status'] == 'terminal' for r in rows()))settled = await rpc(observer, 'bot_relay.deliver', **params)diff --git a/tests/gateway/test_api_cutover_contract.py b/tests/gateway/test_api_cutover_contract.pyindex 2c885415091..74337fcfcaa 100644--- a/tests/gateway/test_api_cutover_contract.py+++ b/tests/gateway/test_api_cutover_contract.py@@ -60,3 +60,37 @@ async def test_structured_content_bypasses_text_parser_without_losing_parts(api,return 'ok'owner.runner._handle_message = handleassert await execute_admission(owner, ref, row) == 'ok'++++def test_api_author_is_admission_scoped_not_session_identity(api, owner):+ from gateway.session_api_turn import prepare_api_execution+ from gateway.run_turn_runner import TurnRunner+ from gateway.turn_context import TurnContext+ from hermes_state_runtime import RuntimeStoreError+ author = {'id': 'bot:peer', 'name': 'Peer', 'is_bot': True}+ args = dict(session_id='author', request_id='one', user_message='hello', conversation_history=[], turn_author=author)+ _, ref, row = admit_api_turn(api, **args)+ assert row['payload']['api_turn_v1']['turn_author'] == author+ author['name'] = 'changed'+ with pytest.raises(RuntimeStoreError, match='admission_conflict'):+ admit_api_turn(api, **args)+ owner.sessions.clear()+ from gateway.session_api import restore_api_session+ restore_api_session(owner, ref.session_id)+ seen = []+ def run(message, *, turn_author=None, **kwargs):+ seen.append(turn_author)+ return {'final_response': 'ok'}+ agent = SimpleNamespace(run_conversation=run)+ turn = TurnRunner(SimpleNamespace(session_authority=None, _consume_pending_native_image_paths=lambda key: []),+ TurnContext(message='hello', session_id=ref.session_id, session_key='api',+ source=SimpleNamespace(user_id='authenticated', user_name='Owner', is_bot=False)))+ for payload in (row['payload'], {'text': 'human'}):+ prepared = prepare_api_execution(owner, ref, payload)+ token = api_execution.set(prepared)+ try:+ turn._run_conversation_with_approval(agent, [], None, None, None)+ finally:+ api_execution.reset(token)+ assert seen == [row['payload']['api_turn_v1']['turn_author'], None]