The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: admit local automation through owner durable FIFO
Teknium1642b339918c
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex a3d35be071c..46a211ba346 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -305,7 +305,10 @@ class SessionAuthority:if first is not None and live.source.platform == Platform.LOCAL:from gateway.session_local_recovery import restore_local_sessionrestore_local_session(self, ref.session_id)- if first['principal_id'] != live.source.user_id or set(first['payload']) != {'text'}:+ if 'local_automation_v1' in first['payload']:+ from gateway.session_automation import check_local_automation+ check_local_automation(self, ref, first)+ elif first['principal_id'] != live.source.user_id or set(first['payload']) != {'text'}:raise RuntimeStoreError('permission_denied')if first is not None and 'native_text_v1' in first['payload']:from gateway.session_envelope import check_native_routediff --git a/gateway/session_automation.py b/gateway/session_automation.pyindex 4935ec8df21..f6f5591d252 100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@ -29,8 +29,9 @@ def completion_admission(runner, event):return Nonefrom hermes_state_runtime import list_session_admissionsidentity = producer_identity(runner, event)- for row in list_session_admissions(authority.db, session_id=entry.session_id, pending_only=False):- descriptor = row['payload'].get('native_text_v1', {}).get('automation', {})+ sid = entry.origin.chat_id if entry.origin.platform == Platform.LOCAL else entry.session_id+ for row in list_session_admissions(authority.db, session_id=sid, pending_only=False):+ descriptor = row['payload'].get('local_automation_v1') or row['payload'].get('native_text_v1', {}).get('automation', {})if identity in descriptor.get('identities', [descriptor.get('identity')]):return rowreturn None@@ -62,9 +63,7 @@ def snapshot_automation(authority, adapter, event, identity):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')+ return snapshot_local_automation(authority, adapter, event, identity, entry)from gateway.session_envelope import restore_nativefrom hermes_state_runtime import list_session_admissionsprior = list_session_admissions(authority.db, session_id=entry.session_id, pending_only=False)@@ -106,11 +105,56 @@ def check_automation_route(runner, payload, session_id, available_source, adaptereturn event.source, entry.session_key+def snapshot_local_automation(authority, adapter, event, identity, entry):+ from gateway.session_local_recovery import restore_local_session+ ref = restore_local_session(authority, event.source.chat_id)+ live = authority.sessions[ref.session_id]+ if (live.source is not event.source or not adapter.authorize_source(event.source)+ or authority.runner._adapter_for_source(live.source) is not adapter):+ raise RuntimeStoreError('permission_denied')+ descriptor = {'identity': identity, 'owner': ref.session_id,+ 'route': entry.session_key, 'target': entry.session_id}+ if event.metadata.get('automation_identities'):+ descriptor['identities'] = sorted(set(event.metadata['automation_identities']))+ if getattr(event, '_heartbeat_session_id', None):+ descriptor['heartbeat'] = event._heartbeat_session_id+ return {'text': event.text, 'local_automation_v1': descriptor}, entry+++def check_local_automation(authority, ref, row):+ live = authority.sessions[ref.session_id]+ payload = row['payload']+ descriptor = payload['local_automation_v1']+ if (set(payload) != {'text', 'local_automation_v1'}+ or row['principal_id'] != 'automation:' + live.route+ or descriptor['owner'] != ref.session_id or descriptor['route'] != live.route+ or descriptor['identity'] != row['request_id']):+ raise RuntimeStoreError('permission_denied')+ entry = authority.runner.session_store.lookup_by_session_key(live.route)+ if (entry is None or entry.suspended or (entry.session_id != descriptor['target']+ and authority.db.get_compression_tip(descriptor['target']) != entry.session_id)):+ raise RuntimeStoreError('admission_conflict')+++def restore_local_automation(authority, ref, row):+ check_local_automation(authority, ref, row)+ live = authority.sessions[ref.session_id]+ descriptor = row['payload']['local_automation_v1']+ entry = authority.runner.session_store.lookup_by_session_key(live.route)+ 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('heartbeat'):+ event._heartbeat_session_id = descriptor['heartbeat']+ return event++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)+ sid = payload.get('local_automation_v1', {}).get('owner', entry.session_id)+ ref = SessionRef(authority.profile_id, sid)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))diff --git a/gateway/session_ingress.py b/gateway/session_ingress.pyindex 59a1ce2cbb1..24c596b64b1 100644--- a/gateway/session_ingress.py+++ b/gateway/session_ingress.py@@ -29,6 +29,9 @@ async def execute_admission(authority, ref, row):else:event = MessageEvent(text=row['payload']['text'], source=live.source,message_id=row['admission_id'])+ if 'local_automation_v1' in row['payload']:+ from gateway.session_automation import restore_local_automation+ event = restore_local_automation(authority, ref, row)provenance = row['payload'].get('native_text_v1', {}).get('provenance')scope = nullcontext()if provenance is not None:diff --git a/tests/gateway/fixtures/local_automation_peer.py b/tests/gateway/fixtures/local_automation_peer.pynew file mode 100644index 00000000000..4d177fed939--- /dev/null+++ b/tests/gateway/fixtures/local_automation_peer.py@@ -0,0 +1,96 @@+"""Ordinary daemon + local authenticated clients + actual terminal completion."""+import asyncio+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import sqlite3+import sys+import threading++from automation_peer import Model+from local_recovery_probe import daemon, websocket, rpc+++def probe(base, source):+ root = Path(__file__).resolve().parents[3]+ 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 / 'terminal-gate'+ threading.Thread(target=model.serve_forever, daemon=True).start()+ 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},+ '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')++ 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(predicate):+ async with asyncio.timeout(30):+ while not predicate():+ await asyncio.sleep(.05)++ async def run(desc):+ async with websocket(home, desc) as ws:+ result = await rpc(ws, 'session.create', request_id='automation', source=source,+ cwd=str(home), toolsets=['terminal'])+ assert 'result' in result, result+ sid = result['result']['session_id']+ async def submit(identity, text):+ reply = await rpc(ws, 'prompt.submit', session_id=sid, input_id=identity, text=text)+ assert 'result' in reply, reply+ await submit('spawn', 'SPAWN_AUTOMATION')+ await wait(lambda: rows()[0]['status'] == 'terminal')+ assert 'REAL_TERMINAL_COMPLETION' in json.dumps(model.requests)+ await submit('held', 'HOLD_AUTOMATION')+ assert await asyncio.to_thread(model.blocked.wait, 20)+ await submit('follower', 'HUMAN_FIFO_FOLLOWER')+ # Last observer closes while owner remains in a model call.+ model.gate.touch()+ await asyncio.sleep(8)+ ledger = rows()+ automatic = [r for r in ledger if r['principal_id'].startswith('automation:')]+ assert automatic, {'missing_automation': ledger}+ assert len(automatic) == 1 and 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'] == 'follower')['seq']+ model.release.set()+ await wait(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+ async with websocket(home, desc) as ws:+ resumed = await rpc(ws, 'session.resume', session_id=sid)+ assert 'result' in resumed, resumed+ return {'source': source, 'ledger': rows(), 'model_inputs': texts,+ 'observer_closed_before_completion': True}++ try:+ with daemon(root, home, env, barrier=False) as (proc, desc):+ try:+ receipt = asyncio.run(run(desc))+ receipt['daemon_pid'] = proc.pid+ print(json.dumps(receipt))+ except BaseException:+ print((home / 'restart.log').read_text()[-15000:], file=sys.stderr)+ raise+ finally:+ model.gate.touch(); model.release.set()+ model.shutdown(); model.server_close()+++if __name__ == '__main__':+ probe(Path(sys.argv[1]), sys.argv[2])diff --git a/tests/gateway/test_local_automation.py b/tests/gateway/test_local_automation.pynew file mode 100644index 00000000000..4552eb52bb9--- /dev/null+++ b/tests/gateway/test_local_automation.py@@ -0,0 +1,19 @@+"""Local automation belongs to the owner, never an attached client."""+import os+from pathlib import Path+import subprocess+import sys++import pytest++[email protected]('source', ['cli', 'tui', 'gui'])+def test_local_completion_joins_fifo_without_an_observer(tmp_path, source):+ 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/local_automation_peer.py'),+ str(tmp_path), source], cwd=root, env=env, stdin=subprocess.DEVNULL,+ capture_output=True, text=True, timeout=150)+ assert result.returncode == 0, result.stdout + result.stderr+ print(result.stdout)