Skip to content

The agent that grows with you

fix: expose owner-scoped ancillary session reads

Teknium61ace21a95a9
diff --git a/gateway/session_ancillary.py b/gateway/session_ancillary.py
new file mode 100644
index 00000000000..9a50cf05161
--- /dev/null
+++ b/gateway/session_ancillary.py
@@ -0,0 +1,148 @@
+"""Read-only Desktop/Ink projections of existing owner state.
+
+No legacy server, manager construction, process recovery, or execution on reads.
+"""
+from functools import partial
+import sys
+
+from gateway.session_busy_controls import authorize
+from hermes_state_runtime import RuntimeStoreError
+
+
+_SUBAGENT_FIELDS = (
+ 'subagent_id', 'parent_id', 'depth', 'goal', 'delegation_id', 'model',
+ 'started_at', 'status', 'tool_count', 'last_tool', 'accepting_steer',
+)
+_TAIL_BYTES = 16384
+
+
+def handlers(connection):
+ return {name: partial(read, connection, kind=kind) for name, kind in {
+ 'session.control.read': 'control', 'process.list': 'processes',
+ 'subagent.list': 'subagents', 'subagent.tail': 'tail',
+ }.items()}
+
+
+async def read(connection, ref, params, *, kind):
+ fields = {'session_id', 'profile'} | ({'subagent_id'} if kind == 'tail' else set())
+ if (set(params) - fields or not isinstance(ref.session_id, str) or not ref.session_id
+ or (kind == 'tail' and (not isinstance(params.get('subagent_id'), str)
+ or not params['subagent_id']))):
+ raise RuntimeStoreError('invalid_params')
+ authority = connection.authority
+ # Cold adoption belongs to session.resume, never an ancillary poll.
+ if ref.session_id not in authority.sessions:
+ raise RuntimeStoreError('not_found')
+ authorize(connection, ref, params, 'session:read')
+ live = authority.sessions[ref.session_id]
+ with live.event_stream.lock:
+ target = physical_target(authority, ref)
+ store = authority.runner.session_store
+ with store._lock:
+ entry = store._entries.get(live.route)
+ if entry is None or entry.session_id != target:
+ raise RuntimeStoreError('stale_generation')
+ if kind == 'control':
+ return {'control': control_snapshot(authority, ref)}
+ # Process-local registries cannot describe another interpreter's live
+ # objects. Never turn that missing authority into a successful empty list.
+ from gateway.session_managed_worker import managed_policy
+ if managed_policy(authority, ref) is not None:
+ raise RuntimeStoreError('unsupported_projection')
+ agent = authority.agent(ref)
+ records = subagent_records(agent)
+ if kind == 'subagents':
+ return {'subagents': [{key: record.get(key) for key in _SUBAGENT_FIELDS}
+ for record in records], 'delegations': []}
+ if kind == 'tail':
+ return subagent_tail(records, params['subagent_id'])
+ return {'processes': process_snapshot(authority, ref, agent, records)}
+
+
+def physical_target(authority, ref):
+ from gateway.config import Platform
+ if authority.sessions[ref.session_id].source.platform == Platform.LOCAL:
+ from hermes_state_local import local_receipt
+ return local_receipt(authority.db, ref.session_id)['entry']['session_id']
+ return ref.session_id
+
+
+def control_snapshot(authority, ref):
+ from hermes_cli.goals import GoalState
+ from hermes_cli.loops import LoopState
+ from hermes_cli.heartbeat import HeartbeatState
+ # These pure serializers don't bind/import the legacy server. In particular
+ # do not reuse _snapshot_control: its manager loader can write on a read.
+ from tui_gateway.methods_session_control import (
+ _safe_goal_snapshot, _safe_loop_snapshot, _safe_heartbeat_snapshot,
+ _snapshot_revision, _snapshot_updated_at,
+ )
+ target = physical_target(authority, ref)
+ states = []
+ for kind, cls in [('goal', GoalState), ('loop', LoopState), ('heartbeat', HeartbeatState)]:
+ raw = authority.db.get_meta(kind + ':' + target)
+ try:
+ states.append(cls.from_json(raw) if raw else None)
+ except (ValueError, TypeError, AttributeError) as exc:
+ raise RuntimeStoreError('storage_unavailable') from exc
+ goal_state, loop_state, heartbeat_state = states
+ goal = _safe_goal_snapshot(goal_state)
+ # Project the persisted barrier, not GoalManager.is_waiting(), which clears
+ # satisfied barriers and can query unrelated processes during a UI refresh.
+ deferred = bool(goal and goal['status'] == 'active' and not goal.get('wait_barrier'))
+ loop = _safe_loop_snapshot(loop_state, deferred_by_goal=bool(
+ deferred and loop_state and loop_state.status == 'active'))
+ heartbeat = _safe_heartbeat_snapshot(heartbeat_state)
+ return {'goal': goal, 'loop': loop, 'heartbeat': heartbeat,
+ 'revision': _snapshot_revision(goal, loop, heartbeat),
+ 'updated_at': _snapshot_updated_at(*states)}
+
+
+def subagent_records(parent):
+ registry = sys.modules.get('tools.delegate_tool_registry')
+ if parent is None or registry is None:
+ return []
+ with registry._active_subagents_lock:
+ # Deliberately no durable-ID fallback: equal IDs cannot transfer a live
+ # old parent's transcript to a replacement execution object.
+ return [dict(record) for record in registry._active_subagents.values()
+ if registry._is_descendant_of(record.get('agent'), parent)]
+
+
+def subagent_tail(records, subagent_id):
+ result = {'subagent_id': subagent_id, 'available': False, 'text': '', 'truncated': False}
+ record = next((r for r in records if r.get('subagent_id') == subagent_id), None)
+ path = getattr(record.get('agent'), '_live_transcript_path', None) if record else None
+ if not path:
+ return result
+ try:
+ with open(path, 'rb') as stream:
+ size = stream.seek(0, 2)
+ stream.seek(max(0, size - _TAIL_BYTES))
+ text = stream.read(_TAIL_BYTES).decode('utf-8', errors='ignore')
+ except OSError:
+ return result
+ return {**result, 'available': True, 'text': text, 'truncated': size > _TAIL_BYTES}
+
+
+def process_snapshot(authority, ref, agent, records):
+ module = sys.modules.get('tools.process_registry')
+ if module is None:
+ return []
+ registry = module.process_registry
+ route = authority.sessions[ref.session_id].route
+ target = physical_target(authority, ref)
+ owners = {target}
+ if agent is not None:
+ owners.add(getattr(agent, 'session_id', None))
+ owners.update(r.get('subagent_id') for r in records)
+ owners.discard(None)
+ owners.discard('')
+ # list_sessions refreshes recovered processes (and writes checkpoints).
+ # Read the current objects directly, keeping ownership and output together.
+ with registry._lock:
+ processes = [p for p in (*registry._running.values(), *registry._finished.values())
+ if p.session_key in {route, target} and (p.owner_task_id or p.task_id) in owners]
+ return [{'session_id': p.id, 'command': p.command[:200],
+ 'status': 'exited' if p.exited else 'running', 'exit_code': p.exit_code,
+ 'output_tail': p.output_buffer[-4000:]} for p in processes]
diff --git a/tests/gateway/fixtures/ancillary_reads_peer.py b/tests/gateway/fixtures/ancillary_reads_peer.py
new file mode 100644
index 00000000000..11f0be479e8
--- /dev/null
+++ b/tests/gateway/fixtures/ancillary_reads_peer.py
@@ -0,0 +1,182 @@
+"""Authenticated TCP fixture with owner-seeded state; no external inference."""
+import asyncio
+import json
+import os
+from pathlib import Path
+import shlex
+import sys
+import traceback
+import weakref
+
+
+async def probe(mode):
+ from gateway.run import GatewayRunner
+ from gateway.session_authority import initialize_session_authority
+ from gateway.run_api import start_gateway_api, stop_gateway_api
+ from gateway.session_contract import SessionRef
+ from hermes_cli import web_server
+ from hermes_cli.dashboard_auth.ws_tickets import mint_ticket
+ from tests.gateway.fixtures.local_recovery_probe import rpc
+ from websockets.asyncio.client import connect
+
+ home = Path(os.environ['HERMES_HOME'])
+ (home / 'config.yaml').write_text('gateway:\n multiplex_profiles: false\nmodel:\n provider: custom\n default: no-inference\n base_url: http://127.0.0.1:1/v1\nauxiliary:\n title_generation:\n enabled: false\n')
+ runner = GatewayRunner()
+ authority = await initialize_session_authority(runner, profile_id=str(home), instance_id='ancillary')
+ api = await start_gateway_api(runner)
+ web_server.app.state.auth_required = True
+
+ def socket(actor='owner'):
+ ticket = mint_ticket(user_id=actor, provider='fixture')
+ return connect(api.api_origin.replace('http:', 'ws:') + '/api/ws?ticket=' + ticket)
+
+ try:
+ async with socket() as ws, socket('stranger') as stranger:
+ created = await rpc(ws, 'session.create', request_id='read-owner', source='gui', toolsets=[])
+ assert 'result' in created, created
+ sid = created['result']['session_id']
+ ref = SessionRef(str(home), sid)
+ live = authority.sessions[sid]
+ 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
+ denied = await rpc(ws, method, session_id=sid, profile='foreign', **args)
+ assert denied.get('error', {}).get('message') == 'profile_mismatch', denied
+
+ if mode == 'control':
+ from hermes_cli.goals import GoalState, GoalGate
+ from hermes_cli.loops import LoopState
+ from hermes_cli.heartbeat import HeartbeatState
+ # Owner writes fixture rows; reads must not call managers that clear barriers.
+ goal = GoalState('OWNER_GOAL', status='paused', created_at=10, waiting_on_pid=99999999,
+ gates=[GoalGate(command='owned command', last_output_tail='PRIVATE_GATE_OUTPUT')])
+ loop = LoopState('OWNER_LOOP', status='paused', created_at=20, route={'token': 'PRIVATE_ROUTE'})
+ heartbeat = HeartbeatState('OWNER_HEARTBEAT', 600, status='paused', created_at=30)
+ for key, state in [('goal', goal), ('loop', loop), ('heartbeat', heartbeat)]:
+ authority.db.set_meta(key + ':' + sid, state.to_json())
+ authority.db.set_meta(key + ':' + live.route, state.to_json().replace('OWNER_', 'WRONG_ROUTE_'))
+ before = authority.db._conn.total_changes
+ responses = [await rpc(ws, 'session.control.read', session_id=sid) for _ in range(2)]
+ assert 'result' in responses[0], responses
+ snap = responses[0]['result']['control']
+ assert responses[0] == responses[1]
+ assert snap['goal']['title'] == 'OWNER_GOAL' and snap['loop']['prompt'] == 'OWNER_LOOP'
+ assert snap['heartbeat']['prompt'] == 'OWNER_HEARTBEAT' and snap['updated_at'] == 30
+ assert snap['goal']['wait_barrier']['target'] == 99999999
+ assert 'PRIVATE_' not in json.dumps(snap) and len(snap['revision']) == 64
+ assert authority.db._conn.total_changes == before
+ for method, expected in [('process.list', {'processes': []}),
+ ('subagent.list', {'subagents': [], 'delegations': []})]:
+ result = await rpc(ws, method, session_id=sid)
+ assert result.get('result') == expected, result
+ assert authority.agent(ref) is None
+ assert not authority.db.get_messages(sid)
+ authority.sessions.pop(sid)
+ result = await rpc(ws, 'session.control.read', session_id=sid)
+ assert result.get('error', {}).get('message') == 'not_found', result
+ assert sid not in authority.sessions, 'read restored a cold session'
+ authority.sessions[sid] = live
+ else:
+ from tools.process_registry import process_registry
+ from tools.delegate_tool_child_run import _register_child
+ from tools.delegate_tool_registry import _unregister_subagent
+ class Agent:
+ pass
+ parent, old_parent, other_parent = Agent(), Agent(), Agent()
+ parent.session_id = old_parent.session_id = sid
+ other_parent.session_id = 'foreign-session'
+ with runner._agent_cache_lock:
+ runner._agent_cache[live.route] = (parent, 'fixture')
+ children = []
+ processes = []
+ gate = home / 'release-process'
+ try:
+ for name, ancestor in [('owned', parent), ('stale', old_parent), ('sibling', other_parent)]:
+ child = Agent()
+ child._subagent_id = name
+ child._delegate_parent_ref = weakref.ref(ancestor)
+ child._parent_session_id = ancestor.session_id
+ child._live_transcript_path = home / (name + '.txt')
+ child._live_transcript_path.write_text(name.upper() + '_PRIVATE\n' + 'x' * 18000 + '\n' + name.upper() + '_TAIL')
+ _register_child(child, ancestor, name + '-goal', owner_session_id=None,
+ owner_transport=None, owner_session_record=None)
+ children.append(child)
+ command = (shlex.quote(sys.executable) + ' -c ' + shlex.quote(
+ "import pathlib,time;print('PROCESS_OWNED',flush=True);p=pathlib.Path(" + repr(str(gate)) + ");\nwhile not p.exists(): time.sleep(.02)"))
+ for task, route in [(sid, live.route), ('foreign', live.route), (sid, 'wrong-route')]:
+ processes.append(process_registry.spawn_local(command, cwd=str(home), task_id=task,
+ owner_task_id=task, session_key=route))
+ async with asyncio.timeout(10):
+ while any('PROCESS_OWNED' not in p.output_buffer for p in processes):
+ await asyncio.sleep(.02)
+ process_result = await rpc(ws, 'process.list', session_id=sid)
+ rows = process_result.get('result', {}).get('processes')
+ assert rows and [p['session_id'] for p in rows] == [processes[0].id], process_result
+ assert rows[0]['status'] == 'running' and 'PROCESS_OWNED' in rows[0]['output_tail']
+ # Real process handoff stores the parent physical ID as its routing key.
+ transferred = process_registry.transfer_ownership(
+ processes[1].id, from_owner='foreign', to_owner=sid, to_task_id=sid, to_session_key=sid)
+ assert transferred is processes[1]
+ handed = await rpc(ws, 'process.list', session_id=sid)
+ assert {p['session_id'] for p in handed['result']['processes']} == {p.id for p in processes[:2]}, handed
+ roster = await rpc(ws, 'subagent.list', session_id=sid)
+ assert [r['subagent_id'] for r in roster.get('result', {}).get('subagents', [])] == ['owned'], roster
+ assert 'agent' not in roster['result']['subagents'][0]
+ for child in children:
+ tail = await rpc(ws, 'subagent.tail', session_id=sid, subagent_id=child._subagent_id)
+ data = tail['result']
+ assert data['available'] == (child._subagent_id == 'owned'), tail
+ if data['available']:
+ assert data['text'].endswith('OWNED_TAIL') and data['truncated']
+ assert len(data['text'].encode()) <= 16384
+ else:
+ assert data['text'] == ''
+ # A route can be reused while an old LiveSession remains attached.
+ with runner.session_store._lock:
+ entry = runner.session_store._entries[live.route]
+ entry.session_id = 'replacement-conversation'
+ rejected = await rpc(ws, 'subagent.list', session_id=sid)
+ assert rejected.get('error', {}).get('message') == 'stale_generation', rejected
+ with runner.session_store._lock:
+ entry.session_id = sid
+ # Identical durable session IDs cannot transfer old-object read authority.
+ with runner._agent_cache_lock:
+ runner._agent_cache[live.route] = (Agent(), 'new-generation')
+ roster = await rpc(ws, 'subagent.list', session_id=sid)
+ assert roster['result']['subagents'] == [], roster
+ tail = await rpc(ws, 'subagent.tail', session_id=sid, subagent_id='owned')
+ assert not tail['result']['available']
+ from dataclasses import replace
+ from gateway.config import Platform
+ adapter = runner.adapters[Platform.LOCAL]
+ policy = adapter.policies[live.source.chat_id]
+ adapter.policies[live.source.chat_id] = replace(policy, ignore_user_config=True)
+ for method in ('process.list', 'subagent.list', 'subagent.tail'):
+ args = {'subagent_id': 'owned'} if method == 'subagent.tail' else {}
+ result = await rpc(ws, method, session_id=sid, **args)
+ assert result.get('error', {}).get('message') == 'unsupported_projection', result
+ finally:
+ gate.touch()
+ for proc in processes:
+ await asyncio.to_thread(proc._completion_event.wait, 10)
+ assert proc.exited and proc.exit_code == 0
+ for child in children:
+ _unregister_subagent(child._subagent_id, agent=child)
+ (home / 'receipt.json').write_text(json.dumps({'mode': mode, 'authenticated_ws': True,
+ 'foreign_actor_denied': True, 'foreign_profile_denied': True, 'no_inference': True}))
+ finally:
+ await stop_gateway_api(api)
+
+
+if __name__ == '__main__':
+ status = 0
+ try:
+ asyncio.run(probe(sys.argv[1]))
+ except BaseException:
+ traceback.print_exc()
+ status = 1
+ sys.stdout.flush()
+ sys.stderr.flush()
+ os._exit(status)
diff --git a/tests/gateway/test_session_ancillary_reads.py b/tests/gateway/test_session_ancillary_reads.py
new file mode 100644
index 00000000000..04f01642d1b
--- /dev/null
+++ b/tests/gateway/test_session_ancillary_reads.py
@@ -0,0 +1,31 @@
+"""Canonical observers read owner state without bootstrapping legacy services."""
+import json
+from pathlib import Path
+import subprocess
+import sys
+
+from tests.gateway.fixtures.local_recovery_probe import child_env
+
+
+def probe(tmp_path, mode):
+ root = Path(__file__).resolve().parents[2]
+ home, user = tmp_path / 'state', tmp_path / 'user'
+ home.mkdir()
+ user.mkdir()
+ env = child_env()
+ 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/ancillary_reads_peer.py'), mode],
+ cwd=root, env=env, capture_output=True, text=True, timeout=90)
+ assert result.returncode == 0, result.stdout + result.stderr
+ receipt = json.loads((home / 'receipt.json').read_text())
+ assert receipt['mode'] == mode and receipt['authenticated_ws']
+ print(json.dumps(receipt))
+
+
+def test_control_snapshot_is_authorized_read_only_owner_projection(tmp_path):
+ probe(tmp_path, 'control')
+
+
+def test_activity_snapshot_requires_current_owner_objects(tmp_path):
+ probe(tmp_path, 'activity')
diff --git a/website/docs/developer-guide/gateway-internals.md b/website/docs/developer-guide/gateway-internals.md
index 22a1ebe074e..b1ceb035af4 100644
--- a/website/docs/developer-guide/gateway-internals.md
+++ b/website/docs/developer-guide/gateway-internals.md
@@ -30,6 +30,29 @@ recent conversation. Discovery does not create, restore, or unarchive sessions,
open sibling profile databases, or run inference. Cross-profile discovery requires
a separately authenticated connection to the relevant owner.
+## Canonical ancillary reads
+
+Desktop and Ink use authenticated `session.control.read`, `process.list`,
+`subagent.list`, and `subagent.tail` with `session_id`. They require
+`session:read` and the owning profile/session identity. These polls never restore
+a cold session: use `session.resume` first. A retired route binding returns
+`stale_generation` rather than exposing its replacement conversation.
+
+Control reads project the physical transcript's persisted goal, loop and heartbeat
+through the existing frontend field allowlists, without constructing managers or
+clearing wait barriers. Revisions hash the visible snapshot; timed wait barriers
+can disappear when their deadline passes without changing persisted state.
+Process reads use already-owned registry objects and include a bounded output tail;
+they do not recover processes, consume notifications or scan retained receipts.
+Subagent reads require the current parent's live object ancestry, not merely equal
+session IDs; tails are bounded to 16 KiB. Missing or retired children return
+`available: false`. These are reads, not child steering or stop controls.
+
+Managed-worker policies return `unsupported_projection` for process/subagent reads:
+the owner's process-local registry cannot truthfully describe another interpreter.
+Control mutations (`session.control`), process mutations and subagent steering are
+not enabled by these read projections.
+
## Shared authority pending-input snapshots
`session.resume` returns each pending admission with its original `input_id` and