The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): publish subagent events to local viewers and retain fallback-evicted rosters
yoniebansc6ac2564ba2e
diff --git a/gateway/local_viewer_events.py b/gateway/local_viewer_events.pyindex 234ae9a3d66..92b8c23fa3e 100644--- a/gateway/local_viewer_events.py+++ b/gateway/local_viewer_events.py@@ -62,10 +62,32 @@ def show_reasoning(turn) -> bool:return getattr(live, "show_reasoning", None) is True+def _publish_subagent(turn, event_type, payload) -> None:+ owner = getattr(turn, "_approval_owner", None)+ if owner is not None:+ authority, session_id, generation = owner+ executing = getattr(authority, "executing", None)+ if isinstance(executing, dict) and executing.get(session_id) != generation:+ # A background delegate_task outlives the spawning turn's running claim.+ live = authority.sessions.get(session_id)+ if live is not None and hasattr(live, "event_stream"):+ live.event_stream.publish(session_id, payload, event_type=event_type)+ return+ turn._publish_execution(event_type, payload)++def publish_progress(turn, event_type, name, preview, kwargs) -> None:- """``reasoning.available`` and the MoA facade events from the agent's progress callback. A- classic CLI renders MoA references whatever its reasoning display (main's ``_on_tool_progress``);- other viewers get them, like the TUI gateway's own emitters, only with reasoning shown."""+ """``subagent.*``, ``reasoning.available`` and the MoA facade events from the agent's progress+ callback. A classic CLI renders MoA references whatever its reasoning display (main's+ ``_on_tool_progress``); other viewers get them, like the TUI gateway's own emitters, only with+ reasoning shown."""+ if isinstance(event_type, str) and event_type.startswith("subagent."):+ if event_type == "subagent.text":+ return+ from tui_gateway.tool_progress import _subagent_payload+ _publish_subagent(turn, event_type, _subagent_payload(+ event_type, name, preview, kwargs, show_reasoning=show_reasoning(turn)))+ returnif event_type != "reasoning.available" and event_type not in _MOA_KEYS:returnfrom gateway.session_cli_turn import classic_cli_turndiff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex 95af473302a..56cae47d8f5 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -1665,23 +1665,22 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway"""Evict the cached agent when a fallback model activated on a SUCCESSFUL run (so /model showsthe active model and the next message retries the primary). Skip failed runs: evictingwould loop bad model → fallback → evict → recreate."""- session_key = turn_ctx.session_key- _agent = turn_ctx.agent_holder[0]- _result_for_fb = turn_ctx.result_holder[0]+ session_key, _agent, _result_for_fb = turn_ctx.session_key, turn_ctx.agent_holder[0], turn_ctx.result_holder[0]if _agent is None or not hasattr(_agent, 'model') or (_result_for_fb and _result_for_fb.get("failed")):return# A provider fallback is drift even when it serves the configured model name on another endpoint.- if getattr(_agent, "_provider_fallback_active", False) is True:- self._evict_cached_agent(session_key)- return- # A LOCAL session runs its frozen launch policy's model, not the gateway's configured one.- from gateway.session_authorities import active_authority- from gateway.session_policy import policy_for_source- policy = policy_for_source(self, turn_ctx.source)- _cfg_model = self._fallback_baseline_model(- session_key, turn_ctx.source, _agent, policy_model=policy.current_model(active_authority(self)) if policy and policy.model else None)- if _agent.model != _cfg_model and not self._is_intentional_model_switch(session_key, _agent, _cfg_model):- self._evict_cached_agent(session_key)+ if getattr(_agent, "_provider_fallback_active", False) is not True:+ # A LOCAL session runs its frozen launch policy's model, not the gateway's configured one.+ from gateway.session_authorities import active_authority+ from gateway.session_policy import policy_for_source+ policy = policy_for_source(self, turn_ctx.source)+ _cfg_model = self._fallback_baseline_model(+ session_key, turn_ctx.source, _agent, policy_model=policy.current_model(active_authority(self)) if policy and policy.model else None)+ if _agent.model == _cfg_model or self._is_intentional_model_switch(session_key, _agent, _cfg_model):+ return+ with suppress(Exception):+ _agent._evicted_on_fallback = True+ self._evict_cached_agent(session_key)async def _run_agent_finalize_streaming_tts(self, turn_ctx: TurnContext, adapter: Any) -> None:"""Finalize the streaming-TTS consumer on the outer event-loop thread (covers early returnsdiff --git a/gateway/run_turn_progress.py b/gateway/run_turn_progress.pyindex b103b86864b..5f93d5e622e 100644--- a/gateway/run_turn_progress.py+++ b/gateway/run_turn_progress.py@@ -138,14 +138,14 @@ class GatewayTurnProgressMixin:def progress_callback(self, event_type: str, tool_name: str | None = None, preview: str | None = None, args: dict | None = None, **kwargs):"""Callback invoked by agent on tool lifecycle events."""ctx = self._ctx+ if local_viewer_turn(self):+ from gateway import local_viewer_events+ local_viewer_events.publish_progress(self, event_type, tool_name, preview, kwargs)# Failed subagent → one clean user-facing notice, handled FIRST, before every progress-queue# gate: platforms with tool_progress off must still hear about a dead delegation.if event_type == "subagent.complete":self._progress_subagent_notice(preview, kwargs)return- if local_viewer_turn(self):- from gateway import local_viewer_events- local_viewer_events.publish_progress(self, event_type, tool_name, preview, kwargs)self._progress_live_status(event_type, tool_name, args)# "log" mode: append tool.started lines to the log queue, silent in chat. Handled before# the progress_queue guard because log mode runs without a chat progress queue.diff --git a/gateway/session_ancillary.py b/gateway/session_ancillary.pyindex 168516502c0..33cb3e9a8d5 100644--- a/gateway/session_ancillary.py+++ b/gateway/session_ancillary.py@@ -205,7 +205,7 @@ async def read(connection, ref, params, *, kind):_require_current_route(authority, ref)if kind == 'control':return {'control': control_snapshot(authority, ref)}- agent, records = _owner_objects(authority, ref)+ agent, records = _owner_objects(authority, ref, include_fallback_evicted=kind == 'subagents')if kind == 'subagents':return {'subagents': [{key: record.get(key) for key in _SUBAGENT_FIELDS}for record in records], 'delegations': []}@@ -312,7 +312,7 @@ def _require_current_route(authority, ref):raise RuntimeStoreError('stale_generation')-def _owner_objects(authority, ref):+def _owner_objects(authority, ref, *, include_fallback_evicted=False):"""``(agent, subagent records)`` of this in-process session. Process-local registries cannotdescribe (or stop) another interpreter's live objects: a managed worker is refused rather thananswered with an empty success."""@@ -320,7 +320,8 @@ def _owner_objects(authority, ref):if managed_policy(authority, ref) is not None:raise RuntimeStoreError('unsupported_projection')agent = authority.agent(ref)- return agent, subagent_records(agent)+ session_id = physical_target(authority, ref) if include_fallback_evicted else None+ return agent, subagent_records(agent, session_id=session_id, include_fallback_evicted=include_fallback_evicted)def physical_target(authority, ref):@@ -362,15 +363,32 @@ def control_snapshot(authority, ref):'updated_at': _snapshot_updated_at(*states)}-def subagent_records(parent):+def _has_fallback_evicted_ancestor(agent, target_sid, registry):+ if not target_sid:+ return False+ current = agent+ for _ in range(getattr(registry, '_MAX_ANCESTOR_HOPS', 16)):+ ref = getattr(current, '_delegate_parent_ref', None) if current is not None else None+ current = ref() if callable(ref) else None+ if current is None:+ return False+ if getattr(current, '_evicted_on_fallback', False) is True and getattr(current, 'session_id', None) == target_sid:+ return True+ return False+++def subagent_records(parent, session_id=None, *, include_fallback_evicted=True):registry = sys.modules.get('tools.delegate_tool_registry')- if parent is None or registry is None:+ target_sid = (session_id or getattr(parent, 'session_id', None)) if include_fallback_evicted else None+ if registry is None or (parent is None and not target_sid):return []with registry._active_subagents_lock:- # Deliberately no durable-ID fallback: equal IDs cannot transfer a live- # old parent's transcript to a replacement execution object.+ # Deliberately no unconditional durable-ID fallback: equal IDs cannot transfer a live+ # old parent's transcript or control to a replacement execution object. Only a parent+ # evicted by this session's own fallback keeps its children visible in the read-only roster.return [dict(record) for record in registry._active_subagents.values()- if registry._is_descendant_of(record.get('agent'), parent)]+ if (parent is not None and registry._is_descendant_of(record.get('agent'), parent))+ or _has_fallback_evicted_ancestor(record.get('agent'), target_sid, registry)]def subagent_tail(records, subagent_id):diff --git a/tests/gateway/test_local_viewer_events_turn.py b/tests/gateway/test_local_viewer_events_turn.pyindex 5a59ca2128b..6b6aabd9ff0 100644--- a/tests/gateway/test_local_viewer_events_turn.py+++ b/tests/gateway/test_local_viewer_events_turn.py@@ -324,15 +324,21 @@ def test_completion_payload_forwards_billing_failure_and_response_flags():finally:execution_result.reset(token)- captured['result'].update(warning='History changed during this turn', response_previewed=True)+ from agent.billing_links import build_billing_block+ assert captured['result']['billing_block'] == {'provider': 'openrouter', 'url': 'https://openrouter.ai/credits'}+ billing = build_billing_block(+ provider='openrouter', base_url='https://openrouter.ai/api/v1', model='gpt-x', message='Out of credits'+ ).to_dict()+ captured['result'].update(billing_block=billing, warning='History changed during this turn', response_previewed=True)complete = completion_payload({'admission_id': 'a1', 'request_id': 'r1'}, {'outcome': 'failed'}, delivered['final_response'], captured)- assert complete['billing'] == {'provider': 'openrouter', 'url': 'https://openrouter.ai/credits'}+ assert complete['billing'] == billingassert complete['failure_reason'] == 'billing'assert complete['warning'] == 'History changed during this turn'assert complete['response_previewed'] is Trueassert complete['response_transformed'] is True- EVENTS['message.complete'].payload.model_validate(complete)+ EVENTS['message.complete'].payload.model_validate(+ {k: v for k, v in complete.items() if k not in ('content', 'admission_id', 'outcome')})def test_progress_publishes_subagent_lifecycle_events_for_local_viewers():diff --git a/tools/delegate_tool_progress.py b/tools/delegate_tool_progress.pyindex 7e171a1c546..d731709106d 100644--- a/tools/delegate_tool_progress.py+++ b/tools/delegate_tool_progress.py@@ -120,8 +120,9 @@ _LEGACY_EVENT_MAP: dict[str, DelegateEvent] = {# Event → _ChildProgressRelay method name. Lifecycle strings are emitted by the orchestrator itself (not# DelegateEvent). Any other DelegateEvent (TASK_TOOL_STARTED and the reserved TASK_* values) takes the tool-started# path; None means "recognised but ignored".-_LIFECYCLE_EVENTS = frozenset({"subagent.start", "subagent.complete", "subagent.text"})+_LIFECYCLE_EVENTS = frozenset({"subagent.spawn_requested", "subagent.start", "subagent.complete", "subagent.text"})_EVENT_HANDLERS: dict[Any, Optional[str]] = {+ "subagent.spawn_requested": "_on_spawn_requested","subagent.start": "_on_start","subagent.complete": "_on_complete","subagent.text": "_on_text",@@ -346,6 +347,9 @@ class _ChildProgressRelay:self.batch.clear()# ── Lifecycle events emitted by the orchestrator itself ──+ def _on_spawn_requested(self, tool_name, preview, args, kwargs):+ self._relay("subagent.spawn_requested", preview=preview or self.goal_label or "", **kwargs)+def _on_start(self, tool_name, preview, args, kwargs):if self.goal_label:self._tree_line(f"🔀 {_short(self.goal_label, 55)}")diff --git a/tui_gateway/tool_progress.py b/tui_gateway/tool_progress.pyindex b2b03399011..6396e162c53 100644--- a/tui_gateway/tool_progress.py+++ b/tui_gateway/tool_progress.py@@ -450,7 +450,7 @@ _SUBAGENT_FIELDS = ()-def _progress_subagent(sid: str, name: str, preview, kw, event_type):+def _subagent_payload(event_type: str, name: str | None, preview, kw: dict, *, show_reasoning: bool) -> dict:payload = {"goal": str(kw.get("goal") or ""), "task_count": int(kw.get("task_count") or 1), "task_index": int(kw.get("task_index") or 0)}source = {**kw, "tool_name": name, "text": preview}for key, present, coerce in _SUBAGENT_FIELDS:@@ -460,11 +460,16 @@ def _progress_subagent(sid: str, name: str, preview, kw, event_type):payload[key] = val# subagent.thinking's text is the child's chain of thought: with reasoning hidden the# delegate card must not leak it, same policy as the child-mirror's reasoning.delta.- if event_type == "subagent.thinking" and not _session_show_reasoning(sid):+ if event_type == "subagent.thinking" and not show_reasoning:payload.pop("text", None)if preview and event_type == "subagent.tool":payload["tool_preview"] = str(preview)payload["text"] = str(preview)+ return payload+++def _progress_subagent(sid: str, name: str, preview, kw, event_type):+ payload = _subagent_payload(event_type, name, preview, kw, show_reasoning=bool(_session_show_reasoning(sid)))# subagent.text is the child's per-token reply, relayed solely to feed a watch window's live mirror# (keyed off the child sid); on the parent it's hundreds of ignored frames, so skip it.if event_type != "subagent.text":