The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: restore scoped canonical busy and correction controls
Tekniumdaa016976b09
diff --git a/gateway/session_busy_controls.py b/gateway/session_busy_controls.pynew file mode 100644index 00000000000..4e57b480879--- /dev/null+++ b/gateway/session_busy_controls.py@@ -0,0 +1,73 @@+"""Session-scoped busy preferences and controls of the existing execution only."""+from functools import partial+from pathlib import Path++from hermes_state_runtime import RuntimeStoreError+++def handlers(connection):+ return {+ 'config.get': partial(busy_config, connection),+ 'config.set': partial(busy_config, connection, write=True),+ 'session.steer': partial(correct, connection, verb='steer'),+ 'session.redirect': partial(correct, connection, verb='redirect'),+ }+++def authorize(connection, ref, params, capability):+ connection.authority.authorize(connection.actor, ref, capability)+ if 'profile' in params:+ from hermes_cli.profiles import profile_matches_home+ profile = params['profile']+ if not isinstance(profile, str):+ raise RuntimeStoreError('invalid_params')+ if profile and not profile_matches_home(profile, Path(connection.authority.profile_id)):+ raise RuntimeStoreError('profile_mismatch')+++async def busy_config(connection, ref, params, *, write=False):+ allowed = {'session_id', 'profile', 'key'} | ({'value'} if write else set())+ if (set(params) - allowed or not ref.session_id or params.get('key') != 'busy'+ or (write and params.get('value') not in ('interrupt', 'steer', 'queue'))):+ raise RuntimeStoreError('invalid_params')+ authorize(connection, ref, params, 'session:control' if write else 'session:read')+ authority = connection.authority+ live = authority.sessions[ref.session_id]+ if write:+ # UI negotiation is not a settings write and must not rebuild frozen+ # launch policy, toolsets, history, or the retained AIAgent.+ live.busy_input_mode = params['value']+ value = getattr(live, 'busy_input_mode', None)+ if value is None:+ from gateway.session_policy import policy_for_source+ policy = policy_for_source(authority.runner, live.source)+ value = (policy.config().get('display', {}).get('busy_input_mode', 'interrupt') if policy else+ authority.runner._effective_busy_input_mode(live.source))+ if value not in ('interrupt', 'steer', 'queue'):+ value = 'interrupt'+ return {'key': 'busy', 'value': value, 'scope': 'session'}+++async def correct(connection, ref, params, *, verb):+ if (set(params) - {'session_id', 'profile', 'text', 'execution_generation'}+ or not isinstance(params.get('text'), str) or not params['text'].strip()+ or type(params.get('execution_generation')) is not int):+ raise RuntimeStoreError('invalid_params')+ authorize(connection, ref, params, 'session:control')+ authority = connection.authority+ generation = params['execution_generation']+ live = authority.sessions[ref.session_id]+ with live.event_stream.lock:+ authority.check_approval_generation(ref.session_id, generation)+ # Managed workers have a separate control channel, not a cached owner+ # agent. Refuse explicitly instead of acknowledging undeliverable text.+ if ref.session_id in getattr(authority, '_managed_workers', {}):+ raise RuntimeStoreError('unsupported_control')+ agent = authority.agent(ref)+ method = getattr(agent, verb, None)+ if not callable(method):+ raise RuntimeStoreError('execution_not_ready')+ accepted = method(params['text'])+ return {'status': ({'steer': 'queued', 'redirect': 'redirected'}[verb] if accepted else 'rejected'),+ 'text': params['text'], 'execution_generation': generation,+ 'authority_epoch': authority.epoch}diff --git a/tests/gateway/test_session_busy_controls.py b/tests/gateway/test_session_busy_controls.pynew file mode 100644index 00000000000..566d0d0dd40--- /dev/null+++ b/tests/gateway/test_session_busy_controls.py@@ -0,0 +1,180 @@+"""Public owner controls never become a second admission or change the cached prefix."""+import asyncio+from contextlib import contextmanager+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+from pathlib import Path+import sqlite3+import threading++import pytest+from websockets.asyncio.client import connect++from tests.gateway.fixtures.local_recovery_probe import child_env, daemon, rpc, websocket+++class CorrectionModel(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ messages = body.get('messages', [])+ if messages:+ self.server.requests.append(body)+ text = next((m['content'] for m in reversed(messages) if m['role'] == 'user'), '')+ message = {'role': 'assistant', 'content': 'CONTROL_ACK'}+ finish = 'stop'+ if text in {'BLOCK_STEER', 'BLOCK_REDIRECT'}:+ self.server.blocked.set()+ self.server.release.wait(30)+ if text == 'BLOCK_STEER':+ message = {'role': 'assistant', 'content': None, 'tool_calls': [{+ 'id': 'owned-tool', 'type': 'function', 'function': {+ 'name': 'terminal', 'arguments': json.dumps({'command': 'printf controls', 'timeout': 5})}}]}+ finish = 'tool_calls'+ payload = json.dumps({'id': 'controls', 'choices': [{'index': 0, 'message': message, 'finish_reason': finish}],+ 'usage': {'prompt_tokens': 10, 'completion_tokens': 5, 'total_tokens': 15}}).encode()+ kind = 'application/json'+ if body.get('stream'):+ delta = dict(message)+ if 'tool_calls' in delta:+ delta['tool_calls'] = [dict(delta['tool_calls'][0], index=0)]+ payload = ('data: ' + json.dumps({'id': 'controls', 'choices': [{'index': 0, 'delta': delta,+ 'finish_reason': finish}]}) + '\n\ndata: [DONE]\n\n').encode()+ kind = 'text/event-stream'+ try:+ self.send_response(200)+ self.send_header('Content-Type', kind)+ self.send_header('Content-Length', str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)+ except (BrokenPipeError, ConnectionResetError):+ pass+++@contextmanager+def owner(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), CorrectionModel)+ peer.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'+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False}, 'display': {'busy_input_mode': 'steer'},+ 'model': {'provider': 'custom', 'default': 'controls-fixture', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}},+ }))+ env = child_env()+ 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',+ HERMES_DASHBOARD_SESSION_TOKEN='other-controls-actor')+ try:+ with daemon(root, home, env, barrier=False) as (_, desc):+ yield home, peer, desc+ finally:+ peer.release.set()+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)+++def admissions(home):+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:+ return list(db.execute('SELECT request_id,status,seq FROM session_admissions ORDER BY seq'))+++async def settled(home):+ async with asyncio.timeout(40):+ while not admissions(home) or any(r[1] != 'terminal' for r in admissions(home)):+ await asyncio.sleep(.05)++[email protected]_only+def test_busy_policy_is_authorized_session_scoped_and_not_inference(tmp_path):+ with owner(tmp_path) as (home, peer, desc):+ async def probe():+ async with websocket(home, desc) as ws:+ ids = []+ for name in ('a', 'b'):+ result = await rpc(ws, 'session.create', request_id=name, source='tui', toolsets=[])+ ids.append(result['result']['session_id'])+ config_before = (home / 'config.yaml').read_bytes()+ result = await rpc(ws, 'config.get', session_id=ids[0], key='busy')+ assert result.get('result', {}).get('value') == 'steer', result+ result = await rpc(ws, 'config.set', session_id=ids[0], key='busy', value='queue')+ assert result.get('result', {}).get('scope') == 'session', result+ async with websocket(home, desc) as viewer:+ assert (await rpc(viewer, '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'+ for method, params, reason in [+ ('config.get', {'session_id': ids[0], 'key': 'busy', 'profile': 'foreign'}, 'profile_mismatch'),+ ('config.set', {'key': 'busy', 'value': 'queue'}, 'invalid_params'),+ ('config.set', {'session_id': ids[0], 'key': 'model', 'value': 'other'}, 'invalid_params'),+ ]:+ result = await rpc(ws, method, **params)+ assert result.get('error', {}).get('message') == reason, result+ other_url = desc['api_origin'].replace('http:', 'ws:') + '/api/ws?token=other-controls-actor'+ async with connect(other_url) as other:+ 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+ assert (home / 'config.yaml').read_bytes() == config_before+ assert not admissions(home) and not peer.requests+ asyncio.run(probe())++[email protected]_only+def test_corrections_are_generation_fenced_and_consumed_by_same_provider_loop(tmp_path):+ with owner(tmp_path) as (home, peer, desc):+ async def probe():+ async with websocket(home, desc) as ws:+ created = await rpc(ws, 'session.create', request_id='controls', source='tui', toolsets=['terminal'])+ sid = created['result']['session_id']+ await rpc(ws, 'prompt.submit', session_id=sid, input_id='warm', text='WARM')+ await settled(home)+ for verb, status in [('steer', 'queued'), ('redirect', 'redirected')]:+ peer.blocked.clear()+ peer.release.clear()+ await rpc(ws, 'prompt.submit', session_id=sid, input_id=verb, text='BLOCK_' + verb.upper())+ assert await asyncio.to_thread(peer.blocked.wait, 25)+ snapshot = (await rpc(ws, 'session.resume', session_id=sid))['result']+ generation = snapshot['execution_generation']+ for extra, reason in [({'execution_generation': generation - 1}, 'stale_generation'),+ ({'profile': 'foreign'}, 'profile_mismatch')]:+ params = {'session_id': sid, 'text': 'DENIED_MARKER', 'execution_generation': generation, **extra}+ denied = await rpc(ws, 'session.' + verb, **params)+ assert denied.get('error', {}).get('message') == reason, denied+ other_url = desc['api_origin'].replace('http:', 'ws:') + '/api/ws?token=other-controls-actor'+ async with connect(other_url) as other:+ 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())+ assert result.get('result', {}).get('status') == status, result+ assert result['result']['execution_generation'] == generation+ queue = await rpc(ws, 'prompt.submit', session_id=sid, input_id=verb + '-queue', text='FIFO_' + verb.upper())+ assert queue['result']['status'] == 'queued'+ peer.release.set()+ await settled(home)+ corrected = [r for r in peer.requests if 'CORRECT_' + verb.upper() in json.dumps(r['messages'])]+ assert corrected, peer.requests+ assert not any('DENIED_MARKER' in json.dumps(r) for r in peer.requests)+ stale = await rpc(ws, 'session.' + verb, session_id=sid,+ execution_generation=generation, text='TOO_LATE')+ assert stale.get('error', {}).get('message') == 'stale_generation', stale+ assert [r[0] for r in admissions(home)] == ['warm', 'steer', 'steer-queue', 'redirect', 'redirect-queue']+ prefixes = [[m for m in r['messages'] if m['role'] in {'system', 'developer'}] for r in peer.requests]+ assert prefixes and all(p == prefixes[0] for p in prefixes)+ tools = [r.get('tools') for r in peer.requests]+ assert all(t == tools[0] for t in tools)+ print(json.dumps({'ledger': admissions(home), 'model_requests': len(peer.requests),+ 'same_prefix': True, 'corrections_consumed': True}))+ asyncio.run(probe())diff --git a/website/docs/developer-guide/gateway-internals.md b/website/docs/developer-guide/gateway-internals.mdindex dc51d521d70..9af71c076bc 100644--- a/website/docs/developer-guide/gateway-internals.md+++ b/website/docs/developer-guide/gateway-internals.md@@ -76,6 +76,26 @@ bundles, configuration/runtime changes, lifecycle commands, and approval/secretslash shortcuts are not exposed. Existing generation-bound approval and interruptRPCs remain separate. Catalog discovery is broader than this reviewed execution set.+## Shared authority busy input and corrections++`config.get({session_id, key: "busy"})` projects the session's frozen busy-input+preference. `config.set({session_id, key: "busy", value})` accepts `interrupt`,+`steer`, or `queue` and changes only that live session's preference, shared by its+viewers until owner restart. Neither operation changes profile settings or the+cached agent/system prompt. Other config keys are not handled by this adapter.++`session.steer` and `session.redirect` require `session_id`, `text`, and the current+`execution_generation`, plus authenticated session-control rights. Optional+`profile` must match the authority. Controls target the existing running agent:+steer uses the ordinary correction drain; redirect cancels an active model request+and continues the same turn (or steers at a tool boundary). They never create a+queued admission or silently fall back to a new turn. `queued` (steer) and+`redirected` acknowledge runtime acceptance, not crash-durable delivery; do not+automatically retry an ambiguous reply. `rejected` means the runtime missed the+active correction window, while `stale_generation` rejects settled/replaced work.+Managed-worker corrections currently return `unsupported_control`; normal durable+queue submission and Stop remain separate controls.+## Shared authority setup readinessAuthenticated local clients can call `setup.status` and `setup.runtime_check` before