The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a cold /review sends what a resident one sends
Tekniumb222bced94bc
diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.pyindex 36de190dcaa..1085f99a5a3 100644--- a/gateway/run_turn_prepare.py+++ b/gateway/run_turn_prepare.py@@ -37,6 +37,8 @@ if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)# Log-record parity with the origin module.logger = logging.getLogger("gateway.run")+# ``_resolve_turn_agent_config``'s default tier: the runner's per-turn ``_service_tier``.+_TIER_FROM_RUNNER = object()def _resolve_policy_agent_runtime(runner, policy, *, fallback=True) -> tuple[str, dict]:@@ -210,9 +212,12 @@ class GatewayTurnPrepareMixin:return _recover_or_remember_model(self, skey, model), runtime_kwargs- def _resolve_turn_agent_config(self, user_message: str, model: str, runtime_kwargs: dict) -> dict:+ def _resolve_turn_agent_config(self, user_message: str, model: str, runtime_kwargs: dict, *,+ tier: Any = _TIER_FROM_RUNNER) -> dict:"""Effective model/runtime config for one turn. With `/fast` priority on, fast-mode- ``request_overrides`` are deep-merged OVER the per-provider ones so both reach the model."""+ ``request_overrides`` are deep-merged OVER the per-provider ones so both reach the model.+ ``tier`` defaults to the runner's per-turn ``_service_tier``; an off-turn builder (a cold+ ``/review``) passes the session's own instead of writing that shared slot."""from gateway.run import _deep_merge_request_overridesfrom agent.fast_mode import STATIC_TIERSfrom hermes_cli.models import resolve_fast_mode_overrides@@ -234,7 +239,8 @@ class GatewayTurnPrepareMixin:runtime["api_mode"], runtime["command"], tuple(runtime["args"]),),}- tier = getattr(self, "_service_tier", None)+ if tier is _TIER_FROM_RUNNER:+ tier = getattr(self, "_service_tier", None)if tier not in STATIC_TIERS:# None / auto / cold: the bounded window is applied per request by agent.fast_mode.route["request_overrides"] = base_request_overridesdiff --git a/gateway/session_cold_review.py b/gateway/session_cold_review.pyindex dd429a9f794..009a618de46 100644--- a/gateway/session_cold_review.py+++ b/gateway/session_cold_review.py@@ -38,6 +38,7 @@ def cold_review_parent(runner, source, session_key, session_id):from gateway.session_api_turn import api_runtime_lockedfrom gateway.session_authorities import active_authorityfrom gateway.session_policy import policy_for_source, policy_scope, policy_turn_toolsets+ from gateway.session_worker_construct import session_prefill, session_routingfrom run_agent import AIAgentpolicy = policy_for_source(runner, source)authority = active_authority(runner) if policy else None@@ -46,16 +47,24 @@ def cold_review_parent(runner, source, session_key, session_id):enabled, disabled = runner._resolve_turn_toolsets(user_config, source, platform_key)if policy:enabled = policy_turn_toolsets(authority, policy, user_config, source.chat_id)+ # Each input below is the one the turn runner reads for this session (``run_turn_runner``).+ pr = session_routing(authority, policy) if policy else runner._provider_routing+ prefill = session_prefill(authority, policy, source.chat_id) if policy else runner._prefill_messages+ tier = (policy.current_service_tier(runner, session_key) if policy else+ runner._resolve_session_service_tier(source=source, session_key=session_key))with policy_scope(policy, authority=authority):model, runtime = runner._resolve_session_agent_runtime(source=source, session_key=session_key, user_config=user_config)- pr = runner._provider_routing+ route = runner._resolve_turn_agent_config("", model, runtime, tier=tier) # /fast request optionsagent = AIAgent(- model=model, **runtime, quiet_mode=True, verbose_logging=False,+ model=route["model"], **route["runtime"], quiet_mode=True, verbose_logging=False,enabled_toolsets=enabled, disabled_toolsets=disabled,# Launch-preloaded skills (``hermes -s``): the reviewer is told to load them too.ephemeral_system_prompt=(policy.skills_prompt if policy else None) or None,- reasoning_config=runner._resolve_session_reasoning_config(source=source, model=model),+ prefill_messages=prefill or None,+ reasoning_config=runner._resolve_session_reasoning_config(source=source, session_key=session_key,+ model=model),+ service_tier=tier, request_overrides=route.get("request_overrides"),providers_allowed=pr.get("only"), providers_ignored=pr.get("ignore"), providers_order=pr.get("order"),provider_sort=pr.get("sort"), provider_require_parameters=pr.get("require_parameters", False),provider_data_collection=pr.get("data_collection"),diff --git a/tests/gateway/test_local_review_without_cached_agent.py b/tests/gateway/test_local_review_without_cached_agent.pyindex 4d757248fc5..35f5c0b2b68 100644--- a/tests/gateway/test_local_review_without_cached_agent.py+++ b/tests/gateway/test_local_review_without_cached_agent.py@@ -3,12 +3,15 @@The gateway drops a session's cached agent after an idle hour, under memory pressure, and around a``/moa`` turn. ``/review`` read only the cached agent, so a session left alone for an hour answered"Nothing to review yet — send a message first" until the next message rebuilt one. The conversation-is the session's stored transcript; the reviewer reviews it and its completion re-enters the session.+is the session's stored transcript; the reviewer reviews it, its completion re-enters the session, and+its request carries what a review from the resident agent carries (the session's provider routing,+not the daemon's startup copy, and its prefill examples).Real daemon (``python -m gateway.run``), ``slash.exec`` (``session_commands.execute_command``),loopback model. ``/moa`` drops the cached agent here because the idle sweep's first pass is a minute in."""import asyncio+import contextlibimport jsonimport signalimport sqlite3@@ -35,46 +38,60 @@ def test_local_review_reviews_the_stored_conversation_once_the_cached_agent_is_gthread = threading.Thread(target=peer.serve_forever, daemon=True)thread.start()url = f'http://127.0.0.1:{peer.server_port}/v1'- (home / 'config.yaml').write_text(json.dumps({+ config = {'gateway': {'multiplex_profiles': False},- 'model': {'provider': 'custom', 'default': 'review-model', 'base_url': url},+ 'model': {'provider': 'openrouter', 'default': 'openai/gpt-5', 'base_url': url,+ 'api_key': 'loopback-only', 'api_mode': 'chat_completions'},'auxiliary': {'title_generation': {'enabled': False}},- }))+ 'provider_routing': {'only': ['daemon-start'], 'data_collection': 'allow'},+ 'prefill_messages_file': 'prefill.json',+ }+ (home / 'prefill.json').write_text(json.dumps([{'role': 'user', 'content': 'PREFILL_EXAMPLE'},+ {'role': 'assistant', 'content': 'Noted.'}]))+ (home / 'config.yaml').write_text(json.dumps(config))env = child_env()env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),- OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, PYTHONUNBUFFERED='1')+ OPENROUTER_API_KEY='loopback-only', OPENAI_API_KEY='loopback-only', PYTHONUNBUFFERED='1')out = {}+ def settled():+ with contextlib.closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ return all(row[0] == 'terminal' for row in db.execute('SELECT status FROM session_admissions'))++ async def review(ws, sid, focus):+ before = len(peer.requests)+ reply = await rpc(ws, 'slash.exec', session_id=sid, command='review ' + focus)+ result = reply.get('result') or reply.get('error')+ assert 'Review started' in json.dumps(result), (focus, result)++ def reviewer(request):+ return any(m.get('content') == 'Review: ' + focus for m in request.get('messages', []))+ await async_wait_until(lambda: any(reviewer(r) for r in peer.requests[before:]), timeout=45,+ what=f'the {focus} reviewer reaching the model')+ request = next(r for r in peer.requests[before:] if reviewer(r))+ text = json.dumps(request['messages'])+ # The reviewer's completion comes back to this session as a delegation-completion turn.+ await async_wait_until(lambda: any('ASYNC DELEGATION' in json.dumps(r) for r in peer.requests[before:]),+ timeout=60, what=f'the {focus} completion re-entering the session')+ await async_wait_until(settled, timeout=60, what=f'the {focus} completion turn settling')+ return {'provider': request.get('provider'), 'prefill': 'PREFILL_EXAMPLE' in text,+ 'saw_conversation': 'OPENED_PR_42' in text}+async def probe(desc):async with websocket(home, desc) as ws:+ # A local session takes the profile's config as of its creation, not the daemon's startup copy.+ config['provider_routing'] = {'only': ['session'], 'data_collection': 'deny'}+ (home / 'config.yaml').write_text(json.dumps(config))created = await rpc(ws, 'session.create', request_id='cold-review', source='cli', toolsets=[],cwd=str(work))sid = created['result']['session_id']-- def rows():- with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:- return dict(db.execute('SELECT request_id,status FROM session_admissions'))-- async def settle(input_id):- await async_wait_until(lambda: rows().get(input_id) == 'terminal', timeout=45,- what=f'{input_id} turn terminal')-await rpc(ws, 'prompt.submit', session_id=sid, input_id='warm', text='OPENED_PR_42')- await settle('warm')+ await async_wait_until(settled, timeout=45, what='the warm turn settling')+ out['warm'] = await review(ws, sid, 'resident pass')moa = (await rpc(ws, 'slash.exec', session_id=sid, command='moa compare the options'))['result']await rpc(ws, 'prompt.submit', session_id=sid, input_id='moa', text=moa['message'])- await settle('moa')- before = len(peer.requests)- reply = await rpc(ws, 'slash.exec', session_id=sid, command='review check the naming')- out['review'] = review = reply.get('result') or reply.get('error')- assert 'Nothing to review' not in json.dumps(review), ('/review lost the conversation with its agent', out)- await async_wait_until(lambda: any('check the naming' in json.dumps(r) for r in peer.requests[before:]),- timeout=30, what='the reviewer reaching the model')- request = next(r for r in peer.requests[before:] if 'check the naming' in json.dumps(r))- out['reviewer_saw_conversation'] = 'OPENED_PR_42' in json.dumps(request['messages'])- # The reviewer's completion comes back to this session as a delegation-completion turn.- await async_wait_until(lambda: any('ASYNC DELEGATION' in json.dumps(r) for r in peer.requests[before:]),- timeout=60, what='the review completion re-entering the session')+ await async_wait_until(settled, timeout=45, what='the /moa turn settling')+ out['cold'] = await review(ws, sid, 'cold pass')try:with daemon(root, home, env, barrier=False) as (proc, desc):@@ -86,6 +103,6 @@ def test_local_review_reviews_the_stored_conversation_once_the_cached_agent_is_gpeer.server_close()thread.join(timeout=5)- review = out['review']- assert review.get('type') == 'exec' and 'Review started' in review['output'], out- assert out['reviewer_saw_conversation'], out+ assert out['cold']['saw_conversation'], out+ assert out['warm']['provider'] == {'only': ['session'], 'data_collection': 'deny'}, out+ assert out['cold'] == out['warm'], ('a cold /review must send what a resident one sends', out)