The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: canonical API SSE carries the turn's reasoning, status and commentary
Teknium94349601b2ef
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex b16b07f7f15..008fee15eb7 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -4157,6 +4157,8 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):ephemeral_system_prompt=ephemeral_system_prompt, session_id=session_id,stream_delta_callback=stream_delta_callback, tool_progress_callback=tool_progress_callback,tool_start_callback=tool_start_callback, tool_complete_callback=tool_complete_callback,+ interim_assistant_callback=interim_assistant_callback, reasoning_callback=reasoning_callback,+ status_callback=status_callback,agent_ref=agent_ref, active_run_id=active_run_id, gateway_session_key=gateway_session_key,requested_model=requested_model, requested_provider=requested_provider, model_options=model_options,route=route, session_model=session_model, requested_runtime=requested_runtime,diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 0b1840c63a9..1bf81195fb0 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -382,6 +382,12 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):agent.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_sync+ agent.reasoning_callback = None # per turn: a reused agent never keeps an earlier API turn's sink+ if self._approval_owner is not None:+ from gateway.session_api_turn import api_execution, wire_api_observers+ if api_execution.get() is not None:+ # The API request's SSE observes reasoning/status/commentary through its admission.+ wire_api_observers(agent, self._approval_owner, want_interim_messages)agent.notice_clear_callback = None # sends can't be retractedagent.event_callback = ctx._event_callback_syncagent.reasoning_config, agent.service_tier = reasoning_config, runner._service_tierdiff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.pyindex 1f391a6ea1a..66ee4c6d26e 100644--- a/gateway/session_api_turn.py+++ b/gateway/session_api_turn.py@@ -14,6 +14,9 @@ from hermes_state_runtime import RuntimeStoreError, admit_session_input, _epoch,api_execution: ContextVar[dict | None] = ContextVar('api_execution', default=None)_SETTINGS_PREFIX = 'gateway.api.settings.v1.'+# Request-owned sinks an API observer may register for its admission's execution.+_OBSERVER_KEYS = ('stream_delta_callback', 'tool_start_callback', 'tool_complete_callback',+ 'reasoning_callback', 'status_callback', 'interim_assistant_callback')_SETTING_KEYS = ('ephemeral_system_prompt', 'requested_model', 'requested_provider','model_options', 'route', 'session_model', 'confirmed_runtime_lock','requested_runtime', 'route_source', 'room_dispatch', 'room_execution_policy',@@ -249,8 +252,7 @@ async def observe_api_turn(admitted, **kwargs):observers = getattr(authority, 'api_observers', None)if observers is None:observers = authority.api_observers = {}- observer = {key: kwargs[key] for key in ('stream_delta_callback', 'tool_start_callback', 'tool_complete_callback')- if kwargs.get(key) is not None}+ observer = {key: kwargs[key] for key in _OBSERVER_KEYS if kwargs.get(key) is not None}registered = observers.setdefault(row['admission_id'], [])registered.append(observer)try:@@ -325,7 +327,7 @@ def _api_observers(authority, session_id):return tuple(getattr(authority, 'api_observers', {}).get(admission_id, ()))-def _notify_observers(authority, session_id, key, *args):+def _notify_observers(authority, session_id, key, *args, **kwargs):"""Observer callbacks are request-owned sinks; one that raises (closed socket, torn-downloop) must not abort canonical execution or starve the other observers. Returns whetherany observer accepted the event."""@@ -335,13 +337,45 @@ def _notify_observers(authority, session_id, key, *args):callback = observer.get(key)if callback:try:- callback(*args)+ callback(*args, **kwargs)accepted = Trueexcept Exception:logging.getLogger(__name__).warning('API observer %s failed for %s', key, session_id, exc_info=True)return accepted+def wire_api_observers(agent, owner, want_interim):+ """Hand this admission's API observers (Chat/Responses SSE, runs) the agent's reasoning,+ status and commentary callbacks, the ones the direct API path gave the agent itself. Each+ event is fenced to the exact running claim, so a settled worker's late callback is inert;+ the turn's own status/commentary sinks keep running after the observers."""+ authority, session_id, generation = owner++ def publish(key, *args, **kwargs):+ with authority.sessions[session_id].event_stream.lock:+ try:+ authority.check_approval_generation(session_id, generation)+ except RuntimeStoreError:+ return False+ return _notify_observers(authority, session_id, key, *args, **kwargs)++ status, interim = agent.status_callback, agent.interim_assistant_callback++ def status_callback(kind, message=None):+ publish('status_callback', kind, message)+ if status is not None:+ status(kind, message)++ def interim_assistant_callback(text, *, already_streamed=False):+ publish('interim_assistant_callback', text, already_streamed=already_streamed)+ if interim is not None:+ interim(text, already_streamed=already_streamed)+ agent.reasoning_callback = lambda text: publish('reasoning_callback', text)+ agent.status_callback = status_callback+ if want_interim:+ agent.interim_assistant_callback = interim_assistant_callback++def publish_api_event(authority, session_id, event_type, payload):if event_type == 'message.delta':return _notify_observers(authority, session_id, 'stream_delta_callback', payload['text'])diff --git a/tests/gateway/test_api_canonical_projection.py b/tests/gateway/test_api_canonical_projection.pyindex 5acec10eb74..91efe677a01 100644--- a/tests/gateway/test_api_canonical_projection.py+++ b/tests/gateway/test_api_canonical_projection.py@@ -277,3 +277,53 @@ def test_run_status_reports_waiting_for_approval_while_a_prompt_is_pending(api,projected = run_projection(api, 'run_wait')assert [p['prompt_id'] for p in projected['pending_controls']] == ['approve-me']assert projected['status'] == 'waiting_for_approval'++[email protected]('path,body,marker', [+ ('/v1/chat/completions', {'messages': [{'role': 'user', 'content': 'hi'}], 'stream': True},+ '"reasoning_content": "THINKING"'),+ ('/v1/responses', {'input': 'hi', 'stream': True}, 'response.reasoning_summary_text.delta'),+])+async def test_canonical_sse_projects_the_turn_reasoning(api, owner, path, body, marker):+ """Chat and Responses SSE under the authority get the agent's reasoning, like the direct+ path: the real per-turn wiring hands the admission's observers the reasoning callback."""+ from gateway.run_turn_runner import TurnRunner+ from gateway.session_api_turn import api_execution++ async def handle(event):+ from gateway.session_results import execution_result+ sid = event.source.chat_id+ turn = _turn_runner(owner, SimpleNamespace(session_id=sid))+ agent = SimpleNamespace(reasoning_callback=None) # AIAgent's own default+ holder = SimpleNamespace(+ _ctx=SimpleNamespace(+ progress_callback=None, native_tool_start_callback=None, voice_ack_callback=None,+ _voice_ack_guild=[None], voice_turn=False, _native_slack_task_cards=False,+ native_tool_complete_callback=None, _step_callback_sync=None,+ _hooks_ref=SimpleNamespace(loaded_hooks=[]), _status_callback_sync=None, _event_callback_sync=None,+ _status_adapter=None, session_key='', user_config={}, source=event.source,+ mute_notification_reply=False, _thinking_enabled=False, agent_holder=[None], tools_holder=[None],+ process_task_id=None, process_baseline=None, run_generation=0),+ _approval_owner=turn._approval_owner, combined_tool_start_callback=None,+ combined_tool_complete_callback=None,+ _runner=SimpleNamespace(_service_tier=None, _consume_pending_turn_sidecar_notes=lambda key: []),+ _make_bg_review_callbacks=lambda: (lambda message: None, lambda: None),+ _merge_turn_request_overrides=TurnRunner._merge_turn_request_overrides,+ _clarify_callback_sync=None, _notice_callback_sync=None,+ _attach_session_title_callback=lambda agent, ctx: None)+ assert api_execution.get() is not None+ TurnRunner._wire_turn_agent_callbacks(holder, agent, {}, None, None, None, False)+ if agent.reasoning_callback: # AIAgent._fire_reasoning_delta calls it only when wired+ agent.reasoning_callback('THINKING')+ execution_result.get()['result'] = {'final_response': 'ANSWER', 'messages': []}+ return 'ANSWER'+ owner.runner._handle_message = handle+ owner.adopt_agent = lambda *args: None+ app = web.Application()+ app.router.add_post(path, getattr(api, '_handle_chat_completions' if 'chat' in path else '_handle_responses'))+ async with TestClient(TestServer(app)) as client:+ response = await client.post(path, json=body)+ text = await response.text()+ assert response.status == 200, text+ assert marker in text and 'THINKING' in text, text