The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway): an admitted CLI turn runs its api_text, one-turn model and author
Teknium01080bae83ab
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 6aff1238055..13c13f73890 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -791,6 +791,14 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):)ctx = self._ctxpersist_override: Optional[Any] = ctx.persist_user_message+ from gateway.session_cli_turn import cli_turn+ api_text = cli_turn(ctx.inbound_message_id).get('api_text')+ if api_text is not None:+ # The classic CLI's model-facing message (voice prefix, its own model-switch and+ # skills-reload notes); the admitted text stays the persisted user row.+ clean_text = persist_override if persist_override is not None else ctx.message+ persist_override = clean_text+ ctx.message = api_textself._prepend_pending_note("_pending_model_notes")# Auto-continue: history ending with a tool result means the previous turn was cut off# (restart, crash, SIGTERM). Session-level resume_pending (drain-timeout shutdown) uses@@ -825,6 +833,8 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):+ ctx.message)self._prepend_pending_note("_pending_skills_reload_notes")+ if api_text is not None:+ persist_override = clean_text # recovery wording is API-only too, never the stored row# Safety net: a startup auto-resume event carries empty text; if the resume_pending branch# did not fire (freshness signals disagreed, marker cleared) we must NOT hand the model a blank# user turn. Restricted to resume_pending sessions so caption-less image turns are untouched.@@ -1140,6 +1150,14 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):# model is the one this agent must send (#112600).from gateway.session_authorities import active_authoritymodel = 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)logger.debug("run_agent resolved: model=%s provider=%s session=%s",model, runtime_kwargs.get("provider"), ctx.session_key or "",diff --git a/gateway/session_cli_turn.py b/gateway/session_cli_turn.pyindex 62c86874ae3..99c4a6cf0ce 100644--- a/gateway/session_cli_turn.py+++ b/gateway/session_cli_turn.py@@ -14,7 +14,7 @@ from hermes_state_runtime import RuntimeStoreError_SUBMIT_FIELDS = ('turn_author', 'api_text', 'model_override')_API_TEXT_LIMIT = 1_000_000-_cli_turn: ContextVar[dict | None] = ContextVar('cli_turn', default=None)+_cli_turn: ContextVar[tuple | None] = ContextVar('cli_turn', default=None)def submit_cli_turn_fields(params):@@ -49,14 +49,45 @@ def admit_cli_turn(params):@contextmanager-def cli_turn_scope(committed):- token = _cli_turn.set(committed or None)+def cli_turn_scope(admission_id, committed):+ token = _cli_turn.set((admission_id, committed) if committed else None)try:yieldfinally:_cli_turn.reset(token)-def cli_turn():- """The executing admission's committed CLI turn fields (``{}`` outside one)."""- return _cli_turn.get() or {}+def cli_turn(message_id):+ """The committed CLI turn fields of the admission whose event id is ``message_id``; ``{}`` for+ any other turn, so a follow-up drained on the same task never inherits them."""+ bound = _cli_turn.get()+ if bound is None or message_id is None or str(message_id) != bound[0]:+ return {}+ return bound[1]+++def one_turn_runtime(override, model, runtime_kwargs, config):+ """``(model, runtime_kwargs)`` of a committed ``model_override`` for this one turn, resolved by the+ same ``switch_model`` pipeline ``/model`` uses against the session's current route. Nothing is+ written: the session's route, policy and cached agent are untouched, so the next turn runs its own+ route again (main's ``/model --once`` restore). Raises ``RuntimeError`` with the switch's own+ sentence when the target cannot be resolved; the caller fails the turn with it."""+ from hermes_cli.config import get_compatible_custom_providers+ from hermes_cli.model_switch import switch_model+ result = switch_model(+ raw_input=override['model'], current_provider=runtime_kwargs.get('provider') or '',+ current_model=model or '', current_base_url=runtime_kwargs.get('base_url') or '',+ current_api_key=runtime_kwargs.get('api_key') or '', is_global=False,+ explicit_provider=override.get('provider', ''), user_providers=(config or {}).get('providers'),+ custom_providers=get_compatible_custom_providers(config or {}))+ if not result.success:+ raise RuntimeError(result.error_message or f"model {override['model']!r} could not be resolved")+ runtime = dict(runtime_kwargs)+ if result.target_provider != runtime_kwargs.get('provider'):+ # The previous provider's pool and ACP command belong to that provider only.+ runtime.update(credential_pool=None, command=None, args=[])+ runtime.update(provider=result.target_provider, requested_provider=result.target_provider,+ api_key=result.api_key, base_url=result.base_url, api_mode=result.api_mode or None,+ request_overrides=dict(result.request_overrides or {}),+ capabilities=dict(result.runtime_capabilities or {}))+ return result.new_model, runtimediff --git a/gateway/session_finite.py b/gateway/session_finite.pyindex fee2876a8d7..e27c3011e4f 100644--- a/gateway/session_finite.py+++ b/gateway/session_finite.py@@ -66,5 +66,5 @@ async def execute_finite_admission(authority, ref, row):with finite_turn_scope(row['payload'].get('finite', False), row['payload'].get('unattended') is True), \surface_turn_scope(row['payload'].get('surface_v1')), \display_turn_scope(row['admission_id'], row['payload'].get('display_v1')), \- cli_turn_scope(row['payload'].get('cli_turn_v1')):+ cli_turn_scope(row['admission_id'], row['payload'].get('cli_turn_v1')):return await execute_admission(authority, ref, row)diff --git a/tests/gateway/test_local_viewer_events_submit.py b/tests/gateway/test_local_viewer_events_submit.pyindex e3339245a0b..766a4f561f1 100644--- a/tests/gateway/test_local_viewer_events_submit.py+++ b/tests/gateway/test_local_viewer_events_submit.py@@ -5,8 +5,13 @@ notes) while persisting the clean text, names the turn's author, and runs ``/modas a one-turn override. Each is committed with the admission row as ``cli_turn_v1`` and bound to thatadmission's execution only."""+from types import SimpleNamespace+from unittest.mock import MagicMock, patch+import pytest+from gateway.config import Platform+from tests.gateway.test_surface_admission import _authority@@ -19,7 +24,7 @@ async def test_cli_turn_fields_are_admitted_and_bound_to_their_own_turn(tmp_pathseen = []async def answer(event):- seen.append((event.text, cli_turn(), admission_author.get()))+ seen.append((event.text, cli_turn(event.message_id), cli_turn('another-event'), admission_author.get()))return 'ok'authority = await _authority(tmp_path, monkeypatch, answer)connection = AuthorityConnection(authority, object(), {'user_id': 'owner'})@@ -50,6 +55,107 @@ async def test_cli_turn_fields_are_admitted_and_bound_to_their_own_turn(tmp_path'model_override': {'model': 'gpt-x', 'provider': 'openrouter'}}assert 'cli_turn_v1' not in rows['plain']['payload']assert not {'no-model', 'extra-key', 'bad-text', 'bad-author'} & set(rows)- assert seen[0][0] == 'full' and seen[0][1] == rows['full']['payload']['cli_turn_v1'] and seen[0][2] == author+ assert seen[0] == ('full', rows['full']['payload']['cli_turn_v1'], {}, author)# The next admission never inherits the previous turn's fields.- assert seen[1][0] == 'plain' and seen[1][1] == {}+ assert seen[1][:3] == ('plain', {}, {})+++class _RecordingAgent:+ built: list = []++ def __init__(self, **kwargs):+ type(self).built.append(kwargs)+ self.model = kwargs["model"]+ self.session_id = kwargs.get("session_id")+ self.tools = []+ self.context_compressor = SimpleNamespace(last_prompt_tokens=0, context_length=200_000)+ self.session_prompt_tokens = self.session_completion_tokens = 0+ self.calls = []++ def run_conversation(self, message, **kwargs):+ self.calls.append((message, kwargs))+ return {"final_response": "ok", "messages": []}+++def _gateway_runner():+ runner = MagicMock()+ runner.config = SimpleNamespace(streaming=None)+ runner._provider_routing = {}+ runner._agent_cache_lock = None+ runner._agent_cache = {}+ runner._session_db = runner._prefill_messages = None+ runner._pending_model_notes = runner._pending_skills_reload_notes = {}+ runner.session_store._entries = {}+ runner._pre_agent_fallback_notice = None+ runner._get_system_prompt_for_channel.return_value = None+ runner._resolve_session_agent_runtime.return_value = (+ "session-model", {"provider": "custom", "api_key": "k1", "base_url": "http://session"})+ runner._resolve_session_reasoning_config.return_value = None+ runner._resolve_session_service_tier.return_value = None+ runner._resolve_turn_agent_config.side_effect = lambda _msg, model, rt: {+ "model": model, "runtime": {k: v for k, v in rt.items() if k != "request_overrides"}}+ runner._agent_config_signature.return_value = ("sig",)+ runner._extract_cache_busting_config.return_value = {}+ runner._refresh_fallback_model.return_value = None+ runner._consume_pending_native_image_paths.return_value = []+ runner._consume_pending_turn_sidecar_notes.return_value = []+ for lane in ("_is_telegram_topic_lane", "_is_discord_auto_thread_lane", "_is_relay_discord_channel_lane"):+ getattr(runner, lane).return_value = False+ return runner+++def _run_turn(runner, admission_id="adm-1"):+ from gateway.run_turn_runner import TurnRunner+ from gateway.session import SessionSource+ from gateway.turn_context import TurnContext+ ctx = TurnContext(+ source=SessionSource(platform=Platform.LOCAL, chat_id="c", user_id="u"),+ message="clean text", history=[], session_id="sid", session_key="key", user_config={},+ inbound_message_id=admission_id, AIAgent=_RecordingAgent, resolve_display_setting=lambda *_a: False,+ _run_still_current=lambda: True, _hooks_ref=SimpleNamespace(loaded_hooks=False))+ result = TurnRunner(runner, ctx).run_sync()+ return result, ctx.agent_holder[0]+++def test_the_turn_sends_api_text_persists_the_clean_text_and_runs_the_one_turn_model():+ from gateway.session_cli_turn import cli_turn_scope+ from hermes_cli.model_switch import ModelSwitchResult++ switched = ModelSwitchResult(success=True, new_model="gpt-x", target_provider="openrouter",+ api_key="k2", base_url="http://or", api_mode="chat_completions")+ _RecordingAgent.built = []+ runner = _gateway_runner()+ committed = {"api_text": "[voice] clean text", "model_override": {"model": "gpt-x", "provider": "openrouter"}}+ with patch("hermes_cli.model_switch.switch_model", return_value=switched) as switch, \+ cli_turn_scope("adm-1", committed):+ result, agent = _run_turn(runner)+ assert result["final_response"] == "ok"+ [(message, kwargs)] = agent.calls+ assert message == "[voice] clean text" and kwargs["persist_user_message"] == "clean text"+ assert switch.call_args.kwargs["raw_input"] == "gpt-x"+ assert switch.call_args.kwargs["explicit_provider"] == "openrouter"+ assert switch.call_args.kwargs["current_model"] == "session-model"+ built = _RecordingAgent.built[-1]+ assert (built["model"], built["provider"], built["api_key"], built["base_url"]) == (+ "gpt-x", "openrouter", "k2", "http://or")++ # The next turn (and any turn whose event is not that admission) runs the session's own route.+ with patch("hermes_cli.model_switch.switch_model") as switch, cli_turn_scope("adm-1", committed):+ _result, agent = _run_turn(runner, admission_id="adm-2")+ switch.assert_not_called()+ [(message, kwargs)] = agent.calls+ assert message == "clean text" and "persist_user_message" not in kwargs+ assert _RecordingAgent.built[-1]["model"] == "session-model"+++def test_an_unresolvable_one_turn_model_fails_the_turn_without_running_it():+ from gateway.session_cli_turn import cli_turn_scope+ from hermes_cli.model_switch import ModelSwitchResult++ _RecordingAgent.built = []+ failed = ModelSwitchResult(success=False, error_message="Unknown model 'nope'")+ with patch("hermes_cli.model_switch.switch_model", return_value=failed), \+ cli_turn_scope("adm-1", {"model_override": {"model": "nope"}}):+ 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 == []