The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: admit trusted gateway completions to the durable session FIFO
Teknium7cd1b000daa3
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.pyindex 7661ec6a06f..61ea4064ccd 100644--- a/gateway/run_inbound.py+++ b/gateway/run_inbound.py@@ -1198,7 +1198,7 @@ class GatewayInboundMixin:return _paused_notice_quick_key = self._session_key_for_source(source)- _reply = await self._hm_pending_reply_intercepts(event, source, _quick_key)+ _reply = None if is_internal else await self._hm_pending_reply_intercepts(event, source, _quick_key)if _reply is not None:return _replydiff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex f5084100571..8505a08c052 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -984,7 +984,17 @@ class GatewayNotificationsMixin:_prime = getattr(adapter, "prime_routing_cache", None)if callable(_prime):_prime(synth_event)- await admit_internal_event(adapter, synth_event)+ authority = getattr(self, 'session_authority', None)+ if authority is not None:+ from gateway.session_automation import producer_identity+ from hermes_state_runtime import RuntimeStoreError+ try:+ identity = producer_identity(self, evt)+ await authority.admit_automation(adapter, synth_event, identity)+ except RuntimeStoreError as exc:+ raise WakeNotAccepted(str(exc)) from exc+ else:+ await admit_internal_event(adapter, synth_event)return Trueexcept WakeNotAccepted:# Durable callers refund the claim; ordinary watch callers just requeue.diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 44e54f28e4e..a3d35be071c 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -155,6 +155,10 @@ class SessionAuthority:if live.task is None or live.task.done():live.task = asyncio.create_task(self._drain(ref))+ async def admit_automation(self, adapter, event, identity):+ from gateway.session_automation import admit_automation+ return await admit_automation(self, adapter, event, identity)+async def admit_native(self, event):"""Await current connector policy, then commit before ACK or scheduling execution."""import jsondiff --git a/gateway/session_automation.py b/gateway/session_automation.pynew file mode 100644index 00000000000..e382cafc008--- /dev/null+++ b/gateway/session_automation.py@@ -0,0 +1,97 @@+"""Trusted producer admission; not a client-selectable internal input flag.++Reuse the private native route envelope and FIFO, retaining nonhuman turn semantics.+A producer ACK means committed input, not successful inference or outbound delivery.+"""+from copy import deepcopy+from datetime import datetime, timezone+import json++from gateway.config import Platform+from gateway.platforms.event import MessageEvent, MessageType+from gateway.session_contract import SessionRef+from hermes_state_runtime import RuntimeStoreError, admit_session_input+++def producer_identity(runner, event):+ identity = runner._completion_delivery_identity(event)+ if identity is None:+ raise RuntimeStoreError('invalid_params')+ return json.dumps(identity, separators=(',', ':'))+++def _owner(runner, event):+ route = event.metadata.get('gateway_session_key') or runner.session_store._generate_session_key(event.source)+ entry = runner.session_store.lookup_by_session_key(route)+ if entry is None or entry.suspended:+ raise RuntimeStoreError('not_found')+ if runner.session_store._generate_session_key(event.source) != route:+ raise RuntimeStoreError('admission_conflict')+ expected = event.metadata.get('gateway_session_id')+ if expected and expected != entry.session_id:+ # A completed child may follow compression, but never /new or an unrelated resume.+ if runner.session_authority.db.get_compression_tip(expected) != entry.session_id:+ raise RuntimeStoreError('admission_conflict')+ return entry+++def snapshot_automation(authority, adapter, event, identity):+ runner = authority.runner+ if (not event.internal or event.message_type != MessageType.TEXT or event.is_command()+ or not isinstance(event.text, str) or not identity+ or event.media_urls or event.prompt_response or event.source.platform == Platform.API_SERVER+ or set(event.metadata) - {'gateway_session_key', 'gateway_session_id'}):+ raise RuntimeStoreError('invalid_params')+ entry = _owner(runner, event)+ if event.source.platform == Platform.LOCAL:+ # Local frozen policy uses a different payload preflight; do not ACK work+ # until that consumer supports a private internal envelope too.+ raise RuntimeStoreError('invalid_params')+ from gateway.session_envelope import restore_native+ from hermes_state_runtime import list_session_admissions+ prior = list_session_admissions(authority.db, session_id=entry.session_id, pending_only=False)+ envelope = next((r['payload']['native_text_v1'] for r in reversed(prior)+ if 'native_text_v1' in r['payload']), None)+ if envelope is None or 'provenance' not in envelope:+ raise RuntimeStoreError('not_found')+ # Persisted origins deliberately omit relay trust. Borrow only an exact+ # committed source's private proof, revalidated against the live connector.+ restored = restore_native({'text': event.text, 'native_text_v1': envelope}, runner)+ if (restored.source.to_dict() != event.source.to_dict()+ or runner._adapter_for_source(restored.source) is not adapter):+ raise RuntimeStoreError('admission_conflict')+ provenance = deepcopy(envelope['provenance'])+ source = deepcopy(envelope['source'])+ # Producer timestamps and platform reply IDs change on retry. Neither belongs+ # in the identity/fingerprint of the same immutable completion.+ envelope = {'source': source, 'route': entry.session_key,+ 'timestamp': datetime.fromtimestamp(0, timezone.utc).isoformat(),+ 'event': {'message_id': identity}, 'provenance': provenance,+ 'automation': {'identity': identity, 'owner': entry.session_id}}+ return {'text': event.text, 'native_text_v1': envelope}, entry+++def check_automation_route(runner, payload, session_id, available_source, adapter):+ from gateway.session_envelope import restore_native+ event = restore_native(payload, runner)+ envelope = payload['native_text_v1']+ entry = _owner(runner, event)+ if (entry.session_id != session_id or envelope['automation']['owner'] != session_id+ or runner.session_store._generate_session_key(available_source) != entry.session_key+ or adapter is None or runner._adapter_for_source(event.source) is not adapter):+ raise RuntimeStoreError('admission_conflict')+ return event.source, entry.session_key+++async def admit_automation(authority, adapter, event, identity):+ authority._require_admission_open()+ payload, entry = snapshot_automation(authority, adapter, event, identity)+ from gateway.session_authority import LiveSession+ ref = SessionRef(authority.profile_id, entry.session_id)+ authority.sessions.setdefault(ref.session_id, LiveSession(event.source, entry.session_key))+ row = admit_session_input(authority.db, epoch=authority.epoch, principal_id='automation:' + entry.session_key,+ session_id=ref.session_id, request_id=identity, payload=deepcopy(payload))+ event._gateway_accepted = True+ authority._publish_pending(ref)+ authority._schedule(ref)+ return authority._receipt(row)diff --git a/gateway/session_envelope.py b/gateway/session_envelope.pyindex 2ecd70ca923..778b2d7477d 100644--- a/gateway/session_envelope.py+++ b/gateway/session_envelope.py@@ -131,15 +131,23 @@ def restore_native(payload, runner=None):runner = runner or callback_runner()if runner is not None:restore_provenance(runner, source, envelope['provenance'])- return MessageEvent(text=payload['text'], source=source,+ event = MessageEvent(text=payload['text'], source=source,timestamp=datetime.fromisoformat(envelope['timestamp']),message_type=MessageType(envelope.get('message_type', 'text')),media_urls=restore_native_media(envelope.get('media', [])),**deepcopy(envelope['event']))+ if 'automation' in envelope:+ event.internal = True+ event.metadata = {'gateway_session_key': envelope['route'],+ 'gateway_session_id': envelope['automation']['owner']}+ return eventasync def check_native_route(runner, payload, session_id, available_source, adapter):"""Read-only preflight: route/auth rejection must never consume a queued row."""+ if 'automation' in payload['native_text_v1']:+ from gateway.session_automation import check_automation_route+ return check_automation_route(runner, payload, session_id, available_source, adapter)event = restore_native(payload, runner)# Validate the stored sender without recapturing files or trusting the binding caller.from gateway.session_ingress_context import reauthorize_rolesdiff --git a/tests/gateway/fixtures/automation_peer.py b/tests/gateway/fixtures/automation_peer.pynew file mode 100644index 00000000000..2a68684ed51--- /dev/null+++ b/tests/gateway/fixtures/automation_peer.py@@ -0,0 +1,170 @@+"""Ordinary daemon, real terminal child, loopback-only relay/provider peers."""+import asyncio+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+import os+from pathlib import Path+import shlex+import sqlite3+import subprocess+import sys+import threading+import time++import websockets+from tests.gateway.test_normal_runtime_boot import control+from local_recovery_probe import websocket, rpc+++class Model(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ messages = body.get('messages', [])+ if messages:+ self.server.requests.append(body)+ last = next((m.get('content', '') for m in reversed(messages) if m['role'] == 'user'), '')+ if 'HOLD_AUTOMATION' in str(last):+ self.server.blocked.set()+ self.server.release.wait(60)+ message = {'role': 'assistant', 'content': 'AUTOMATION_ACK'}+ if 'SPAWN_AUTOMATION' in str(last) and messages[-1]['role'] != 'tool':+ code = ('import pathlib,time; p=pathlib.Path(' + repr(str(self.server.gate)) + '); '+ '\nwhile not p.exists(): time.sleep(.02)\nprint("REAL_TERMINAL_COMPLETION",flush=True)')+ command = shlex.join([sys.executable, '-c', code])+ message = {'role': 'assistant', 'content': None, 'tool_calls': [{'id': 'terminal-spawn',+ 'type': 'function', 'function': {'name': 'terminal', 'arguments': json.dumps({+ 'command': command, 'background': True, 'notify_on_complete': True, 'check_interval': 1})}}]}+ finish = 'tool_calls' if message.get('tool_calls') else 'stop'+ payload = json.dumps({'id': 'local', 'choices': [{'index': 0, 'message': message, 'finish_reason': finish}],+ 'usage': {'prompt_tokens': 10, 'completion_tokens': 5, 'total_tokens': 15}}).encode()+ kind = 'application/json'+ if body.get('stream'):+ if message.get('tool_calls'):+ message['tool_calls'][0]['index'] = 0+ payload = ('data: ' + json.dumps({'id': 'local', 'choices': [+ {'index': 0, 'delta': message, 'finish_reason': finish}]}) + '\n\ndata: [DONE]\n\n').encode()+ kind = 'text/event-stream'+ self.send_response(200)+ self.send_header('Content-Type', kind)+ self.send_header('Content-Length', str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)+++async def probe(root, base):+ home, user = base / 'state', base / 'user'+ home.mkdir(); user.mkdir()+ model = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ model.requests = []+ model.blocked, model.release = threading.Event(), threading.Event()+ model.gate = home / 'release-terminal'+ threading.Thread(target=model.serve_forever, daemon=True).start()+ ready = asyncio.Queue()+ outgoing = []+ async def connector(ws):+ hello = json.loads(await ws.recv())+ assert hello['platform'] == 'telegram', hello+ descriptor = {'contract_version': 1, 'platform': 'telegram', 'label': 'Fixture',+ 'max_message_length': 4096, 'supports_draft_streaming': False, 'supports_edit': True,+ 'supports_threads': False, 'markdown_dialect': 'plain', 'len_unit': 'chars'}+ await ws.send(json.dumps({'type': 'descriptor', 'descriptor': descriptor}) + '\n')+ await ready.put(ws)+ async for line in ws:+ frame = json.loads(line)+ outgoing.append(frame)+ if frame['type'] == 'outbound':+ await ws.send(json.dumps({'type': 'outbound_result', 'requestId': frame['requestId'],+ 'result': {'success': True, 'message_id': 'fixture-final'}}) + '\n')+ elif frame['type'] == 'going_idle':+ await ws.send(json.dumps({'type': 'going_idle_ack'}) + '\n')++ def rows():+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:+ db.row_factory = sqlite3.Row+ return [dict(r) for r in db.execute('SELECT * FROM session_admissions ORDER BY seq')]++ async def wait_for(predicate, seconds=35):+ async with asyncio.timeout(seconds):+ while not predicate():+ await asyncio.sleep(.03)++ proc = None+ try:+ async with websockets.serve(connector, '127.0.0.1', 0) as relay:+ url = f'http://127.0.0.1:{model.server_port}/v1'+ cfg = {'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'local-fixture', 'base_url': url},+ 'streaming': {'enabled': False}, 'terminal': {'cwd': str(home)},+ 'approvals': {'mode': 'off'},+ 'auxiliary': {'title_generation': {'enabled': False}}}+ (home / 'config.yaml').write_text(json.dumps(cfg))+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, PYTHONUNBUFFERED='1',+ GATEWAY_RELAY_URL=f'ws://127.0.0.1:{relay.sockets[0].getsockname()[1]}/relay',+ GATEWAY_RELAY_PLATFORMS='telegram', GATEWAY_RELAY_BOT_IDS='{"telegram":"fixture-bot"}',+ GATEWAY_RELAY_ID='fixture-gateway', GATEWAY_RELAY_SECRET='fixture-secret')+ with (home / 'daemon.log').open('w+') as log:+ proc = subprocess.Popen([sys.executable, '-m', 'gateway.run'], cwd=root, env=env,+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)+ try:+ ws = await asyncio.wait_for(ready.get(), 35)+ desc = {}+ deadline = time.monotonic() + 35+ while time.monotonic() < deadline:+ try:+ desc = await asyncio.to_thread(control, home, 'identify')+ if desc.get('state') == 'ready':+ break+ except (OSError, ValueError):+ pass+ await asyncio.sleep(.05)+ assert desc.get('state') == 'ready', desc+ async def send(identity, text):+ await ws.send(json.dumps({'type': 'inbound', 'event': {'text': text,+ 'message_id': identity, 'source': {'platform': 'telegram', 'chat_id': 'automation-chat',+ 'chat_type': 'dm', 'user_id': 'fixture-user'}}}) + '\n')+ await send('spawn', 'SPAWN_AUTOMATION')+ await wait_for(lambda: any(r['request_id'] == 'spawn' and r['status'] == 'terminal' for r in rows()))+ assert 'REAL_TERMINAL_COMPLETION' in json.dumps(model.requests), 'model did not request real terminal'+ sid = rows()[0]['target_session_id']+ async with websocket(home, desc) as observer:+ assert 'result' in await rpc(observer, 'session.resume', session_id=sid)+ await send('held', 'HOLD_AUTOMATION')+ assert await asyncio.to_thread(model.blocked.wait, 15)+ await send('human-follower', 'HUMAN_FIFO_FOLLOWER')+ await wait_for(lambda: any(r['request_id'] == 'human-follower' for r in rows()))+ model.gate.touch()+ await asyncio.sleep(8) # production notify watcher polls every five seconds+ ledger = rows()+ automatic = [r for r in ledger if r['principal_id'].startswith('automation:')]+ assert automatic, {'failure': 'producer ACK bypassed canonical durable FIFO', 'ledger': ledger,+ 'daemon_tail': (home / 'daemon.log').read_text()[-6000:]}+ assert automatic[0]['status'] == 'queued', automatic+ assert next(r for r in ledger if r['request_id'] == 'held')['status'] == 'started'+ assert automatic[0]['seq'] > next(r for r in ledger if r['request_id'] == 'human-follower')['seq']+ model.release.set()+ await wait_for(lambda: all(r['status'] == 'terminal' for r in rows()))+ assert all(r['outcome'] == 'completed' for r in rows()), rows()+ texts = [next((m.get('content', '') for m in reversed(r['messages']) if m['role'] == 'user'), '')+ for r in model.requests if r.get('messages')]+ assert 'REAL_TERMINAL_COMPLETION' in str(texts[-1]), texts+ assert 'HUMAN_FIFO_FOLLOWER' in str(texts[-2]), texts+ print(json.dumps({'daemon_pid': proc.pid, 'ledger': rows(), 'model_inputs': texts,+ 'observer_closed_before_completion': True}))+ except BaseException:+ print((home / 'daemon.log').read_text()[-10000:], file=sys.stderr)+ raise+ finally:+ model.gate.touch()+ model.release.set()+ if proc is not None:+ proc.kill(); proc.wait(timeout=10)+ model.shutdown(); model.server_close()+++if __name__ == '__main__':+ asyncio.run(probe(Path(__file__).resolve().parents[3], Path(sys.argv[1])))diff --git a/tests/gateway/test_authority_automation.py b/tests/gateway/test_authority_automation.pynew file mode 100644index 00000000000..1291fb6b737--- /dev/null+++ b/tests/gateway/test_authority_automation.py@@ -0,0 +1,16 @@+"""Completion producers must commit to the same FIFO as human input."""+import os+from pathlib import Path+import subprocess+import sys+++def test_terminal_completion_commits_while_ordinary_daemon_model_is_held(tmp_path):+ root = Path(__file__).resolve().parents[2]+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}+ env['PYTHONPATH'] = str(root)+ result = subprocess.run([sys.executable, str(root / 'tests/gateway/fixtures/automation_peer.py'),+ str(tmp_path)], env=env, cwd=root, stdin=subprocess.DEVNULL,+ capture_output=True, text=True, timeout=150)+ assert result.returncode == 0, result.stdout + result.stderr+ print(result.stdout)