The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): one-shot chats on managed workers never wait on an approval
Teknium0a2ae8857390
diff --git a/gateway/session_kanban.py b/gateway/session_kanban.pyindex fcb5462fb44..ec33dff6743 100644--- a/gateway/session_kanban.py+++ b/gateway/session_kanban.py@@ -203,6 +203,12 @@ def _watch_submitter(db, run_id):def run_worker_turns(agent, frame, history):+ from gateway.session_managed_worker import worker_turn_scope+ with worker_turn_scope(frame):+ return _run_worker_turns(agent, frame, history)+++def _run_worker_turns(agent, frame, history):context = json.loads(frame['policy'].get('kanban_json') or 'null')if context is None:author = frame.get('turn_author')diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.pyindex 0ea16c758d9..cf8dace4a3a 100644--- a/gateway/session_managed_worker.py+++ b/gateway/session_managed_worker.py@@ -1,5 +1,6 @@"""Admission-owned production exec; observers never own the worker lifetime."""import asyncio+from contextlib import contextmanagerfrom dataclasses import asdict, replaceimport jsonimport queue@@ -50,9 +51,13 @@ def _bootstrap(authority, ref, row, policy, scope):for path, value in recover_config_secrets(authority, policy).items():if path[0] is None:terminal[path[1]] = value- hydrated = replace(policy, config_json=json.dumps(policy.config(authority)),- terminal_json=json.dumps(terminal), credential_ref=None, config_secret_ref=None)live = authority.sessions[ref.session_id]+ # This turn's facts ride the per-turn hydrated request (the bootstrap field set is closed):+ # the admission's one-shot flags, bound in the owner only for in-process turns.+ request = dict(json.loads(policy.request_json), turn_v1={+ 'finite': row['payload'].get('finite', False), 'unattended': row['payload'].get('unattended') is True})+ hydrated = replace(policy, config_json=json.dumps(policy.config(authority)), request_json=json.dumps(request),+ terminal_json=json.dumps(terminal), credential_ref=None, config_secret_ref=None)return {'version': 1, 'home': authority.profile_id, 'scope': scope,'policy': asdict(hydrated), 'api_key': launch_key(authority, policy),'text': row['payload']['text'], 'route': live.route,@@ -62,6 +67,23 @@ def _bootstrap(authority, ref, row, policy, scope):'safe_mode': policy.safe_mode, 'ignore_user_config': policy.ignore_user_config}+@contextmanager+def worker_turn_scope(frame):+ """Child side of ``turn_v1``: bind what the in-process turn binds on the owner+ (execute_finite_admission), so ``chat -q``/``-z`` never park a prompt. Frames without it+ bind nothing."""+ from gateway.session_finite import finite_turn_scope+ turn = json.loads(frame['policy'].get('request_json') or '{}').get('turn_v1')+ if turn is None:+ yield+ return+ if (not isinstance(turn, dict) or set(turn) != {'finite', 'unattended'}+ or any(type(v) is not bool for v in turn.values()) or (turn['unattended'] and not turn['finite'])):+ raise ValueError('invalid_managed_worker_bootstrap')+ with finite_turn_scope(turn['finite'], turn['unattended']):+ yield++class ManagedWorker:def __init__(self, process):self.process = processdiff --git a/tests/gateway/test_managed_worker_turn_flags.py b/tests/gateway/test_managed_worker_turn_flags.pynew file mode 100644index 00000000000..6786563c25c--- /dev/null+++ b/tests/gateway/test_managed_worker_turn_flags.py@@ -0,0 +1,114 @@+"""A managed worker applies the same per-turn approval facts as the in-process turn: the admission's+one-shot flags (``chat -q`` / ``-z``) and the route's current YOLO bypass, including its revocation."""+import asyncio+from contextlib import closing+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+import os+from pathlib import Path+import sqlite3+import threading++import pytest++from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket+++class Model(BaseHTTPRequestHandler):+ """Asks for one dangerous terminal call per user turn, then answers once the tool result lands."""+ def log_message(self, *args):+ pass++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ last = (body.get('messages') or [{'role': 'system'}])[-1]+ if last['role'] == 'user':+ message = {'role': 'assistant', 'content': None, 'tool_calls': [{'id': 'call-%d' % len(body['messages']),+ 'type': 'function', 'function': {'name': 'terminal',+ 'arguments': json.dumps({'command': self.server.command, 'timeout': 10})}}]}+ else:+ message = {'role': 'assistant', 'content': 'TURN_DONE'}+ choice = {'index': 0, 'delta': message, 'finish_reason': 'tool_calls' if message.get('tool_calls') else 'stop'}+ for index, call in enumerate(message.get('tool_calls', [])):+ call['index'] = index+ frame = {'id': 'flags', 'model': 'flags-model', 'choices': [choice],+ 'usage': {'prompt_tokens': 1, 'completion_tokens': 1, 'total_tokens': 2}}+ if body.get('stream'):+ payload, kind = ('data: ' + json.dumps(frame) + '\n\ndata: [DONE]\n\n').encode(), 'text/event-stream'+ else:+ choice['message'] = choice.pop('delta')+ payload, kind = json.dumps(frame).encode(), 'application/json'+ 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)+++def _run(tmp_path, scenario):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ target = home / 'delete-me'+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.command = 'rm -rf ' + str(target)+ threading.Thread(target=peer.serve_forever, daemon=True).start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False, 'managed_workers': True},+ 'model': {'provider': 'custom', 'default': 'flags-model', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}},+ 'approvals': {'mode': 'manual', 'single_query_mode': 'deny'}, 'platform_toolsets': {'cli': ['terminal']}}))+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)++ def status(request_id):+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ return db.execute('SELECT status FROM session_admissions WHERE request_id=?', (request_id,)).fetchall()++ async def turn(ws, sid, request_id, **flags):+ """Submit one turn; returns 'prompted' if it parked an approval, else 'settled'."""+ target.mkdir(exist_ok=True)+ submitted = await rpc(ws, 'prompt.submit', session_id=sid, input_id=request_id, text='DELETE', **flags)+ assert 'result' in submitted, submitted+ async with asyncio.timeout(90):+ while status(request_id) != [('terminal',)]:+ snapshot = await rpc(ws, 'session.resume', session_id=sid)+ prompt = next((p for p in snapshot['result']['prompts'] if p['kind'] == 'approval'), None)+ if prompt:+ await rpc(ws, 'approval.respond', session_id=sid, prompt_id=prompt['prompt_id'],+ execution_generation=prompt['execution_generation'], choice='deny')+ while status(request_id) != [('terminal',)]:+ await asyncio.sleep(.05)+ return 'prompted'+ await asyncio.sleep(.1)+ return 'settled'++ async def exercise(desc):+ async with websocket(home, desc) as ws:+ created = await rpc(ws, 'session.create', request_id='flags', source='cli', cwd=str(home),+ model='flags-model', provider='custom', base_url=url, api_key='loopback-only',+ toolsets=['terminal'], ignore_rules=True)+ assert 'result' in created, created+ await scenario(ws, created['result']['session_id'], turn, target)+ try:+ with daemon(root, home, env, barrier=False) as (_owner, desc):+ asyncio.run(exercise(desc))+ finally:+ peer.shutdown()+ peer.server_close()++[email protected]("linux")+def test_one_shot_managed_turns_never_park_an_approval(tmp_path):+ async def scenario(ws, sid, turn, target):+ # `-z`: nobody can answer, so the classic one-shot contract auto-approves.+ assert await turn(ws, sid, 'unattended', finite=True, unattended=True) == 'settled'+ assert not target.exists()+ # `chat -q`: approvals.single_query_mode (deny here) decides instantly, never a parked prompt.+ assert await turn(ws, sid, 'single-query', finite=True) == 'settled'+ assert target.exists()+ _run(tmp_path, scenario)+