Skip to content

The agent that grows with you

refactor(gateway): the classic CLI turn seams live in session_cli_turn; health clean

Tekniumbfa156802dde
diff --git a/gateway/local_viewer_events.py b/gateway/local_viewer_events.py
index b237b24b20c..1682c3bd6a1 100644
--- a/gateway/local_viewer_events.py
+++ b/gateway/local_viewer_events.py
@@ -12,8 +12,11 @@ previous values; ``restore`` puts them back when the turn's ``run_conversation``
"""
from __future__ import annotations
+import logging
import time
+logger = logging.getLogger(__name__)
+
# Attributes ``wire`` may overwrite on the cached agent for one local-viewer turn.
_TURN_ATTRS = ("tool_gen_callback", "_print_fn", "thinking_callback", "reaction_callback", "reasoning_callback")
# MoA facade progress (agent/moa_loop._RELAY_EVENTS) -> the payload tui_gateway/tool_progress emits.
@@ -93,7 +96,8 @@ def note_tool_start(turn, call_id, tool_name=None, args=None) -> None:
from agent.display import capture_local_edit_snapshot
snapshot = capture_local_edit_snapshot(tool_name, args if isinstance(args, dict) else {},
task_id=turn._ctx.session_id)
- except Exception:
+ except Exception: # health: allow BLE001 -- display-only preview; a failed snapshot only drops the diff
+ logger.debug("Edit snapshot capture failed for %s", tool_name, exc_info=True)
snapshot = None
if snapshot is not None:
turn.__dict__.setdefault("_local_edit_snapshots", {})[key] = snapshot
@@ -113,7 +117,8 @@ def complete_fields(turn, call_id, tool_name=None, args=None, result=None) -> di
from agent.display import render_edit_diff_with_delta
render_edit_diff_with_delta(tool_name, result, function_args=args if isinstance(args, dict) else {},
snapshot=snapshot, print_fn=rendered.append)
- except Exception:
+ except Exception: # health: allow BLE001 -- display-only preview, as main's CLI _on_tool_complete
+ logger.debug("Edit diff preview failed for %s", tool_name, exc_info=True)
rendered = []
fields["inline_diff"] = "\n".join(rendered) if rendered else None
todo = todo_state(tool_name, result)
@@ -143,13 +148,11 @@ def prompt_timeout_s(turn, kind) -> int | None:
from gateway.run_turn_progress import local_viewer_turn
if not local_viewer_turn(turn):
return None
- try:
- if kind == "approval":
- from tools.approval_context import _get_approval_timeout
- seconds = int(_get_approval_timeout())
- else:
- from tools.clarify_gateway import get_clarify_timeout
- seconds = int(get_clarify_timeout())
- except Exception:
- return None
+ # Both readers fall back to their defaults themselves; they never raise.
+ if kind == "approval":
+ from tools.approval_context import _get_approval_timeout
+ seconds = int(_get_approval_timeout())
+ else:
+ from tools.clarify_gateway import get_clarify_timeout
+ seconds = int(get_clarify_timeout())
return seconds if seconds > 0 else None
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index e587b7ac65a..d6dfc9abaeb 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -1162,14 +1162,9 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
# model is the one this agent must send (#112600).
from gateway.session_authorities import active_authority
model = policy.current_model(active_authority(runner))
- from gateway.session_cli_turn import cli_turn, one_turn_runtime
- override = cli_turn(ctx.inbound_message_id).get('model_override')
- if override:
- # The classic CLI's `/model --once` / `/moa`: this admission only, nothing persisted.
- from gateway.session_authorities import active_authority
- model, runtime_kwargs = one_turn_runtime(
- override, model, runtime_kwargs,
- policy.config(active_authority(runner)) if policy else ctx.user_config)
+ # The classic CLI's `/model --once` / `/moa`: this admission only, nothing persisted.
+ from gateway.session_cli_turn import one_turn_route
+ model, runtime_kwargs = one_turn_route(self, policy, model, runtime_kwargs)
logger.debug(
"run_agent resolved: model=%s provider=%s session=%s",
model, runtime_kwargs.get("provider"), ctx.session_key or "",
@@ -1240,18 +1235,9 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
agent_history, observed_group_context, history_media_paths = self._load_turn_history(agent, reused_cached_agent)
persist_msg, persist_ts = self._prepare_turn_message(agent_history)
compressions = getattr(getattr(agent, "context_compressor", None), "compression_count", None)
- aux_before = cli_db = None
- from gateway.session_cli_turn import classic_cli_turn, take_cli_result_fields
- cli_turn_result = classic_cli_turn(self)
- if cli_turn_result and _finite_viewer_turn():
- # `chat -q --usage-file` / stream-json: this turn's auxiliary spend, as oneshot.py read it.
- from hermes_cli.oneshot import _auxiliary_usage
- cli_db = getattr(runner._session_db, "_db", runner._session_db)
- aux_before = _auxiliary_usage(cli_db, ctx.session_id)
- result = self._run_conversation_with_approval(agent, agent_history, observed_group_context, persist_msg, persist_ts)
- if cli_turn_result:
- self._cli_result_fields = take_cli_result_fields(
- result, aux_before=aux_before, session_db=cli_db, session_id=ctx.session_id)
+ from gateway.session_cli_turn import run_classic_cli_turn
+ result = run_classic_cli_turn(self, lambda: self._run_conversation_with_approval(
+ agent, agent_history, observed_group_context, persist_msg, persist_ts))
finally:
if local_sinks is not None:
from gateway import local_viewer_events
diff --git a/gateway/session_cli_turn.py b/gateway/session_cli_turn.py
index 1f1ad1c0f70..d6baaf69710 100644
--- a/gateway/session_cli_turn.py
+++ b/gateway/session_cli_turn.py
@@ -109,7 +109,7 @@ def classic_cli_turn(turn):
from gateway.session_policy import policy_for_source
try:
policy = policy_for_source(turn._runner, turn._ctx.source)
- except Exception:
+ except RuntimeStoreError: # a route whose frozen policy is not restored: not a CLI viewer turn
return False
return policy is not None and policy.platform == 'cli'
@@ -133,3 +133,32 @@ def take_cli_result_fields(result, *, aux_before=None, session_db=None, session_
_attach_auxiliary_usage(holder, session_db, aux_before, fallback_session_id=session_id)
fields['auxiliary_usage'] = holder.get('auxiliary_usage') or {}
return fields
+
+
+def one_turn_route(turn, policy, model, runtime_kwargs):
+ """The executing admission's ``model_override`` applied to the resolved route (unchanged without one)."""
+ override = cli_turn(turn._ctx.inbound_message_id).get('model_override')
+ if not override:
+ return model, runtime_kwargs
+ from gateway.session_authorities import active_authority
+ config = policy.config(active_authority(turn._runner)) if policy else turn._ctx.user_config
+ return one_turn_runtime(override, model, runtime_kwargs, config)
+
+
+def run_classic_cli_turn(turn, run):
+ """``run()`` (the turn's run_conversation) for any turn; on a classic CLI turn the receipt-only
+ fields are taken from its raw result and kept on ``turn`` for the committed receipt."""
+ if not classic_cli_turn(turn):
+ return run()
+ from gateway.session_finite import finite_turn_required
+ aux_before = cli_db = None
+ if finite_turn_required() is True:
+ # `chat -q --usage-file` / stream-json: this turn's auxiliary spend, as oneshot.py read it.
+ from hermes_cli.oneshot import _auxiliary_usage
+ runner_db = turn._runner._session_db
+ cli_db = getattr(runner_db, "_db", runner_db)
+ aux_before = _auxiliary_usage(cli_db, turn._ctx.session_id)
+ result = run()
+ turn._cli_result_fields = take_cli_result_fields(
+ result, aux_before=aux_before, session_db=cli_db, session_id=turn._ctx.session_id)
+ return result