The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: stream canonical gateway execution events to shared observers
Teknium40d9b4c7ea8e
diff --git a/gateway/run_turn_progress.py b/gateway/run_turn_progress.pyindex 769780cbcc3..ac51aa6cb7f 100644--- a/gateway/run_turn_progress.py+++ b/gateway/run_turn_progress.py@@ -723,17 +723,31 @@ class GatewayTurnProgressMixin:def combined_tool_start_callback(self, call_id, tool_name, args):"""Compose the voice ack + native task-card start consumers."""+ self._publish_execution("tool.start", {+ "tool_call_id": str(call_id or ""), "tool_name": str(tool_name or "tool")})if self._ctx._voice_ack_guild[0] is not None:self.voice_ack_callback(call_id, tool_name, args)if self._ctx._native_slack_task_cards:self.native_tool_start_callback(call_id, tool_name, args)+ def combined_tool_complete_callback(self, call_id, tool_name, args, result):+ from agent.display import _detect_tool_failure+ is_error, _ = _detect_tool_failure(tool_name, result)+ self._publish_execution("tool.complete", {+ "tool_call_id": str(call_id or ""), "tool_name": str(tool_name or "tool"),+ "is_error": bool(is_error)})+ if self._ctx._native_slack_task_cards:+ self.native_tool_complete_callback(call_id, tool_name, args, result)+# ── hook / status bridges (agent thread → gateway loop) ────────────────────────────────def _step_callback_sync(self, iteration: int, prev_tools: list) -> None:ctx = self._ctxif not ctx._run_still_current():return+ self._publish_execution("agent.step", {"iteration": iteration})+ if not ctx._hooks_ref.loaded_hooks:+ return# prev_tools may be list[str] or list[dict] with "name"/"result" keys. Normalise so# "tool_names" stays backward-compatible for user hooks that do ', '.join(tool_names).names = [(t.get("name") or "") if isinstance(t, dict) else str(t) for t in (prev_tools or [])]diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 601e3f441b3..6b5715fdb67 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -62,6 +62,12 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):self._approval_owner = (authority, ctx.session_id, generation)+ def _publish_execution(self, event_type, payload):+ if self._approval_owner is not None:+ authority, session_id, generation = self._approval_owner+ return authority.publish_execution(session_id, generation, event_type, payload)+ return False+# ── stream consumer / interim commentary wiring ─────────────────────────────────────────def _setup_stream_consumer(self, platform_key):@@ -103,9 +109,10 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):# Deltas tee to the stream consumer (when text streaming is on) and to streaming TTS.delta_sinks = [sc for sc in ((stream_consumer if want_stream_deltas else None), stts) if sc is not None]stream_delta_cb = None- if delta_sinks:+ if delta_sinks or self._approval_owner is not None:def stream_delta_cb(text: str) -> None:if ctx._run_still_current():+ self._publish_execution("message.delta", {"text": text})for sink in delta_sinks:sink.on_delta(text)@@ -203,7 +210,10 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):if (ctx._voice_ack_guild[0] is not None or ctx._native_slack_task_cards) else None)agent.tool_complete_callback = ctx.native_tool_complete_callback if ctx._native_slack_task_cards else None- agent.step_callback = ctx._step_callback_sync if ctx._hooks_ref.loaded_hooks else None+ if self._approval_owner is not None:+ agent.tool_start_callback = self.combined_tool_start_callback+ agent.tool_complete_callback = self.combined_tool_complete_callback+ agent.step_callback = ctx._step_callback_sync if (ctx._hooks_ref.loaded_hooks or self._approval_owner is not None) else Noneagent.stream_delta_callback = stream_delta_cbagent.interim_assistant_callback = interim_assistant_cb if want_interim_messages else Noneagent.status_callback, agent.notice_callback = ctx._status_callback_sync, self._notice_callback_syncdiff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 57e8f35316f..4c2f03bd3d3 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -207,6 +207,17 @@ class SessionAuthority:if handle.execution_generation != generation or handle.execution_state != "running":raise RuntimeStoreError("stale_generation")+ def publish_execution(self, session_id, generation, event_type, payload):+ """Worker callbacks never outlive their exact running claim."""+ live = self.sessions[session_id]+ with live.event_stream.lock:+ try:+ self.check_approval_generation(session_id, generation)+ except RuntimeStoreError:+ return False+ live.event_stream.publish(session_id, payload, event_type=event_type)+ return True+def register_approval(self, session_id, generation, route, data):live = self.sessions[session_id]with live.event_stream.lock:@@ -247,18 +258,24 @@ class SessionAuthority:if row is None:returnadmission_id = row['admission_id']+ with live.event_stream.lock:+ live.event_stream.execution = {+ 'authority_epoch': self.epoch, 'execution_generation': row['generation'],+ 'admission_id': admission_id}+ live.event_stream.publish(ref.session_id, {}, event_type='message.start')try:response = await execute_admission(self, ref, row)outcome = 'completed'except Exception:response = 'The admitted turn failed.'outcome = 'failed'- settled = settle_session_input(self.db, epoch=self.epoch, admission_id=admission_id,- generation=row['generation'], outcome=outcome)- live.controls.snapshot(ref.session_id, None)- live.event_stream.publish(ref.session_id, {- 'text': response, 'content': response, 'admission_id': admission_id,- 'outcome': settled['outcome']})+ with live.event_stream.lock:+ settled = settle_session_input(self.db, epoch=self.epoch, admission_id=admission_id,+ generation=row['generation'], outcome=outcome)+ live.controls.snapshot(ref.session_id, None)+ live.event_stream.publish(ref.session_id, {+ 'text': response, 'content': response, 'admission_id': admission_id,+ 'outcome': settled['outcome']})waiter = self.waiters.pop(admission_id, None)if waiter is not None and not waiter.done():waiter.set_result(response)diff --git a/gateway/session_events.py b/gateway/session_events.pyindex 96b42cece9d..8d28503fa1d 100644--- a/gateway/session_events.py+++ b/gateway/session_events.py@@ -16,6 +16,7 @@ class SessionEvents:self._key = uuid.uuid4().hexself.epoch = uuid.uuid4().hexself.sequence = 0+ self.execution = {}def watermark(self):with self.lock:@@ -30,7 +31,7 @@ class SessionEvents:with self.lock:self.watermark()frame = {'jsonrpc': '2.0', 'method': 'event', 'params': {- 'type': event_type, 'session_id': self._key,+ **self.execution, 'type': event_type, 'session_id': self._key,'payload': deepcopy(payload), 'replay_epoch': self.epoch}}event_replay._stamp_event(frame)if frame['params']['seq'] <= self.sequence:diff --git a/tests/gateway/fixtures/authority_events_peer.py b/tests/gateway/fixtures/authority_events_peer.pyindex 3f818be0521..7b578fe657a 100644--- a/tests/gateway/fixtures/authority_events_peer.py+++ b/tests/gateway/fixtures/authority_events_peer.py@@ -75,8 +75,11 @@ def main():row = next(r for r in list_session_admissions(authority.db, session_id=ref.session_id,pending_only=False) if r['admission_id'] == receipt.admission_id)assert row['outcome'] == 'completed', row- frame = await asyncio.to_thread(frames.get, True, 5)- frames.put(frame)+ while True:+ frame = await asyncio.to_thread(frames.get, True, 5)+ if frame['params']['type'] == 'message.complete':+ frames.put(frame)+ breakawait a.close()assert len(authority.sessions[ref.session_id].subscribers) == 1await b.close()diff --git a/tests/gateway/fixtures/authority_stream_peer.py b/tests/gateway/fixtures/authority_stream_peer.pynew file mode 100644index 00000000000..81757e1322e--- /dev/null+++ b/tests/gateway/fixtures/authority_stream_peer.py@@ -0,0 +1,218 @@+"""Real SSE execution and authenticated authority observers in a disposable process."""+import asyncio+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+import os+from pathlib import Path+import shlex+import threading+import traceback+++class ModelPeer(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):+ request = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ messages = request.get('messages', [])+ if not messages:+ self.send_response(200)+ self.end_headers()+ self.wfile.write(b'{}')+ return+ self.server.requests.append(request)+ tool = not any(m['role'] == 'tool' for m in messages)+ self.send_response(200)+ self.send_header('Content-Type', 'text/event-stream')+ self.end_headers()+ assert request.get('stream'), 'fixture requires actual streaming model request'+ deltas = [{'role': 'assistant', 'reasoning_content': 'PRIVATE_REASONING_NOT_PUBLIC'}]+ if tool:+ deltas += [{'content': 'Working '}, {'content': 'on the fixture.'}, {'tool_calls': [{+ 'index': 0, 'id': 'owned-tool', 'type': 'function', 'function': {+ 'name': 'terminal', 'arguments': json.dumps({'command': self.server.command})}}]}]+ else:+ deltas += [{'content': 'STREAM_'}, {'content': 'FINISHED'}]+ for delta in deltas + [{}]:+ frame = {'id': 'local-stream', 'object': 'chat.completion.chunk', 'created': 1,+ 'model': 'local-stream', 'choices': [{'index': 0, 'delta': delta,+ 'finish_reason': None if delta else ('tool_calls' if tool else 'stop')}]}+ self.wfile.write(('data: ' + json.dumps(frame) + '\n\n').encode())+ self.wfile.flush()+ self.wfile.write(b'data: [DONE]\n\n')+ self.wfile.flush()+++class Observer:+ def __init__(self, ws, sid):+ self.ws, self.sid = ws, sid+ self.events, self.waiters = [], {}+ self.complete = asyncio.Event()+ self.task = asyncio.create_task(self.read())+ self.rid = 0++ async def read(self):+ async for raw in self.ws:+ frame = json.loads(raw)+ if frame.get('id') in self.waiters:+ self.waiters.pop(frame['id']).set_result(frame)+ elif frame.get('params', {}).get('session_id') == self.sid:+ self.events.append(frame['params'])+ if frame['params']['type'] == 'message.complete':+ self.complete.set()++ async def rpc(self, method, **params):+ self.rid += 1+ future = asyncio.get_running_loop().create_future()+ self.waiters[self.rid] = future+ await self.ws.send(json.dumps({'jsonrpc': '2.0', 'id': self.rid, 'method': method,+ 'params': {'session_id': self.sid, **params}}))+ frame = await asyncio.wait_for(future, 15)+ assert 'result' in frame, frame+ return frame['result']++ async def close(self):+ await self.ws.close()+ await self.task+++async def probe(peer, target):+ import websockets+ from gateway.config import Platform, PlatformConfig+ from gateway.platforms.base import BasePlatformAdapter, SendResult+ from gateway.run import GatewayRunner+ from gateway.run_api import start_gateway_api, stop_gateway_api+ from gateway.session import SessionSource+ from gateway.session_authority import initialize_session_authority+ from hermes_cli import web_server+ from hermes_state_runtime import list_session_admissions+ from run_agent import AIAgent++ class NativeAdapter(BasePlatformAdapter):+ def __init__(self):+ super().__init__(PlatformConfig(enabled=True, token='fixture'), Platform.TELEGRAM)+ self.sent = []+ async def connect(self, *, is_reconnect=False):+ return True+ async def disconnect(self):+ pass+ async def send(self, chat_id, content, reply_to=None, metadata=None):+ self.sent.append(content)+ return SendResult(success=True, message_id='fixture')+ async def edit_message(self, chat_id, message_id, content, *, finalize=False):+ self.sent.append(content)+ return SendResult(success=True, message_id=message_id)+ async def send_typing(self, chat_id, metadata=None):+ pass+ async def get_chat_info(self, chat_id):+ return {'id': chat_id}++ runner = GatewayRunner()+ authority = await initialize_session_authority(runner, profile_id='fixture', instance_id='stream')+ adapter = NativeAdapter()+ runner.adapters[Platform.TELEGRAM] = adapter+ ref = authority.register(SessionSource(platform=Platform.TELEGRAM, chat_id='stream-chat',+ chat_type='dm', user_id='fixture-user'))+ api = await start_gateway_api(runner)+ uri = api.api_origin.replace('http:', 'ws:') + '/api/ws'+ observers = []++ async def connect():+ ws = await websockets.connect(uri + '?token=' + web_server._SESSION_TOKEN, compression=None)+ observer = Observer(ws, ref.session_id)+ observers.append(observer)+ return observer++ try:+ try:+ async with websockets.connect(uri):+ raise AssertionError('unauthenticated observer accepted')+ except websockets.exceptions.InvalidStatus as exc:+ assert exc.response.status_code == 403+ a, b = await connect(), await connect()+ snapshot = await a.rpc('session.resume')+ await b.rpc('session.resume')+ receipt = await a.rpc('prompt.submit', input_id='stream-first', text='Write the owned fixture')+ await asyncio.wait_for(a.complete.wait(), 30)+ await asyncio.wait_for(b.complete.wait(), 10)+ await asyncio.wait_for(authority.sessions[ref.session_id].task, 10)+ assert target.read_text() == 'owned-effect'+ agent = authority.agent(ref)+ assert isinstance(agent, AIAgent)+ rows = list_session_admissions(authority.db, session_id=ref.session_id, pending_only=False)+ assert len(rows) == 1 and rows[0]['outcome'] == 'completed', rows+ expected = {'message.start', 'message.delta', 'tool.start', 'tool.complete', 'agent.step'}+ assert expected <= {e['type'] for e in a.events}, 'real execution omitted canonical start/delta/tool/progress events'+ assert a.events == b.events, 'observers saw competing event ordering/stamps'+ assert [e['seq'] for e in a.events] == list(range(snapshot['last_sequence'] + 1, a.events[-1]['seq'] + 1))+ for event in a.events:+ assert event['session_id'] == ref.session_id+ assert event['execution_generation'] == rows[0]['generation']+ assert event['authority_epoch'] == authority.epoch+ assert event['admission_id'] == receipt['admission_id']+ assert event['replay_epoch'] == snapshot['replay_epoch']+ tools = [e for e in a.events if e['type'].startswith('tool.')]+ assert [e['type'] for e in tools] == ['tool.start', 'tool.complete']+ assert all(e['payload']['tool_call_id'] == 'owned-tool' for e in tools)+ assert 'PRIVATE_REASONING_NOT_PUBLIC' not in json.dumps(a.events)+ assert str(target) not in json.dumps(tools), 'tool args leaked into public stream'+ assert adapter.sent, 'native delivery lane was lost'+ last = a.events[-1]['seq']+ # Same generation is still recorded after settlement; late callbacks must be inert.+ agent.stream_delta_callback('LATE_CALLBACK_NOT_PUBLIC')+ agent.tool_start_callback('late', 'terminal', {'command': 'PRIVATE_ARGS'})+ agent.tool_complete_callback('late', 'terminal', {}, 'PRIVATE_RESULT')+ agent.step_callback(999, [{'name': 'PRIVATE_PREVIOUS_TOOL', 'result': 'SECRET'}])+ replay = await b.rpc('session.events.since', replay_epoch=snapshot['replay_epoch'], last_sequence=0)+ assert replay['last_sequence'] == last, 'settled worker published late callbacks'+ assert replay['events'] == a.events+ cursor = a.events[-2]['seq']+ await a.close()+ observers.remove(a)+ c = await connect()+ await c.rpc('session.resume')+ tail = await c.rpc('session.events.since', replay_epoch=snapshot['replay_epoch'], last_sequence=cursor)+ assert tail['events'] == [a.events[-1]], 'detach/reconnect replay lost terminal tail'+ Path(os.environ['HERMES_HOME'], 'receipt.json').write_text(json.dumps({+ 'real_terminal_effect': True, 'authenticated_observers': 2, 'same_stamps': True,+ 'stale_callback_inert': True, 'reconnect_replay': True, 'model_calls': len(peer.requests),+ 'event_types': [e['type'] for e in a.events], 'event_count': len(a.events)}))+ finally:+ for observer in observers:+ await observer.close()+ await stop_gateway_api(api)+++def main():+ target = Path(os.environ['HERMES_HOME'], 'owned-effect.txt')+ peer = ThreadingHTTPServer(('127.0.0.1', 0), ModelPeer)+ peer.requests = []+ peer.command = 'printf owned-effect > ' + shlex.quote(str(target))+ threading.Thread(target=peer.serve_forever, daemon=True).start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ os.environ.update(OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url,+ TELEGRAM_ALLOWED_USERS='fixture-user', TERMINAL_ENV='local')+ Path(os.environ['HERMES_HOME'], 'config.yaml').write_text(+ f'model:\n default: local-stream\n provider: custom\n base_url: {url}\n'+ 'streaming:\n enabled: true\nauxiliary:\n title_generation:\n enabled: false\n')+ try:+ asyncio.run(probe(peer, target))+ finally:+ peer.shutdown()+ peer.server_close()+++if __name__ == '__main__':+ status = 0+ try:+ main()+ except BaseException:+ traceback.print_exc()+ status = 1+ os._exit(status)diff --git a/tests/gateway/test_authority_events.py b/tests/gateway/test_authority_events.pyindex af3c150c441..160c62260b3 100644--- a/tests/gateway/test_authority_events.py+++ b/tests/gateway/test_authority_events.py@@ -72,13 +72,18 @@ async def test_replay_matches_subscription_watermark_or_requires_snapshot(tmp_paawait b.resume(ref, {})assert 'replay_epoch' in initial and 'last_sequence' in initial, 'resume omits replay watermark'await turn(1)- frames = [await asyncio.to_thread(peer.frames.get, True, 5) for peer in peers]+ frames = []+ for peer in peers:+ observed = []+ while not observed or observed[-1]['params']['type'] != 'message.complete':+ observed.append(await asyncio.to_thread(peer.frames.get, True, 5))+ frames.append(observed)assert frames[0] == frames[1]replay = (await since(initial['replay_epoch'], initial['last_sequence']))['result']assert not replay['snapshot_required']- assert replay['events'] == [frames[0]['params']]+ assert replay['events'] == [frame['params'] for frame in frames[0]]current = await b.resume(ref, {})- assert current['last_sequence'] == frames[0]['params']['seq']+ assert current['last_sequence'] == frames[0][-1]['params']['seq']assert len(authority.sessions['shared'].subscribers) == 2assert (await since('old-owner', 0))['result']['snapshot_required']assert (await since(current['replay_epoch'], current['last_sequence'] + 1))['result']['snapshot_required']@@ -96,8 +101,9 @@ async def test_replay_matches_subscription_watermark_or_requires_snapshot(tmp_parefreshed = await b.resume(ref, {})await turn(5)after = (await since(refreshed['replay_epoch'], refreshed['last_sequence']))['result']- assert not after['snapshot_required'] and len(after['events']) == 1- assert after['events'][0]['payload']['text'] == '5'+ assert not after['snapshot_required']+ assert after['events'][-1]['type'] == 'message.complete'+ assert after['events'][-1]['payload']['text'] == '5'before_race = await b.resume(ref, {})stamp = event_replay._stamp_eventdef evict_then_stamp(frame):diff --git a/tests/gateway/test_authority_stream.py b/tests/gateway/test_authority_stream.pynew file mode 100644index 00000000000..3750ed5383e--- /dev/null+++ b/tests/gateway/test_authority_stream.py@@ -0,0 +1,21 @@+"""Canonical execution stream through production API binding and real model SSE."""+import json+import os+from pathlib import Path+import subprocess+import sys+++def test_authority_stream_has_one_order_and_rejects_retired_callbacks(tmp_path):+ repo = Path(__file__).resolve().parents[2]+ home, state = tmp_path / 'home', tmp_path / 'state'+ home.mkdir()+ state.mkdir()+ env = {k: os.environ[k] for k in ('PATH', 'SYSTEMROOT', 'LANG', 'TZ') if k in os.environ}+ env.update(HOME=str(home), USERPROFILE=str(home), HERMES_HOME=str(state), PYTHONPATH=str(repo))+ result = subprocess.run([sys.executable, str(Path(__file__).parent / 'fixtures' / 'authority_stream_peer.py')],+ cwd=repo, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=100)+ assert result.returncode == 0, result.stdout + '\n' + result.stderr+ receipt = json.loads((state / 'receipt.json').read_text())+ print(json.dumps(receipt))+ assert receipt['real_terminal_effect'] and receipt['same_stamps'] and receipt['stale_callback_inert']