Skip to content

The agent that grows with you

feat(gateway): a classic CLI turn's receipt is the run_conversation-shaped result

Teknium89944edd2710
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index 13c13f73890..dbc55cc382f 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -1096,7 +1096,10 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
from gateway.session_results import execution_result
captured = execution_result.get()
if captured is not None:
- captured['result'] = result
+ cli_fields = self.__dict__.pop("_cli_result_fields", None)
+ # A classic CLI viewer reads the run_conversation-shaped dict from the receipt; the
+ # delivered reply (message.complete text) keeps the gateway's own copy.
+ captured['result'] = {**result, **cli_fields} if cli_fields else result
return result
def _run_sync_scoped(self):
@@ -1228,7 +1231,18 @@ 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)
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 99c4a6cf0ce..1f1ad1c0f70 100644
--- a/gateway/session_cli_turn.py
+++ b/gateway/session_cli_turn.py
@@ -91,3 +91,45 @@ def one_turn_runtime(override, model, runtime_kwargs, config):
request_overrides=dict(result.request_overrides or {}),
capabilities=dict(result.runtime_capabilities or {}))
return result.new_model, runtime
+
+
+# run_conversation keys main's HermesCLI reads that the gateway's own projection does not carry
+# (CALLMAP §3.3 step 4): the transform-preview original, the billing descriptor and the turn's
+# last reasoning / preview flags.
+_RESULT_PASSTHROUGH = ('pre_transform_response', 'billing_block', 'last_reasoning', 'response_previewed',
+ 'response_transformed', 'turn_exit_reason')
+
+
+def classic_cli_turn(turn):
+ """A local-viewer turn on a classic-CLI surface session (``cli`` / ``oneshot`` / ``tool``): the
+ viewer is main's HermesCLI, which reads the run_conversation-shaped result itself."""
+ from gateway.run_turn_progress import local_viewer_turn
+ if not local_viewer_turn(turn):
+ return False
+ from gateway.session_policy import policy_for_source
+ try:
+ policy = policy_for_source(turn._runner, turn._ctx.source)
+ except Exception:
+ return False
+ return policy is not None and policy.platform == 'cli'
+
+
+def take_cli_result_fields(result, *, aux_before=None, session_db=None, session_id=None):
+ """The receipt-only fields of a classic CLI turn, taken from the agent's raw result.
+
+ ``pending_steer`` is REMOVED from ``result``: main's CLI queues a leftover /steer as its own
+ next turn (``delivering leftover steer``), so the gateway must not also run it as a follow-up
+ inside this admission. ``final_response`` is the agent's raw text: main renders its own
+ ``chat_error_copy`` for an empty failed turn instead of the gateway's chat copy."""
+ if not isinstance(result, dict):
+ return {}
+ fields = {key: result.get(key) for key in _RESULT_PASSTHROUGH if key in result}
+ fields['final_response'] = result.get('final_response') or ''
+ steer = result.pop('pending_steer', None)
+ fields['pending_steer'] = steer or None
+ if aux_before is not None:
+ from hermes_cli.oneshot import _attach_auxiliary_usage
+ holder = {'session_id': result.get('session_id') or session_id}
+ _attach_auxiliary_usage(holder, session_db, aux_before, fallback_session_id=session_id)
+ fields['auxiliary_usage'] = holder.get('auxiliary_usage') or {}
+ return fields
diff --git a/tests/gateway/test_local_viewer_events_submit.py b/tests/gateway/test_local_viewer_events_submit.py
index 766a4f561f1..ceaf9552212 100644
--- a/tests/gateway/test_local_viewer_events_submit.py
+++ b/tests/gateway/test_local_viewer_events_submit.py
@@ -159,3 +159,59 @@ def test_an_unresolvable_one_turn_model_fails_the_turn_without_running_it():
result, agent = _run_turn(_gateway_runner())
assert result["failed"] is True and "Unknown model 'nope'" in result["final_response"]
assert agent is None and _RecordingAgent.built == []
+
+
+class _SteeredAgent(_RecordingAgent):
+ def run_conversation(self, message, **kwargs):
+ self.calls.append((message, kwargs))
+ return {"final_response": "", "messages": [], "failed": True, "error": "HTTP 402",
+ "failure_reason": "billing", "pending_steer": "also check the logs",
+ "pre_transform_response": "raw draft", "response_transformed": True,
+ "billing_block": {"provider": "openrouter", "url": "https://openrouter.ai/credits"},
+ "last_reasoning": "thought", "turn_exit_reason": "billing"}
+
+
[email protected]("classic", [True, False])
+def test_a_classic_cli_receipt_carries_the_run_conversation_keys(classic):
+ from gateway.run_turn_runner import TurnRunner
+ from gateway.session import SessionSource
+ from gateway.session_results import execution_result
+ from gateway.turn_context import TurnContext
+ ctx = TurnContext(
+ source=SessionSource(platform=Platform.LOCAL, chat_id="c", user_id="u"),
+ message="hi", history=[], session_id="sid", session_key="key", user_config={},
+ AIAgent=_SteeredAgent, resolve_display_setting=lambda *_a: False,
+ _run_still_current=lambda: True, _hooks_ref=SimpleNamespace(loaded_hooks=False))
+ captured = {}
+ token = execution_result.set(captured)
+ try:
+ with patch("gateway.session_cli_turn.classic_cli_turn", return_value=classic):
+ delivered = TurnRunner(_gateway_runner(), ctx).run_sync()
+ finally:
+ execution_result.reset(token)
+ stored = captured["result"]
+ if classic:
+ # main's CLI renders its own chat_error_copy for an empty failed turn and queues the
+ # leftover /steer itself, so the gateway must not also drain it as a follow-up.
+ assert stored["final_response"] == ""
+ assert stored["pending_steer"] == "also check the logs"
+ assert stored["pre_transform_response"] == "raw draft" and stored["response_transformed"] is True
+ assert stored["billing_block"]["provider"] == "openrouter"
+ assert (stored["last_reasoning"], stored["turn_exit_reason"]) == ("thought", "billing")
+ assert "pending_steer" not in ctx.result_holder[0]
+ else:
+ assert "pending_steer" not in stored and "billing_block" not in stored
+ assert ctx.result_holder[0]["pending_steer"] == "also check the logs"
+ # The delivered reply (message.complete text) keeps the gateway's own copy either way.
+ assert delivered["final_response"] and stored["failed"] is True
+
+
+def test_only_a_classic_cli_surface_session_is_a_classic_cli_turn():
+ from gateway.session_cli_turn import classic_cli_turn
+ turn = SimpleNamespace(_approval_owner=("authority", "s", 1), _runner=object(),
+ _ctx=SimpleNamespace(source=SimpleNamespace(platform=Platform.LOCAL)))
+ for platform, expected in (("cli", True), ("tui", False), ("desktop", False)):
+ with patch("gateway.session_policy.policy_for_source", return_value=SimpleNamespace(platform=platform)):
+ assert classic_cli_turn(turn) is expected
+ turn._ctx.source.platform = Platform.TELEGRAM
+ assert classic_cli_turn(turn) is False