Skip to content

The agent that grows with you

feat: create gateway-owned local sessions through authenticated controls

Teknium42967cddd73f
diff --git a/gateway/authz_mixin.py b/gateway/authz_mixin.py
index cd53d3aa395..c9f1499b35e 100644
--- a/gateway/authz_mixin.py
+++ b/gateway/authz_mixin.py
@@ -477,6 +477,11 @@ class GatewayAuthorizationMixin:
per-platform allow-all, adapter role auth, pairing store, env/config allowlists,
``GATEWAY_ALLOW_ALL_USERS``, default deny.
"""
+ from gateway.session_local import authorize_local_source
+ local_verdict = authorize_local_source(self, source)
+ if local_verdict is not None:
+ return local_verdict
+
# HA events are system-generated (HASS_TOKEN); webhook events are HMAC-verified.
if source.platform in {Platform.HOMEASSISTANT, Platform.WEBHOOK}:
return True
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index a31334612d5..389ea1d25a3 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -13,7 +13,8 @@ class AuthorityConnection:
self.transport = transport
self.actor = Principal(str(identity.get('user_id') or 'authenticated-dashboard'),
authority.profile_id,
- frozenset({'session:read', 'session:submit', 'session:control', 'session:approve'}),
+ frozenset({'session:read', 'session:submit', 'session:control', 'session:approve'})
+ | (frozenset({'session:create'}) if identity else frozenset()),
uuid.uuid4().hex)
self.subscriptions = {}
authority.events[self.actor.transport_id] = transport
@@ -23,7 +24,8 @@ class AuthorityConnection:
method = request.get('method')
params = request.get('params') or {}
ref = SessionRef(self.actor.profile_id, params.get('session_id', ''))
- handlers = {'session.resume': self.resume, 'prompt.submit': self.submit,
+ handlers = {'session.create': self.create, 'ping': self.ping, 'runtime.describe': self.describe,
+ 'session.resume': self.resume, 'prompt.submit': self.submit,
'prompt.receipt': self.receipt, 'prompt.cancel': self.cancel,
'session.interrupt': self.interrupt, 'session.events.since': self.events_since,
'approval.respond': self.respond, 'clarify.respond': self.respond_clarify}
@@ -39,6 +41,27 @@ class AuthorityConnection:
return {'jsonrpc': '2.0', 'id': rid, 'error': {
'code': 5001, 'message': 'storage_unavailable', 'data': {'reason': 'storage_unavailable'}}}
+ async def create(self, ref, params):
+ from gateway.session_local import create_local_session, local_session_info
+ ref = create_local_session(self.authority, self.actor, params)
+ result = await self.resume(ref, {})
+ result['info'] = local_session_info(self.authority, ref)
+ return result
+
+ async def ping(self, ref, params):
+ if not self.actor.capabilities:
+ raise RuntimeStoreError('permission_denied')
+ if params:
+ raise RuntimeStoreError('invalid_params')
+ return {'pong': True}
+
+ async def describe(self, ref, params):
+ await self.ping(ref, params)
+ return {'instance_id': self.authority.instance_id, 'profile_id': self.authority.profile_id,
+ 'authority_epoch': self.authority.epoch,
+ 'capabilities': ['durable-admission-v1', 'event-replay-v1', 'local-cli-create-v1'],
+ 'session_create': {'sources': ['cli'], 'parameters': ['request_id', 'source']}}
+
async def resume(self, ref, params):
snapshot = await self.authority.attach(self.actor, ref)
self.subscriptions[ref.session_id] = snapshot.subscription_id
diff --git a/gateway/session_local.py b/gateway/session_local.py
new file mode 100644
index 00000000000..112f6416a2c
--- /dev/null
+++ b/gateway/session_local.py
@@ -0,0 +1,112 @@
+"""Fresh local routes owned by the authenticated gateway, not by a viewer.
+
+This initial surface uses CLI policy. Unsupported launch policies fail explicitly
+rather than mutating the daemon environment or pretending to provide GUI parity.
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import uuid
+
+from gateway.config import Platform, PlatformConfig
+from gateway.platforms.base import BasePlatformAdapter, SendResult
+from gateway.session import SessionSource
+from hermes_state_runtime import RuntimeStoreError
+
+
+class LocalSessionAdapter(BasePlatformAdapter):
+ """Delivery stays in the canonical event stream; no second local transport."""
+
+ def __init__(self, authority):
+ super().__init__(PlatformConfig(enabled=True), Platform.LOCAL)
+ self.authority = authority
+ self.sources = {}
+
+ def authorize_source(self, source):
+ saved = self.sources.get(source.chat_id)
+ if saved is None:
+ return False
+ original, identity = saved
+ return (source is original and self._identity(source) == identity
+ and any(live.source is source for live in self.authority.sessions.values()))
+
+ @staticmethod
+ def _identity(source):
+ return source.platform, source.chat_id, source.user_id, source.profile, source.chat_type
+
+ def register_source(self, source):
+ self.sources[source.chat_id] = source, self._identity(source)
+
+ async def connect(self, *, is_reconnect=False):
+ return True
+
+ async def disconnect(self):
+ self.sources.clear()
+
+ async def send(self, chat_id, content, reply_to=None, metadata=None):
+ # TurnRunner already publishes model/tool deltas and settlement exactly once.
+ return SendResult(success=True, message_id=uuid.uuid4().hex)
+
+ async def edit_message(self, chat_id, message_id, content, *, finalize=False):
+ return SendResult(success=True, message_id=message_id)
+
+ async def send_typing(self, chat_id, metadata=None):
+ return None
+
+ async def get_chat_info(self, chat_id):
+ return {'id': chat_id, 'type': 'dm'}
+
+ async def send_exec_approval(self, **kwargs):
+ # The existing callback owns registration in PendingControls. An ACK here
+ # selects that rendering path without a plaintext fallback or a second waiter.
+ return SendResult(success=True, message_id=uuid.uuid4().hex)
+
+
+def authorize_local_source(runner, source):
+ """None for legacy/nonlocal routes; registered local adapters fail closed."""
+ adapter = runner._adapter_for_source(source)
+ if not isinstance(adapter, LocalSessionAdapter):
+ return None
+ if adapter.authority is not getattr(runner, 'session_authority', None):
+ return False
+ return adapter.authorize_source(source)
+
+
+def create_local_session(authority, actor, params):
+ if actor.profile_id != authority.profile_id:
+ raise RuntimeStoreError('profile_mismatch')
+ if 'session:create' not in actor.capabilities:
+ raise RuntimeStoreError('permission_denied')
+ if set(params) - {'request_id', 'source'}:
+ raise RuntimeStoreError('invalid_params')
+ # LOCAL maps to CLI policy in the existing TurnRunner; do not label this GUI.
+ if params.get('source', 'cli') != 'cli':
+ raise RuntimeStoreError('invalid_params')
+ request_id = params.get('request_id', uuid.uuid4().hex)
+ if not isinstance(request_id, str) or not request_id or len(request_id) > 256:
+ raise RuntimeStoreError('invalid_params')
+ adapter = authority.runner.adapters.get(Platform.LOCAL)
+ if adapter is None:
+ adapter = LocalSessionAdapter(authority)
+ authority.runner.adapters[Platform.LOCAL] = adapter
+ if not isinstance(adapter, LocalSessionAdapter) or adapter.authority is not authority:
+ raise RuntimeStoreError('runtime_draining')
+ # Stable route lets the persisted SessionStore recover a lost create ACK.
+ identity = json.dumps([authority.profile_id, actor.subject, request_id], separators=(',', ':'))
+ chat_id = 'local-' + hashlib.sha256(identity.encode()).hexdigest()
+ source = SessionSource(platform=Platform.LOCAL, chat_id=chat_id,
+ user_id=actor.subject, chat_type='dm')
+ ref = authority.register(source)
+ source = authority.sessions[ref.session_id].source
+ adapter.register_source(source)
+ return ref
+
+
+def local_session_info(authority, ref):
+ live = authority.sessions[ref.session_id]
+ agent = authority.agent(ref)
+ return {'source': 'cli' if isinstance(authority.runner._adapter_for_source(live.source),
+ LocalSessionAdapter) else live.source.platform.value,
+ 'model': getattr(agent, 'model', None), 'lazy': agent is None,
+ 'profile_id': authority.profile_id}
diff --git a/tests/gateway/fixtures/local_session_peer.py b/tests/gateway/fixtures/local_session_peer.py
new file mode 100644
index 00000000000..c540a5f72e4
--- /dev/null
+++ b/tests/gateway/fixtures/local_session_peer.py
@@ -0,0 +1,148 @@
+"""Owned loopback fixture: no native credentials or alternative agent runtime."""
+import asyncio
+from http.server import ThreadingHTTPServer
+import json
+import os
+from pathlib import Path
+import shlex
+import threading
+import traceback
+
+from authority_controls_peer import ModelPeer
+
+
+async def probe(peer, target):
+ import websockets
+ from gateway.run import GatewayRunner
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_contract import SessionRef
+ from gateway.run_api import start_gateway_api, stop_gateway_api
+ from hermes_cli import web_server
+ from run_agent import AIAgent
+ from tools.approval import resolve_gateway_approval
+
+ runner = GatewayRunner()
+ authority = await initialize_session_authority(runner, profile_id='fixture', instance_id='local')
+ api = await start_gateway_api(runner)
+ port = api.socket.getsockname()[1]
+ web_server.app.state.auth_required = True
+ from hermes_cli.dashboard_auth.ws_tickets import mint_ticket
+ sid = None
+ sockets = []
+
+ async def connect():
+ ticket = mint_ticket(user_id='fixture-creator', provider='local-fixture')
+ ws = await websockets.connect(f'ws://127.0.0.1:{port}/api/ws?ticket={ticket}')
+ sockets.append(ws)
+ return ws
+
+ async def rpc(ws, method, **params):
+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': method, 'method': method, 'params': params}))
+ async with asyncio.timeout(15):
+ while True:
+ frame = json.loads(await ws.recv())
+ if frame.get('id') == method:
+ return frame
+
+ try:
+ a = await connect()
+ for payload in ({'source': 'telegram'}, {'source': 'cron'}, {'internal': True},
+ {'profile': 'foreign'}, {'cwd': str(target)}, {'yolo': True}):
+ denied = await rpc(a, 'session.create', **payload)
+ assert 'error' in denied, denied
+ created = await rpc(a, 'session.create', request_id='fresh', source='cli')
+ assert 'result' in created, created
+ sid = created['result']['session_id']
+ assert sid == created['result']['stored_session_id']
+ assert authority.db.get_session(sid) is not None
+ repeated = await rpc(a, 'session.create', request_id='fresh', source='cli')
+ assert repeated['result']['session_id'] == sid, repeated
+ b = await connect()
+ resumed = await rpc(b, 'session.resume', session_id=sid)
+ assert resumed['result']['session_id'] == sid, resumed
+ submitted = await rpc(a, 'prompt.submit', session_id=sid, input_id='first', text='Remove owned fixture')
+ assert submitted.get('result', {}).get('status') == 'queued', submitted
+ async with asyncio.timeout(25):
+ while True:
+ snapshot = await rpc(b, 'session.resume', session_id=sid)
+ if snapshot['result'].get('prompts'):
+ break
+ await asyncio.sleep(.03)
+ assert target.exists(), 'effect preceded consent'
+ ref = SessionRef(authority.profile_id, sid)
+ agent = authority.agent(ref)
+ assert isinstance(agent, AIAgent)
+ prompt = snapshot['result']['prompts'][0]
+ await a.close()
+ await b.close()
+ assert target.exists()
+ c = await connect()
+ snapshot = await rpc(c, 'session.resume', session_id=sid)
+ assert snapshot['result']['prompts'][0]['prompt_id'] == prompt['prompt_id']
+ assert authority.agent(ref) is agent
+ answer = await rpc(c, 'approval.respond', session_id=sid,
+ prompt_id=prompt['prompt_id'], execution_generation=prompt['execution_generation'], choice='once')
+ assert answer.get('result', {}).get('status') == 'resolved', answer
+ await asyncio.wait_for(authority.sessions[sid].task, 25)
+ assert not target.exists(), 'real owned terminal effect missing'
+ final = await rpc(c, 'session.resume', session_id=sid)
+ assert final['result']['session_id'] == sid
+ assert any(m.get('content') == 'APPROVAL_FINISHED' for m in final['result']['messages']), final
+ assert authority.agent(ref) is agent
+ pong = await rpc(c, 'ping')
+ assert pong.get('result', {}).get('pong') is True, pong
+ described = await rpc(c, 'runtime.describe')
+ assert described['result']['instance_id'] == authority.instance_id
+ assert str(Path(os.environ['HERMES_HOME'])) not in json.dumps(described)
+ # Public transport auth remains mandatory, even for metadata or fresh sessions.
+ try:
+ async with websockets.connect(f'ws://127.0.0.1:{port}/api/ws?token=forged') as bad:
+ await rpc(bad, 'session.create', request_id='forged')
+ except (websockets.exceptions.InvalidStatus, websockets.exceptions.ConnectionClosed):
+ pass
+ else:
+ raise AssertionError('unauthenticated socket accepted')
+ Path(os.environ['HERMES_HOME'], 'receipt.json').write_text(json.dumps({
+ 'terminal_effect': True, 'same_agent': True, 'detached_pending': True,
+ 'negative_controls': True, 'reconnected_identity': sid, 'model_requests': len(peer.requests)}))
+ finally:
+ if sid is not None:
+ resolve_gateway_approval(authority.sessions[sid].route, 'deny', resolve_all=True)
+ task = authority.sessions[sid].task
+ if task is not None:
+ await asyncio.wait_for(task, 30)
+ for ws in sockets:
+ await ws.close()
+ await stop_gateway_api(api)
+
+
+def main():
+ target = Path(os.environ['HERMES_HOME'], 'owned-removal')
+ target.mkdir()
+ (target / 'owned.txt').write_text('disposable')
+ peer = ThreadingHTTPServer(('127.0.0.1', 0), ModelPeer)
+ peer.requests = []
+ peer.command = 'rm -r -- ' + shlex.quote(str(target))
+ threading.Thread(target=peer.serve_forever, daemon=True).start()
+ url = f'http://127.0.0.1:{peer.server_port}/v1'
+ os.environ.update(OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, TERMINAL_ENV='local')
+ Path(os.environ['HERMES_HOME'], 'config.yaml').write_text(
+ f'model:\n default: local-control\n provider: custom\n base_url: {url}\n'
+ 'approvals:\n mode: manual\n timeout: 45\n'
+ 'streaming:\n enabled: false\n'
+ 'auxiliary:\n title_generation:\n enabled: false\n')
+ try:
+ asyncio.run(probe(peer, target))
+ finally:
+ peer.shutdown()
+ peer.server_close()
+
+
+if __name__ == '__main__':
+ status = 0
+ try:
+ main()
+ except BaseException:
+ traceback.print_exc()
+ status = 1
+ os._exit(status)
diff --git a/tests/gateway/test_local_session.py b/tests/gateway/test_local_session.py
new file mode 100644
index 00000000000..215c1aa912e
--- /dev/null
+++ b/tests/gateway/test_local_session.py
@@ -0,0 +1,23 @@
+"""Fresh sessions use the composed authority, real TurnRunner and local tools."""
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+
+def test_fresh_local_session_owns_execution_across_viewers(tmp_path):
+ repo = Path(__file__).resolve().parents[2]
+ home, state = tmp_path / 'home', tmp_path / 'state'
+ home.mkdir()
+ state.mkdir()
+ env = {k: os.environ[k] for k in ('PATH', 'SYSTEMROOT', 'LANG', 'TZ') if k in os.environ}
+ env.update(HOME=str(home), USERPROFILE=str(home), HERMES_HOME=str(state), PYTHONPATH=str(repo))
+ result = subprocess.run(
+ [sys.executable, str(Path(__file__).parent / 'fixtures' / 'local_session_peer.py')],
+ cwd=repo, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=100)
+ assert result.returncode == 0, result.stdout + '\n' + result.stderr
+ receipt = json.loads((state / 'receipt.json').read_text())
+ assert receipt['terminal_effect'] and receipt['same_agent'] and receipt['detached_pending']
+ assert receipt['negative_controls'] and receipt['reconnected_identity']
+ print(json.dumps(receipt))