The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): preserve operator access across native and dashboard sessions
unsupportedpastelsdd6d41e220ba
diff --git a/docs/gateway-local-sessions.md b/docs/gateway-local-sessions.mdindex 15f35e4bea4..be1632146fb 100644--- a/docs/gateway-local-sessions.md+++ b/docs/gateway-local-sessions.md@@ -27,6 +27,37 @@ admission, not inference completion. Closing every viewer leaves the execution apending approval alive. A new viewer can resume the same identity and answer through`approval.respond({session_id, execution_generation, prompt_id, choice})`.+## Deliberate behavior change: shared operator access++Verified operators of the same gateway profile may attach to canonical local sessions+created through another operator authentication path. This replaces the creator-subject-only+access fence for those operators: the existing dashboard gate already grants operator access,+so changing from native CLI/TUI to an authenticated dashboard must not create a second runtime+or prevent attachment solely because the raw identities differ. This is shared access, not+shared identity: creation receipts keep the original owner, and admissions and retries keep+the submitting principal.++The server issues `session:operator` only at these existing trusted boundaries:++- Native interactive bootstrap ticket redemption (not worker-adoption tickets).+- The dashboard WebSocket upgrade gate, including authenticated dashboard login tickets,+ the process-lifetime internal credential for server-spawned PTY clients, and the verified+ legacy session token when that authentication path is enabled.+- The HTTP mutation gate, after a verified dashboard Session, native HTTP owner grant,+ or permitted legacy session token has been accepted.++A client cannot request this scope in RPC parameters or an identity capability list.+Operator scope does not replace profile, instance, per-operation capability, subscription,+revision, or generation checks. It does not upgrade messaging, room, worker, or service+credentials, or permit remote first-claim adoption of unowned historical transcripts. If+restricted dashboard identities are introduced, these issuance gates must reflect that+restriction rather than treating every accepted dashboard credential as an operator.++Cross-subject local submissions carry a private, server-written profile/session/principal+binding for queued execution and recovery. It is not exposed in model requests or public+session snapshots. This change does not expose the gateway listener remotely or implement+OpenAI API-to-local session affinity; those remain separate integration paths.+## Deliberately limited compatibility- `source` accepts `cli` (default), `tui`, or `gui`. These select the existing agent@@ -46,11 +77,11 @@ pending approval alive. A new viewer can resume the same identity and answer thr`invalid_params`. Provider credentials/routing and reasoning/service-tier defaults stilluse the existing gateway resolution lifecycle; this is not full launch-option parity.No supported launch field mutates daemon-wide configuration or process environment.-- Fresh creation currently requires the identity stamped by the existing gated WS ticket- path. The legacy ungated `?token=` path in this base does not stamp identity and cannot- create. The authentication/bootstrap integration must supply the proper server principal;- callers cannot provide one in RPC parameters. Resume-only capabilities must not be- promoted to `session:create` by that integration.+- Fresh creation requires a server-authenticated identity with `session:create`, supplied+ by the gated dashboard or native bootstrap path. The verified legacy `?token=` route+ stamps a session-token identity and also supports creation. Callers cannot provide an+ identity in RPC parameters, and operator scope does not promote resume-only capabilities+ to `session:create`.- `session.list({limit})` returns authorized **live** authority sessions (`scope: "live"`),not the full historical session picker. `session.info({session_id})` is a lightweight,authorized view of source, current model, lazy-agent status, and profile ID.@@ -58,9 +89,10 @@ pending approval alive. A new viewer can resume the same identity and answer threpoch, and the narrow implemented creation contract. It does not claim full runtimeprotocol readiness, reveal credentials/paths, start an agent, or renew a turn lease.- Cold restart restores valid private local policies and server-owned routes before execution.- Local sessions are scoped to their authenticated creating principal and profile. Caller- source/native context cannot reconstruct or authorize a local route. Missing, malformed,- foreign-profile or mismatched policy/identity fails closed, including preclaim checks;+ Creation receipts remain bound to their authenticated creating principal and profile;+ verified operators in that profile may access the canonical session without replacing+ that binding. Caller source/native context cannot reconstruct or authorize a local route.+ Missing, malformed, foreign-profile or mismatched policy/identity fails closed, including preclaim checks;historical pre-extension sessions without a receipt are not silently treated as CLI.- Never-started queued local inputs resume through the same authority FIFO after bootstrapreadiness. Interrupted started inputs become `unknown`, are never replayed, and pause@@ -83,6 +115,21 @@ pending approval alive. A new viewer can resume the same identity and answer thr## Verification+`tests/gateway/test_operator_cross_surface.py` exercises native-created/dashboard-attached+and dashboard-created/native-attached sessions through real bootstrap and dashboard+login/callback/cookie/ticket paths in a disposable gateway process. The identity provider and+model endpoint are test fixtures. It verifies client disconnect/reconnect, FIFO admission and+retry, retained attribution and model context, unchanged system messages, and private+operator provenance absent from public responses and model requests. It does **not** kill+and restart the gateway process, directly compare simultaneous live fanout, or exercise+shared approval/clarify across those two authentication methods.++`tests/gateway/test_session_operator_scope.py` covers queued operator input across a fresh+authority epoch using a stub executor and a paused scheduler. This is unit-level recovery+evidence, not real cross-surface cold-process restart certification. The existing recovery+fixtures described below provide separate coverage; their results must not be presented as+a new end-to-end cross-authentication gateway-crash test.+`tests/gateway/test_local_session.py` launches a disposable process with temporary HOMEand HERMES_HOME, the production composed HTTP/WS listener, real single-use authenticatedtickets, a loopback OpenAI-compatible model, the real TurnRunner/AIAgent, and the realdiff --git a/gateway/run_api.py b/gateway/run_api.pyindex f8c1626e21d..5485b1a4435 100644--- a/gateway/run_api.py+++ b/gateway/run_api.py@@ -141,9 +141,11 @@ class GatewayRuntimeAPI:or not ws.client or ws.client.host not in {'127.0.0.1', '::1'}):await ws.close(code=4403)return+ operator = Truetry:grant = self.runner.session_ticket_store.redeem(ticket, profile_id=None, purpose='interactive')except PermissionError:+ operator = Falsetry:grant = self.runner.session_ticket_store.redeem(ticket, profile_id=None, purpose='worker-adoption')except PermissionError:@@ -164,4 +166,4 @@ class GatewayRuntimeAPI:'profile_id': grant['profile_id'],'instance_id': grant['instance_id'],'capabilities': grant['capabilities'], 'native_bootstrap': True},- subprotocol=CANONICAL_GATEWAY_PROTOCOL)+ subprotocol=CANONICAL_GATEWAY_PROTOCOL, operator=operator)diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 55e464b63a6..92f270e5297 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -70,7 +70,8 @@ class SessionAuthority:restore_api_session(self, ref.session_id)from gateway.config import Platformsource = self.sessions[ref.session_id].source- if source is not None and source.platform == Platform.LOCAL and source.user_id != actor.subject:+ if (source is not None and source.platform == Platform.LOCAL+ and source.user_id != actor.subject and 'session:operator' not in actor.capabilities):raise RuntimeStoreError('permission_denied')def _require_admission_open(self):@@ -237,6 +238,14 @@ class SessionAuthority:finite = admit_finite(request.payload)payload = {'text': request.payload['text'], **finite,**admit_attachments(request.payload.get('attachments'))}+ from gateway.config import Platform+ source = self.sessions[request.ref.session_id].source+ if source is not None and source.platform == Platform.LOCAL and source.user_id != actor.subject:+ # Durable server authorization, not a client payload field. The original+ # principal remains the admission/retry identity across owner restarts.+ payload['local_operator_v1'] = {+ 'profile_id': self.profile_id, 'session_id': request.ref.session_id,+ 'principal_id': actor.subject}row = admit_session_input(self.db, epoch=self.epoch, principal_id=actor.subject,session_id=request.ref.session_id, request_id=request.request_id,payload=payload, intent=request.intent)@@ -349,9 +358,9 @@ class SessionAuthority:if 'local_automation_v1' in first['payload']:from gateway.session_automation import check_local_automationcheck_local_automation(self, ref, first)- elif (first['principal_id'] != live.source.user_id- or not {'text'} <= set(first['payload']) <= {'text', 'attachments_v1', 'finite'}):- raise RuntimeStoreError('permission_denied')+ else:+ from gateway.session_operator import check_local_input+ check_local_input(self, ref, first)if first is not None and 'native_text_v1' in first['payload']:from gateway.session_envelope import check_native_routeawait check_native_route(self.runner, first['payload'], ref.session_id, live.source,diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 1e7e9e77737..3be89c2eea6 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -9,7 +9,7 @@ from hermes_state_runtime import RuntimeStoreErrorclass AuthorityConnection:- def __init__(self, authority, transport, identity):+ def __init__(self, authority, transport, identity, *, operator=False):self.authority = authorityself.transport = transportcapabilities = frozenset({'session:read', 'session:submit', 'session:control',@@ -18,6 +18,10 @@ class AuthorityConnection:capabilities |= {'session:create'}if 'capabilities' in identity:capabilities = frozenset(identity['capabilities'])+ # Only verified transport gates may issue this capability, never identity data.+ capabilities -= {'session:operator'}+ if operator is True:+ capabilities |= {'session:operator'}if (not identity.get('user_id')or identity.get('instance_id', authority.instance_id) != authority.instance_id):capabilities = frozenset()diff --git a/gateway/session_group_controls.py b/gateway/session_group_controls.pyindex eadb486c5c1..839b90125b0 100644--- a/gateway/session_group_controls.py+++ b/gateway/session_group_controls.py@@ -271,13 +271,19 @@ def _profiles(authority, actor, home, params):# The named registry is not a recency window and canonical chats are hidden.canonical = authority.db.get_session_by_title('Bot Chat')- if (canonical and canonical.get('user_id') == actor.subject+ if (canonical and (canonical.get('user_id') == actor.subject+ or 'session:operator' in actor.capabilities)and str(canonical.get('chat_id') or '').startswith('local-') and not canonical.get('archived')):row['canonical_session'] = summary(canonical)+ if 'session:operator' in actor.capabilities:+ owner_filter, owner_params = '', ()+ else:+ owner_filter, owner_params = 'user_id=? AND ', (actor.subject,)with authority.db._lock:latest = authority.db._conn.execute(- "SELECT id FROM sessions WHERE user_id=? AND chat_id LIKE 'local-%' AND archived=0 "- "ORDER BY COALESCE(last_activity_at,started_at) DESC LIMIT 1", (actor.subject,)).fetchone()+ f"SELECT id FROM sessions WHERE {owner_filter}chat_id LIKE 'local-%' AND archived=0 "+ "ORDER BY COALESCE(last_activity_at,started_at) DESC LIMIT 1",+ owner_params).fetchone()if latest:row['last_session'] = summary(authority.db.get_session(latest[0]))profiles = [row]diff --git a/gateway/session_operator.py b/gateway/session_operator.pynew file mode 100644index 00000000000..8a494a9f78f--- /dev/null+++ b/gateway/session_operator.py@@ -0,0 +1,23 @@+"""Private provenance for already-authorized local operator input.++Operator access is profile-local, not account linking or a change of authorship.+It never claims unowned legacy history: that still requires the native migration+path. Only SessionAuthority.submit writes this envelope after authorization;+public submission parameters cannot supply it.+"""+from hermes_state_runtime import RuntimeStoreError+++def check_local_input(authority, ref, row):+ payload = row['payload']+ allowed = {'text', 'attachments_v1', 'finite'}+ if 'local_operator_v1' in payload:+ allowed.add('local_operator_v1')+ if payload['local_operator_v1'] != {+ 'profile_id': authority.profile_id, 'session_id': ref.session_id,+ 'principal_id': row['principal_id']}:+ raise RuntimeStoreError('permission_denied')+ elif row['principal_id'] != authority.sessions[ref.session_id].source.user_id:+ raise RuntimeStoreError('permission_denied')+ if not {'text'} <= set(payload) <= allowed:+ raise RuntimeStoreError('permission_denied')diff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.pyindex a0825e4b014..90d6eb72576 100644--- a/hermes_cli/web_routers/chat_ws.py+++ b/hermes_cli/web_routers/chat_ws.py@@ -579,6 +579,7 @@ async def gateway_ws(ws: WebSocket) -> None:await handle_ws(ws,auth_identity=identity,+ operator=True, # The dashboard upgrade gate above has verified this operator.subprotocol=getattr(ws, "_hermes_ws_subprotocol", None),)diff --git a/hermes_cli/web_server_sessions.py b/hermes_cli/web_server_sessions.pyindex 488422a5e83..3153853d5fc 100644--- a/hermes_cli/web_server_sessions.py+++ b/hermes_cli/web_server_sessions.py@@ -103,7 +103,7 @@ def _session_mutation_context(request, profile):if native is not None and native['profile_id'] != authority.profile_id:raise HTTPException(status_code=403, detail='profile_mismatch')return authority, Principal(subject, authority.profile_id,- frozenset({'session:read', 'session:control', 'session:create'}), 'http')+ frozenset({'session:read', 'session:control', 'session:create', 'session:operator'}), 'http')async def _mutate_session_request(request, profile, session_id, *, request_id,diff --git a/tests/gateway/fixtures/ancillary_reads_peer.py b/tests/gateway/fixtures/ancillary_reads_peer.pyindex 11f0be479e8..630b360266d 100644--- a/tests/gateway/fixtures/ancillary_reads_peer.py+++ b/tests/gateway/fixtures/ancillary_reads_peer.py@@ -31,7 +31,7 @@ async def probe(mode):return connect(api.api_origin.replace('http:', 'ws:') + '/api/ws?ticket=' + ticket)try:- async with socket() as ws, socket('stranger') as stranger:+ async with socket() as ws, socket('peer_operator') as peer_operator:created = await rpc(ws, 'session.create', request_id='read-owner', source='gui', toolsets=[])assert 'result' in created, createdsid = created['result']['session_id']@@ -40,8 +40,13 @@ async def probe(mode):methods = ['session.control.read', 'process.list', 'subagent.list', 'subagent.tail']for method in methods:args = {'subagent_id': 'unowned'} if method == 'subagent.tail' else {}- denied = await rpc(stranger, method, session_id=sid, **args)- assert denied.get('error', {}).get('message') == 'permission_denied', denied+ shared = await rpc(peer_operator, method, session_id=sid, **args)+ original = await rpc(ws, method, session_id=sid, **args)+ # Both tickets are verified dashboard operators; underlying child+ # membership checks still apply, including the absent tail target.+ assert shared.get('result') == original.get('result'), (shared, original)+ assert shared.get('error') == original.get('error'), (shared, original)+ assert shared.get('error', {}).get('message') != 'permission_denied', shareddenied = await rpc(ws, method, session_id=sid, profile='foreign', **args)assert denied.get('error', {}).get('message') == 'profile_mismatch', denieddiff --git a/tests/gateway/fixtures/operator_cross_surface_peer.py b/tests/gateway/fixtures/operator_cross_surface_peer.pynew file mode 100644index 00000000000..4b885846116--- /dev/null+++ b/tests/gateway/fixtures/operator_cross_surface_peer.py@@ -0,0 +1,224 @@+"""Disposable gateway; only the IdP and loopback model wire are synthetic."""+import asyncio+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import sys+import threading+import traceback++from tests.gateway.fixtures.shared_authority_peer import ModelPeer+++async def probe(peer, creator):+ import httpx+ from websockets.asyncio.client import connect+ from gateway.run import GatewayRunner+ from gateway.run_bootstrap import _start_gateway_start_control_socket+ from gateway.run_runtime import (initialize_gateway_runtime, start_gateway_runtime_api,+ publish_gateway_runtime_ready)+ from gateway.runtime_ownership import process_ownership+ from hermes_cli import web_server+ from hermes_cli.dashboard_auth import register_provider, clear_providers+ from hermes_state_local import local_receipt+ from hermes_state_runtime import list_session_admissions+ from tests.hermes_cli.conftest_dashboard_auth import StubAuthProvider+ from tests.gateway.test_normal_runtime_boot import control++ home = Path(os.environ['HERMES_HOME'])+ register_provider(StubAuthProvider())+ process_ownership.reserve([home])+ runner = GatewayRunner()+ sockets = []+ bootstrap = None+ try:+ await initialize_gateway_runtime(runner)+ bootstrap = await _start_gateway_start_control_socket(runner)+ assert bootstrap is not None+ await start_gateway_runtime_api(runner)+ assert await runner.start()+ publish_gateway_runtime_ready(runner)+ assert web_server.app.state.auth_required is True+ descriptor = await asyncio.to_thread(control, home, 'identify')+ authority = runner.session_authority+ origin = descriptor['api_origin']+ url = origin.replace('http:', 'ws:') + '/api/ws'+ binding = dict(profile_id=str(home), instance_id=descriptor['instance_id'], purpose='interactive')++ async def native(purpose='interactive'):+ grant = await asyncio.to_thread(control, home, 'session-ticket', {**binding, 'purpose': purpose})+ ws = await connect(url, subprotocols=['hermes-gateway-v1', 'hermes-gateway-ticket.' + grant['ticket']])+ sockets.append(ws)+ return ws++ counter = 0+ async def rpc(ws, method, error=None, **params):+ nonlocal counter+ counter += 1+ rid = counter+ await ws.send(json.dumps(dict(jsonrpc='2.0', id=rid, method=method, params=params)))+ async with asyncio.timeout(20):+ while True:+ frame = json.loads(await ws.recv())+ if frame.get('id') == rid:+ if error:+ assert frame.get('error', {}).get('message') == error, frame+ return frame['error']+ assert 'result' in frame, frame+ return frame['result']++ async with httpx.AsyncClient(base_url=origin, trust_env=False) as client:+ assert (await client.post('/api/auth/ws-ticket')).status_code == 401+ # Walk real login, PKCE callback, cookie verification, then ticket mint.+ login = await client.get('/auth/login', params={'provider': 'stub'})+ assert login.status_code == 302, login.text+ from urllib.parse import urlsplit+ callback_url = urlsplit(login.headers['location'])+ assert callback_url.netloc == 'gateway.example.test'+ # The declared public origin is a browser-origin policy, not a network peer.+ callback = await client.get(callback_url.path + '?' + callback_url.query)+ assert callback.status_code == 302, callback.text+ me = await client.get('/api/auth/me')+ assert me.status_code == 200, me.text++ async def dashboard():+ response = await client.post('/api/auth/ws-ticket')+ assert response.status_code == 200, response.text+ ws = await connect(url, origin='https://gateway.example.test', subprotocols=[+ 'hermes-gateway-v1', 'hermes-gateway-ticket.' + response.json()['ticket']])+ sockets.append(ws)+ return ws++ native_ws, dashboard_ws = await native(), await dashboard()+ owner, viewer = ((native_ws, dashboard_ws) if creator == 'native'+ else (dashboard_ws, native_ws))+ created = await rpc(owner, 'session.create', request_id='cross-surface-create',+ source='cli' if creator == 'native' else 'gui',+ cwd=str(home), toolsets=[])+ sid = created['session_id']+ assert created['stored_session_id'] == sid+ original_owner = local_receipt(authority.db, sid)['principal_id']+ initial = await rpc(owner, 'session.resume', session_id=sid)+ # Bounded, benign invalid requests: restricted bootstrap purpose is not an operator.+ restricted = await native('worker-adoption')+ await rpc(restricted, 'session.resume', error='permission_denied', session_id=sid)+ await rpc(restricted, 'prompt.submit', error='permission_denied', session_id=sid,+ input_id='restricted', text='not admitted')+ for changed in ({'profile_id': str(home / 'other')}, {'instance_id': 'another-instance'}):+ try:+ await asyncio.to_thread(control, home, 'session-ticket', {**binding, **changed})+ except AssertionError as exc:+ assert 'PermissionError' in str(exc), str(exc)+ else:+ raise AssertionError('bootstrap accepted foreign binding')+ for field, value in (('operator', True), ('operator_scope', str(home)),+ ('capabilities', ['session:operator'])):+ await rpc(viewer, 'session.create', error='invalid_params',+ request_id='unsupported-' + field, source='gui', **{field: value})++ attached = await rpc(viewer, 'session.resume', session_id=sid)+ assert attached['stored_session_id'] == sid+ assert attached['replay_epoch'] == initial['replay_epoch']+ assert attached['subscription_id'] != initial['subscription_id']+ listing = await rpc(viewer, 'session.list')+ assert sid in {row['session_id'] for row in listing['sessions']}++ first = await rpc(owner, 'prompt.submit', session_id=sid, input_id='first',+ text='BLOCK_FIFO WS_SHARED')+ assert first['status'] == 'queued', first+ assert await asyncio.to_thread(peer.blocked.wait, 25), 'real inference never started'+ followup = dict(session_id=sid, input_id='followup', text='WS_SHARED followup')+ accepted = await rpc(viewer, 'prompt.submit', **followup)+ assert accepted['status'] == 'queued', accepted+ assert await rpc(viewer, 'prompt.submit', **followup) == accepted+ rows = list_session_admissions(authority.db, session_id=sid, pending_only=False)+ assert len(rows) == 2, rows+ assert rows[0]['principal_id'] == original_owner, rows+ assert rows[1]['principal_id'] != original_owner, rows+ assert rows[1]['payload']['local_operator_v1'] == {+ 'profile_id': authority.profile_id, 'session_id': sid,+ 'principal_id': rows[1]['principal_id']}+ attribution = [row['principal_id'] for row in rows]+ assert any(subject.startswith('uid:') for subject in attribution), attribution+ assert len(set(attribution)) == 2+ await owner.close()+ await viewer.close()+ # No connected viewer owns this accepted work. A new surface sees the same queue.+ viewer = await (dashboard() if creator == 'native' else native())+ assert (await rpc(viewer, 'session.resume', session_id=sid))['stored_session_id'] == sid+ assert await rpc(viewer, 'prompt.submit', **followup) == accepted+ peer.release.set()+ async with asyncio.timeout(45):+ while True:+ rows = list_session_admissions(authority.db, session_id=sid, pending_only=False)+ if len(rows) == 2 and all(row['status'] == 'terminal' for row in rows):+ break+ await asyncio.sleep(.05)+ assert [row['principal_id'] for row in rows] == attribution+ assert local_receipt(authority.db, sid)['principal_id'] == original_owner+ messages = authority.db.get_messages_as_conversation(sid)+ user_text = [m['content'] for m in messages if m['role'] == 'user']+ assert user_text == ['BLOCK_FIFO WS_SHARED', 'WS_SHARED followup'], messages+ assert len(peer.requests) == 2, peer.requests+ assert any(message['role'] == 'assistant' and 'LOCAL_ACK_WS_SHARED' in str(message['content'])+ for message in peer.requests[1]['messages']), peer.requests[1]+ systems = [[message for message in request['messages'] if message['role'] == 'system']+ for request in peer.requests]+ assert systems[0] == systems[1], 'operator handoff changed frozen system policy'+ assert 'local_operator_v1' not in json.dumps(peer.requests)+ replay = await rpc(viewer, 'session.events.since', session_id=sid,+ replay_epoch=initial['replay_epoch'], last_sequence=initial['last_sequence'])+ assert not replay['snapshot_required'], replay+ assert len([event for event in replay['events'] if event['type'] == 'message.complete']) == 2+ snapshot = await rpc(viewer, 'session.resume', session_id=sid)+ assert snapshot['stored_session_id'] == sid+ assert 'LOCAL_ACK_WS_SHARED' in json.dumps(snapshot['messages'])+ assert 'local_operator_v1' not in json.dumps([initial, attached, accepted, replay, snapshot])+ (home / 'operator-receipt.json').write_text(json.dumps(dict(+ creator=creator, model_requests=len(peer.requests), distinct_attribution=True,+ disconnect_survived=True, negative_boundaries=True)))+ finally:+ peer.release.set()+ for ws in sockets:+ await ws.close()+ if bootstrap:+ await bootstrap.stop()+ await runner.stop()+ process_ownership.close()+ clear_providers()+++def main():+ peer = ThreadingHTTPServer(('127.0.0.1', 0), ModelPeer)+ peer.requests, peer.metadata_requests = [], []+ peer.blocked, peer.release = threading.Event(), threading.Event()+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ os.environ.update(OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)+ home = Path(os.environ['HERMES_HOME'])+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False},+ 'dashboard': {'public_url': 'https://gateway.example.test'},+ 'model': {'provider': 'custom', 'default': 'local-wire-stub', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}},+ }))+ try:+ asyncio.run(probe(peer, sys.argv[1]))+ finally:+ peer.release.set()+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)+++if __name__ == '__main__':+ status = 0+ try:+ main()+ except BaseException:+ traceback.print_exc()+ status = 1+ # Third-party executor threads must not outlive this disposable test process.+ os._exit(status)diff --git a/tests/gateway/test_operator_cross_surface.py b/tests/gateway/test_operator_cross_surface.pynew file mode 100644index 00000000000..b4821d1bba3--- /dev/null+++ b/tests/gateway/test_operator_cross_surface.py@@ -0,0 +1,31 @@+"""Real native bootstrap and dashboard login share one canonical worker, not identities."""+import json+import os+from pathlib import Path+import subprocess+import sys++import pytest++[email protected]_only[email protected]('creator', ['native', 'dashboard'])+def test_operator_cross_surface_real_auth_fifo_and_attribution(tmp_path, creator):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ # Do not inherit credentials, plugins, provider configuration, or user state.+ env = {key: os.environ[key] for key in ('PATH', 'LANG', 'TZ') if key in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),+ PYTHONPATH=str(root), PYTHONUNBUFFERED='1')+ result = subprocess.run(+ [sys.executable, str(root / 'tests/gateway/fixtures/operator_cross_surface_peer.py'), creator],+ cwd=root, env=env, capture_output=True, text=True, timeout=150)+ assert result.returncode == 0, result.stdout + result.stderr+ receipt = json.loads((home / 'operator-receipt.json').read_text())+ assert receipt['creator'] == creator+ assert receipt['model_requests'] == 2+ assert receipt['distinct_attribution'] is True+ assert receipt['disconnect_survived'] is True+ assert receipt['negative_boundaries'] is Truediff --git a/tests/gateway/test_session_busy_controls.py b/tests/gateway/test_session_busy_controls.pyindex 566d0d0dd40..6b89ce462bc 100644--- a/tests/gateway/test_session_busy_controls.py+++ b/tests/gateway/test_session_busy_controls.py@@ -124,7 +124,11 @@ def test_busy_policy_is_authorized_session_scoped_and_not_inference(tmp_path):for method in ('config.get', 'config.set'):params = {'value': 'queue'} if method == 'config.set' else {}result = await rpc(other, method, session_id=ids[0], key='busy', **params)- assert result.get('error', {}).get('message') == 'permission_denied', result+ # This configured dashboard token is another verified operator.+ assert result.get('result') == {+ 'key': 'busy', 'value': 'queue', 'scope': 'session'}, result+ assert (await rpc(ws, 'config.get', session_id=ids[0], key='busy'))['result']['value'] == 'queue'+ assert (await rpc(ws, 'config.get', session_id=ids[1], key='busy'))['result']['value'] == 'steer'assert (home / 'config.yaml').read_bytes() == config_beforeassert not admissions(home) and not peer.requestsasyncio.run(probe())@@ -153,11 +157,12 @@ def test_corrections_are_generation_fenced_and_consumed_by_same_provider_loop(tmassert denied.get('error', {}).get('message') == reason, deniedother_url = desc['api_origin'].replace('http:', 'ws:') + '/api/ws?token=other-controls-actor'async with connect(other_url) as other:+ # Operator sharing does not bypass the execution-generation fence.denied = await rpc(other, 'session.' + verb, session_id=sid,- execution_generation=generation, text='DENIED_MARKER')- assert denied.get('error', {}).get('message') == 'permission_denied', denied- result = await rpc(ws, 'session.' + verb, session_id=sid,- execution_generation=generation, text='CORRECT_' + verb.upper())+ execution_generation=generation - 1, text='DENIED_MARKER')+ assert denied.get('error', {}).get('message') == 'stale_generation', denied+ result = await rpc(other, 'session.' + verb, session_id=sid,+ execution_generation=generation, text='CORRECT_' + verb.upper())assert result.get('result', {}).get('status') == status, resultassert result['result']['execution_generation'] == generationqueue = await rpc(ws, 'prompt.submit', session_id=sid, input_id=verb + '-queue', text='FIFO_' + verb.upper())diff --git a/tests/gateway/test_session_commands.py b/tests/gateway/test_session_commands.pyindex 257a00dc74e..16071aa67ee 100644--- a/tests/gateway/test_session_commands.py+++ b/tests/gateway/test_session_commands.py@@ -102,14 +102,14 @@ def test_ordinary_daemon_slash_skill_uses_durable_fifo(tmp_path):({'command': 'approve'}, 'unsupported_command')]:denied = await command(**params)assert denied['error']['message'] == reason, denied- # A second valid credential is a different actor, not session ownership.+ # A second dashboard operator shares access but still obeys the busy fence.other_url = desc['api_origin'].replace('http:', 'ws:') + '/api/ws?token=owned-slash-negative'async with connect(other_url) as other:for method, payload in [('slash.exec', {'command': 'title stolen'}),('command.dispatch', {'name': 'title', 'arg': 'stolen'})]:- denied = await rpc(other, method, session_id=sid, **payload)- receipts.append(denied)- assert denied.get('error', {}).get('message') == 'permission_denied', denied+ result = await rpc(other, method, session_id=sid, **payload)+ receipts.append(result)+ assert 'mid-turn' in result.get('result', {}).get('output', ''), resultpeer.release.set()async with asyncio.timeout(45):while any(row[1] != 'terminal' for row in rows()):diff --git a/tests/gateway/test_session_config_projection.py b/tests/gateway/test_session_config_projection.pyindex c93ae46777b..5e923e9b1bd 100644--- a/tests/gateway/test_session_config_projection.py+++ b/tests/gateway/test_session_config_projection.py@@ -49,7 +49,13 @@ def test_client_config_projection_keeps_session_policy_and_secrets_private(tmp_passert (await rpc(ws, method, **params))['error']['message'] == reasonother_url = desc['api_origin'].replace('http:', 'ws:') + '/api/ws?token=other-controls-actor'async with connect(other_url) as other:- assert (await rpc(other, 'config.get', key='full', session_id=sid))['error']['message'] == 'permission_denied'+ # Verified dashboard operators receive the same redacted projection.+ shared = await rpc(other, 'config.get', key='full', session_id=sid)+ current = await rpc(ws, 'config.get', key='full', session_id=sid)+ assert 'result' in shared, shared+ assert shared['result'] == current['result']+ assert 'PRIVATE_VOICE' not in json.dumps(shared)+ assert (await rpc(other, 'config.get', key='reasoning', session_id=sid))['result']['value'] == 'low'assert (home / 'config.yaml').read_bytes() == beforeassert not admissions(home) and not peer.requestsasyncio.run(probe())@@ -72,7 +78,11 @@ def test_model_options_uses_frozen_selection_without_composer_global_writes(tmp_assert (await rpc(ws, 'model.options', session_id=sid, refresh='yes'))['error']['message'] == 'invalid_params'other_url = desc['api_origin'].replace('http:', 'ws:') + '/api/ws?token=other-controls-actor'async with connect(other_url) as other:- assert (await rpc(other, 'model.options', session_id=sid))['error']['message'] == 'permission_denied'+ shared = await rpc(other, 'model.options', session_id=sid)+ current = await rpc(ws, 'model.options', session_id=sid)+ assert shared.get('result', {}).get('model') == 'frozen-picker', shared+ assert shared['result'] == current['result']+ assert 'loopback-only' not in json.dumps(shared)assert (home / 'config.yaml').read_bytes() == beforeassert not admissions(home) and not peer.requestsasyncio.run(probe())diff --git a/tests/gateway/test_session_operator_scope.py b/tests/gateway/test_session_operator_scope.pynew file mode 100644index 00000000000..157d2b81b7c--- /dev/null+++ b/tests/gateway/test_session_operator_scope.py@@ -0,0 +1,124 @@+"""Operator scope changes access, not durable authorship or execution fences."""+from dataclasses import replace+from types import SimpleNamespace++import pytest++from gateway.session_contract import Principal, Submission+from gateway.session_controls import AuthorityConnection+from hermes_state_runtime import RuntimeStoreError, list_session_admissions+++async def test_operators_share_local_sessions_without_reassigning_receipts(tmp_path, monkeypatch):+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_local import create_local_session+ from gateway.session_local_title import resolve_titled_session+ from gateway.session_mutations import mutate_session+ from gateway.session_group_controls import _profiles++ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False)+ authority = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='fixture')+ caps = frozenset({'session:create', 'session:read', 'session:submit', 'session:control', 'session:operator'})+ native = Principal('uid:1000', str(tmp_path), caps, 'native')+ remote = Principal('auth:v1:remote', str(tmp_path), caps, 'remote')+ executed = []++ async def execute(authority, ref, row):+ executed.append((row['principal_id'], row['payload']['text']))+ return 'fixture result'++ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)+ for owner, peer in ((native, remote), (remote, native)):+ ref = create_local_session(authority, owner, {'request_id': owner.subject, 'source': 'gui',+ 'cwd': str(tmp_path), 'model': 'fixture', 'toolsets': []})+ authority.db.append_message(ref.session_id, 'user', 'retained history')+ snapshot = await authority.attach(peer, ref)+ assert snapshot.history[0]['content'] == 'retained history'+ assert authority.sessions[ref.session_id].source.user_id == owner.subject+ edit = dict(session_id=ref.session_id, request_id='rename', expected_revision=0,+ operation='rename', payload={'title': 'Bot Chat'})+ await mutate_session(authority, peer, ref, edit)+ assert resolve_titled_session(authority, peer, 'Bot Chat') == ref+ assert _profiles(authority, peer, tmp_path, {})['profiles'][0]['canonical_session']['id'] == ref.session_id+ with pytest.raises(RuntimeStoreError, match='revision_conflict'):+ await mutate_session(authority, peer, ref, {**edit, 'request_id': 'stale'})+ with pytest.raises(RuntimeStoreError, match='stale_generation'):+ await authority.interrupt(peer, ref, -1)+ for actor in (owner, peer):+ await authority.submit(actor, Submission('same-input', ref, {'text': actor.subject}, 'queue'))+ await authority.sessions[ref.session_id].task+ rows = list_session_admissions(authority.db, session_id=ref.session_id, pending_only=False)+ assert [row['principal_id'] for row in rows] == [owner.subject, peer.subject]+ assert all(row['status'] == 'terminal' for row in rows)+ assert executed[-2:] == [(owner.subject, owner.subject), (peer.subject, peer.subject)]+ for denied in (replace(peer, profile_id='foreign'), replace(peer, capabilities=caps - {'session:read'}),+ replace(peer, capabilities=caps - {'session:operator'})):+ with pytest.raises(RuntimeStoreError):+ await authority.attach(denied, ref)+ await authority.detach(peer, snapshot.subscription_id)+ # Free the unique title before testing the inverse direction.+ authority.db.set_session_title(ref.session_id, 'Finished ' + owner.subject)+ # A disconnected operator's accepted turn must survive a new authority epoch.+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)+ receipt = await authority.submit(peer, Submission('restart', ref, {'text': 'after restart'}, 'queue'))+ runner.adapters = {}+ cold = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='restarted')+ await cold._drain(ref)+ assert (await cold.receipt(peer, ref, receipt.admission_id)).status == 'terminal'+ assert executed[-1] == (peer.subject, 'after restart')+ assert (await cold.attach(peer, ref)).history[0]['content'] == 'retained history'+ store._db.close()+++async def test_identity_fields_cannot_grant_operator_or_first_claim(tmp_path, monkeypatch):+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_local import create_local_session++ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False)+ authority = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='fixture')+ owner = Principal('owner', str(tmp_path), frozenset({'session:create'}), 'owner')+ ref = create_local_session(authority, owner, {'request_id': 'owner', 'source': 'gui',+ 'cwd': str(tmp_path), 'model': 'fixture', 'toolsets': []})+ identity = {'user_id': 'other', 'provider': 'local', 'operator': True,+ 'profile_id': str(tmp_path), 'instance_id': 'fixture', 'native_bootstrap': True,+ 'capabilities': ['session:operator', 'session:read', 'session:create']}+ connection = AuthorityConnection(authority, object(), identity)+ assert 'session:operator' not in connection.actor.capabilities+ with pytest.raises(RuntimeStoreError, match='permission_denied'):+ await authority.attach(connection.actor, ref)+ authority.db.create_session('unowned', source='cli')+ operator = replace(connection.actor, capabilities=connection.actor.capabilities | {'session:operator'})+ from gateway.session_local_migration import resolve_local_target+ with pytest.raises(RuntimeStoreError):+ resolve_local_target(authority, operator, 'unowned')+ trusted = AuthorityConnection(authority, object(), {'user_id': 'verified'}, operator=True)+ assert 'session:operator' in trusted.actor.capabilities+ resumed = await trusted.dispatch({'id': 1, 'method': 'session.resume',+ 'params': {'session_id': ref.session_id}})+ assert resumed['result']['session_id'] == ref.session_id+ listing = await trusted.dispatch({'id': 2, 'method': 'session.list', 'params': {}})+ assert ref.session_id in {s['id'] for s in listing['result']['sessions']}+ denied = await trusted.dispatch({'id': 3, 'method': 'prompt.submit', 'params': {+ 'session_id': ref.session_id, 'input_id': 'forged', 'text': 'no',+ 'local_operator_v1': {'principal_id': 'owner'}}})+ assert denied['error']['message'] == 'invalid_params'+ for changed in ({'instance_id': 'foreign'}, {'capabilities': ['worker:adopt']}):+ restricted = AuthorityConnection(authority, object(), {'user_id': 'verified', **changed}, operator=True)+ with pytest.raises(RuntimeStoreError):+ await authority.attach(restricted.actor, ref)+ await restricted.close()+ await trusted.close()+ await connection.close()+ store._db.close()diff --git a/tests/gateway/test_static_token_session_mutations.py b/tests/gateway/test_static_token_session_mutations.pyindex a90c9bebe69..77d36b22126 100644--- a/tests/gateway/test_static_token_session_mutations.py+++ b/tests/gateway/test_static_token_session_mutations.py@@ -50,8 +50,8 @@ def test_static_token_http_mutations_reuse_ws_owner(tmp_path):else:saved.update(sid=sid, receipt=result)async with websocket(home, desc) as native:- denied = await rpc(native, 'session.resume', session_id=sid)- assert denied['error']['message'] == 'permission_denied', denied+ resumed = await rpc(native, 'session.resume', session_id=sid)+ assert resumed.get('result', {}).get('session_id') == sid, resumedfor _ in range(2):with daemon(root, home, env, barrier=False) as (_, desc):diff --git a/tui_gateway/ws.py b/tui_gateway/ws.pyindex b907476d90f..1e112b6ca06 100644--- a/tui_gateway/ws.py+++ b/tui_gateway/ws.py@@ -261,7 +261,8 @@ class _SendFailed(Exception):"""Raised by handle_ws._reply when a reply could not be written: ends the read loop."""-async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol: str | None = None) -> None:+async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol: str | None = None,+ operator: bool = False) -> None:"""Run one WebSocket session. Wire-compatible with ``tui_gateway.entry``. *auth_identity* is the server-minted``{user_id, provider}`` recorded at WS-upgrade auth, stored as ``WSTransport.auth_identity`` (the only identityauthority for browser-controller registration); callers that omit it (harnesses, embedded TUI child) get None."""@@ -294,7 +295,7 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:getattr(getattr(ws, 'app', None), 'state', None), 'session_authority', None)if authority is not None:from gateway.session_controls import AuthorityConnection- authority_connection = AuthorityConnection(authority, transport, auth_identity or {})+ authority_connection = AuthorityConnection(authority, transport, auth_identity or {}, operator=operator)# resolve_skin() is sync I/O + CPU; pooled so the read loop can drain the frontend's initial RPC burst.skin_payload = await asyncio.to_thread(server.resolve_skin)# change_events: this backend broadcasts pet/cron/sessions.changed, so clients can demote legacydiff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.mdindex 98080755f0d..7ea7a763f11 100644--- a/website/docs/user-guide/sessions.md+++ b/website/docs/user-guide/sessions.md@@ -26,22 +26,41 @@ The SQLite database stores:- Timestamps (started_at, ended_at)- Parent session ID (for compression-triggered session splitting)-### Authenticated gateway session ownership--Sessions created through the canonical gateway are owned by the authenticated-identity, not its display name. Dashboard identities include the auth provider,-verified OAuth issuer (when present), and subject. A password account and an OAuth-account with the same subject do not share ownership; changing OAuth issuers also-changes the owner. HTTP session mutations and WebSocket controls use the same key.-Reconnects and daemon restarts retain creation and mutation retry receipts for the-same identity. Private native bootstrap identities keep their existing owner keys-and session IDs.+### Authenticated gateway session access and attribution++The gateway owns execution; a client does not own the running agent. Verified+operators of the same gateway profile can attach to canonical local CLI, TUI, or+Desktop sessions created through another operator authentication method. For+example, a native local operator and an authenticated dashboard operator can+access the same conversation without creating another runtime. Closing a client+connection detaches that client; accepted work remains with the gateway.++This deliberately replaces creator-only access for verified operators, preserving+the dashboard's existing operator permissions. Password and OAuth identities stay+distinct but do not create separate access barriers to canonical local sessions+when both connections have operator access to the profile. The trusted server+paths include native interactive bootstrap, authenticated dashboard tickets,+internal credentials used by server-spawned PTY clients, and the verified legacy+dashboard token. HTTP session mutations also accept the verified native HTTP owner+grant. This does not grant operator permissions to restricted worker, messaging,+room, or service credentials, or remove profile and operation-specific checks.++Attribution remains identity-specific. Dashboard identities include the provider,+verified OAuth issuer (when present), and subject. Creation receipts retain the+original identity; submissions and mutation retries retain the acting identity.+An operator joining a session does not replace its recorded owner or merge retry+identities. Native bootstrap owner keys and session IDs remain unchanged.Older remote sessions whose receipts contain only a bare subject cannot establish-which provider owned them. They remain stored but are not automatically assigned to-the first authenticated account requesting them. This is not a change to the-personal dashboard's general operator permissions or a guarantee of isolation for-all historical messaging sessions.+which provider owned them. They remain stored but are not automatically assigned+to the first authenticated account requesting them. Operator access does not permit+remote first-claim adoption of unowned historical transcripts.++Cross-device attachment also requires a supported, authenticated route to the same+gateway. Shared operator access does not itself expose a remote listener or add+OpenAI-compatible API continuation of local sessions. A gateway crash is different+from a client disconnect: interrupted work becomes `unknown` rather than being+automatically replayed, and may need resolution before queued followers proceed.### What Counts Toward Context