The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: verify native Ink Stop acknowledgement and fresh follow-up
Tekniumd0ad8324c840
diff --git a/ui-tui/scripts/native_canonical_probe.py b/ui-tui/scripts/native_canonical_probe.pyindex 46ea352f899..3bbe97b0cb6 100644--- a/ui-tui/scripts/native_canonical_probe.py+++ b/ui-tui/scripts/native_canonical_probe.py@@ -37,6 +37,10 @@ def run():user = base / 'user'user.mkdir()peer_class = ModelPeer+ stopping = kind in ('stop', 'stop-control')+ if stopping:+ from native_stop_probe import StopPeer+ peer_class = StopPeerif kind in ('approval', 'clarify'):sys.path.insert(0, str(ROOT / 'tests/gateway/fixtures'))if kind == 'approval':@@ -49,6 +53,9 @@ def run():model = ThreadingHTTPServer(('127.0.0.1', 0), peer_class)model.command = 'rm -r -- ' + shlex.quote(str(target))model.requests, model.metadata_requests = [], []+ model.blocked, model.release, model.disconnected = threading.Event(), threading.Event(), threading.Event()+ if stopping:+ model.command = 'touch -- ' + shlex.quote(str(home / 'stop-effect'))threading.Thread(target=model.serve_forever, daemon=True).start()model_url = f'http://127.0.0.1:{model.server_port}/v1'(home / 'config.yaml').write_text(json.dumps({@@ -155,7 +162,10 @@ def run():assert receipts['prepared_journal_cleared']returnlog = (base / 'daemon.log').open('w+')- daemon = subprocess.Popen([sys.executable, '-m', 'gateway.run'], cwd=ROOT, env=env,+ daemon_argv = [sys.executable, '-m', 'gateway.run']+ if stopping:+ daemon_argv = [sys.executable, str(ROOT / 'ui-tui/scripts/native_stop_probe.py')]+ daemon = subprocess.Popen(daemon_argv, cwd=ROOT, env=env,stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)deadline = time.monotonic() + 35while time.monotonic() < deadline:@@ -170,6 +180,11 @@ def run():receipts['instance_id'] = g['instance_id']sid = asyncio.run(seed())first = launch('first', sid, 'WS_SHARED')+ if stopping:+ from native_stop_probe import exercise+ exercise(kind, model, first, sid, grant, rpc, connect, home, receipts, Path(sys.argv[1]))+ receipts['daemon_survived_stop'] = daemon.poll() is None+ returnsecond = launch('second', sid)if kind != 'text':card = b'Allow once' if kind == 'approval' else b'green'@@ -248,6 +263,9 @@ def run():assert receipts['native_answer_on_model_wire']assert receipts['reconnect_rendered_reply']finally:+ model.release.set()+ if 'first' in locals():+ (Path(sys.argv[1]) / 'last-first.pty').write_bytes(first[2])for proc, master in children:if proc.poll() is None:os.killpg(proc.pid, signal.SIGTERM)diff --git a/ui-tui/scripts/native_stop_probe.py b/ui-tui/scripts/native_stop_probe.pynew file mode 100644index 00000000000..c1542780b93--- /dev/null+++ b/ui-tui/scripts/native_stop_probe.py@@ -0,0 +1,131 @@+"""Loopback Stop exercise and observation-only recording of real RPC replies."""+import asyncio+from http.server import BaseHTTPRequestHandler+import json+import os+from pathlib import Path+import runpy+import shlex+import sys+import time+++class StopPeer(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_GET(self):+ self.send_response(200)+ self.end_headers()+ self.wfile.write(b'{"data": []}')++ def do_POST(self):+ try:+ self.respond()+ except (BrokenPipeError, ConnectionResetError):+ # Interrupt closes the real inference stream before its final chunk.+ self.server.disconnected.set()++ def respond(self):+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ messages = body.get('messages', [])+ self.server.requests.append(messages)+ latest = next((m.get('content') for m in reversed(messages) if m['role'] == 'user'), '')+ asking = bool(messages) and latest != 'AFTER_STOP' and not any(m['role'] == 'tool' for m in messages)+ message = {'role': 'assistant', 'content': 'FRESH_AFTER_STOP' if latest == 'AFTER_STOP' else 'STOP_CONTROL_FINISHED'}+ if asking:+ message = {'role': 'assistant', 'tool_calls': [{+ 'index': 0, 'id': 'owned-stop-control', 'type': 'function', 'function': {+ 'name': 'terminal', 'arguments': json.dumps({'command': self.server.command})}}]}+ self.send_response(200)+ self.send_header('Content-Type', 'text/event-stream' if body.get('stream') else 'application/json')+ self.end_headers()+ if body.get('stream'):+ def emit(delta, finish=None):+ frame = {'id': 'local', 'object': 'chat.completion.chunk', 'created': 1,+ 'model': 'local', 'choices': [{'index': 0, 'delta': delta, 'finish_reason': finish}]}+ self.wfile.write(('data: ' + json.dumps(frame) + '\n\n').encode())+ self.wfile.flush()+ if asking:+ emit({'role': 'assistant', 'content': 'STOP_RUNNING'})+ self.server.blocked.set()+ assert self.server.release.wait(30), 'native Stop never released the model boundary'+ emit(message)+ emit({}, 'tool_calls' if asking else 'stop')+ self.wfile.write(b'data: [DONE]\n\n')+ else:+ self.wfile.write(json.dumps({'id': 'local', 'choices': [{'index': 0, 'message': message,+ 'finish_reason': 'tool_calls' if asking else 'stop'}]}).encode())+ self.wfile.flush()+++def exercise(kind, model, first, sid, grant, rpc, connect, home, receipts, destination):+ def wait(predicate, seconds=15):+ deadline = time.monotonic() + seconds+ while time.monotonic() < deadline:+ if predicate():+ return+ assert first[0].poll() is None, bytes(first[2]).decode(errors='replace')+ time.sleep(.05)+ raise AssertionError('native Stop condition timeout')++ wait(lambda: model.blocked.is_set() and b'STOP_RUNNING' in first[2])+ control = home / 'native-control-receipts.jsonl'+ if kind == 'stop':+ os.write(first[1], b'\x03')+ wait(lambda: control.exists())+ wire = [json.loads(line) for line in control.read_text().splitlines()]+ (destination / 'native-interrupt.json').write_text(json.dumps(wire, indent=2))+ receipts['native_interrupt_acknowledged'] = any(+ row['request']['params']['session_id'] == sid and 'result' in row['reply']+ and row['reply']['result']['execution_generation'] == row['request']['params']['execution_generation']+ for row in wire)+ assert receipts['native_interrupt_acknowledged']+ model.release.set()++ async def snapshot():+ g = grant()+ async with connect(g['url'], subprotocols=g['protocols']) as ws:+ async with asyncio.timeout(15):+ while True:+ result = await rpc(ws, 'session.resume', session_id=sid)+ if not result['running']:+ return result+ await asyncio.sleep(.05)+ settled = asyncio.run(snapshot())+ (destination / 'stopped-snapshot.json').write_text(json.dumps(settled, indent=2))+ effect = home / 'stop-effect'+ receipts['post_stop_tool_suppressed'] = not effect.exists()+ assert effect.exists() == (kind == 'stop-control')+ os.write(first[1], b'AFTER_STOP')+ wait(lambda: b'AFTER_STOP' in first[2])+ os.write(first[1], b'\r')+ wait(lambda: b'FRESH_AFTER_STOP' in first[2])+ receipts['fresh_after_stop_rendered'] = True+ final = asyncio.run(snapshot())+ (destination / 'fresh-snapshot.json').write_text(json.dumps(final, indent=2))+ (destination / 'stop.pty').write_bytes(first[2])+ receipts['fresh_after_stop_persisted'] = any(+ row.get('content') == 'FRESH_AFTER_STOP' for row in final['messages'])+ receipts['prepared_journal_cleared'] = not list((home / 'tui-pending-inputs').glob('*.json'))+ assert receipts['fresh_after_stop_persisted'] and receipts['prepared_journal_cleared']+++def daemon():+ root = Path(__file__).resolve().parents[2]+ sys.path.insert(0, str(root))+ from gateway.session_controls import AuthorityConnection+ original = AuthorityConnection.dispatch+ async def observed(self, request):+ reply = await original(self, request)+ if request.get('method') == 'session.interrupt':+ with (Path(os.environ['HERMES_HOME']) / 'native-control-receipts.jsonl').open('a') as output:+ output.write(json.dumps({'request': request, 'reply': reply}) + '\n')+ return reply+ AuthorityConnection.dispatch = observed+ sys.argv = ['gateway.run']+ runpy.run_module('gateway.run', run_name='__main__')+++if __name__ == '__main__':+ daemon()