The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a typed /model on a local session commits through the owner's model mutation
Teknium8d7e2c0e4e00
diff --git a/gateway/session_setting_commands.py b/gateway/session_setting_commands.pyindex 60271d6e2b6..fdfaf9172dc 100644--- a/gateway/session_setting_commands.py+++ b/gateway/session_setting_commands.py@@ -5,6 +5,7 @@ next turn reads its settings from its live session and frozen policy, not from tper-platform snapshot, so a handler that changes a setting also applies it here: one behaviourfor every surface, held by the gateway."""+from types import SimpleNamespacedef local_live(runner, source):@@ -57,3 +58,34 @@ def local_live_for_route(runner, session_key):if live.route == session_key and live.source.platform == Platform.LOCAL:return livereturn None+++def local_authority_live(runner, source):+ """``(authority, live)`` owning the local session ``source`` belongs to, else ``(None, None)``."""+ from gateway.config import Platform+ if source is None or getattr(source, 'platform', None) != Platform.LOCAL:+ return None, None+ from gateway.session_authorities import all_authorities+ for authority in all_authorities(runner):+ live = getattr(authority, 'sessions', {}).get(source.chat_id)+ if live is not None and live.source.platform == Platform.LOCAL:+ return authority, live+ return None, None+++def defer_local_model_pick(authority, live, result):+ """A typed ``/model`` on a local session: the resolved target becomes the session's canonical+ ``model`` mutation, committed by the owner at the next turn boundary (the typed command is+ itself the running admission). One writer, so the next request, ``sessions.model`` and+ ``session.info`` move together, or the commit is announced as a refusal."""+ import uuid+ from gateway.session_contract import SessionRef+ from gateway.session_deferred_pick import defer_pick+ from hermes_state_local import local_receipt+ sid = live.source.chat_id+ owner = SimpleNamespace(subject=local_receipt(authority.db, sid)['principal_id'])+ payload = {'model': result.new_model}+ if result.target_provider:+ payload['provider'] = result.target_provider+ defer_pick(authority, owner, SessionRef(authority.profile_id, sid),+ {'request_id': 'typed-model:' + uuid.uuid4().hex, 'payload': payload})diff --git a/gateway/slash_commands_model.py b/gateway/slash_commands_model.pyindex 984f0feed2f..2fb2af1e97a 100644--- a/gateway/slash_commands_model.py+++ b/gateway/slash_commands_model.py@@ -413,6 +413,25 @@ class GatewayModelCommandsMixin:async def _commit_model_switch_locked(self, result, ctx: _ModelSwitchContext, *, source, picker: bool) -> str:one_turn = False if picker else ctx.one_turn+ from gateway.session_setting_commands import defer_local_model_pick, local_authority_live+ authority, live = local_authority_live(self, source)+ if live is not None:+ # A local session runs its frozen policy: the owner's canonical model mutation is the+ # only commit, landing at the next turn boundary (this command is the running turn).+ if one_turn:+ return t("gateway.model.error_prefix", error=t("gateway.model.err_once_local"))+ await asyncio.to_thread(defer_local_model_pick, authority, live, result)+ self._record_switch_metrics(result, ctx, source)+ global_error = None+ if ctx.persist_global:+ try:+ await _persist_model_switch_to_config(result, ctx.config_path)+ except Exception as e:+ logger.warning("Failed to persist model switch", exc_info=True)+ global_error = t("gateway.model.err_config_not_updated", error=str(e) or type(e).__name__)+ return await self._model_switch_confirmation(+ result, ctx, one_turn=False, picker=picker, global_error=global_error) + (+ "\n" + t("gateway.model.local_next_turn"))error = self._switch_cached_agent_model(result, ctx, picker)if error is not None:return errordiff --git a/locales/af.yaml b/locales/af.yamlindex 9ba33222459..7438262a69b 100644--- a/locales/af.yaml+++ b/locales/af.yaml@@ -73,6 +73,8 @@ gateway:next_turn_only: " (slegs volgende beurt — herstel na een antwoord)"switch_cancelled: "🟡 Modelwisseling gekanselleer. Huidige model onveranderd ({model})."guard_confirm: "⚠️ **{title}**\n\n{message}\n\n_Teks-alternatief: antwoord `{prefix}approve` om te wissel of `{prefix}cancel` om die huidige model te behou._"+ err_once_local: "`--once` is not available in this session; use `/model <name>` and switch back after the turn."+ local_next_turn: "Applies from your next message."agents:header: "🤖 **Aktiewe Agente & Take**"active_agents: "**Aktiewe agente:** {count}"diff --git a/locales/ar.yaml b/locales/ar.yamlindex 12453eb8369..e16a308c0b0 100644--- a/locales/ar.yaml+++ b/locales/ar.yaml@@ -73,6 +73,8 @@ gateway:next_turn_only: " (للدور التالي فقط — يُستعاد بعد ردّ واحد)"switch_cancelled: "🟡 أُلغي تبديل النموذج. النموذج الحالي لم يتغيّر ({model})."guard_confirm: "⚠️ **{title}**\n\n{message}\n\n_بديل نصي: أرسل `{prefix}approve` للتبديل أو `{prefix}cancel` للإبقاء على النموذج الحالي._"+ err_once_local: "`--once` is not available in this session; use `/model <name>` and switch back after the turn."+ local_next_turn: "Applies from your next message."agents:header: "🤖 **الوكلاء والمهام النشطة**"active_agents: "**الوكلاء النشطون:** {count}"diff --git a/locales/de.yaml b/locales/de.yamlindex c02b702fd92..8a39d5fb74f 100644--- a/locales/de.yaml+++ b/locales/de.yaml@@ -73,6 +73,8 @@ gateway:next_turn_only: " (nur nächster Zug — wird nach einer Antwort zurückgesetzt)"switch_cancelled: "🟡 Modellwechsel abgebrochen. Aktuelles Modell unverändert ({model})."guard_confirm: "⚠️ **{title}**\n\n{message}\n\n_Text-Rückfall: Antworten Sie mit `{prefix}approve`, um zu wechseln, oder mit `{prefix}cancel`, um das aktuelle Modell zu behalten._"+ err_once_local: "`--once` is not available in this session; use `/model <name>` and switch back after the turn."+ local_next_turn: "Applies from your next message."agents:header: "🤖 **Aktive Agenten & Aufgaben**"active_agents: "**Aktive Agenten:** {count}"diff --git a/locales/en.yaml b/locales/en.yamlindex 0a53362f21d..cccaf90da1d 100644--- a/locales/en.yaml+++ b/locales/en.yaml@@ -76,6 +76,8 @@ gateway:next_turn_only: " (next turn only — restores after one response)"switch_cancelled: "🟡 Model switch cancelled. Current model unchanged ({model})."guard_confirm: "⚠️ **{title}**\n\n{message}\n\n_Text fallback: reply `{prefix}approve` to switch or `{prefix}cancel` to keep the current model._"+ err_once_local: "`--once` is not available in this session; use `/model <name>` and switch back after the turn."+ local_next_turn: "Applies from your next message."agents:header: "🤖 **Active Agents & Tasks**"active_agents: "**Active agents:** {count}"diff --git a/locales/es.yaml b/locales/es.yamlindex 88670715f7d..111e9577220 100644--- a/locales/es.yaml+++ b/locales/es.yaml@@ -73,6 +73,8 @@ gateway:next_turn_only: " (solo el próximo turno: se restaura tras una respuesta)"switch_cancelled: "🟡 Cambio de modelo cancelado. El modelo actual no cambia ({model})."guard_confirm: "⚠️ **{title}**\n\n{message}\n\n_Alternativa en texto: responde `{prefix}approve` para cambiar o `{prefix}cancel` para conservar el modelo actual._"+ err_once_local: "`--once` is not available in this session; use `/model <name>` and switch back after the turn."+ local_next_turn: "Applies from your next message."agents:header: "🤖 **Agentes y tareas activos**"active_agents: "**Agentes activos:** {count}"diff --git a/locales/fr.yaml b/locales/fr.yamlindex d506c214461..cc5512171e1 100644--- a/locales/fr.yaml+++ b/locales/fr.yaml@@ -72,6 +72,8 @@ gateway:err_stale_override: "enregistré dans config.yaml, mais l'ancienne surcharge de session n'a pas été effacée ({error})"next_turn_only: " (prochain tour uniquement — rétabli après une réponse)"switch_cancelled: "🟡 Changement de modèle annulé. Le modèle actuel est inchangé ({model})."+ err_once_local: "`--once` is not available in this session; use `/model <name>` and switch back after the turn."+ local_next_turn: "Applies from your next message."guard_confirm: |-⚠️ **{title}**diff --git a/locales/ga.yaml b/locales/ga.yamlindex dcb3458f3ae..3da8ffe1a0a 100644--- a/locales/ga.yaml+++ b/locales/ga.yaml@@ -73,6 +73,8 @@ gateway:next_turn_only: " (an chéad seal eile amháin — filleann sé tar éis freagra amháin)"switch_cancelled: "🟡 Athrú samhla cealaithe. Samhail reatha gan athrú ({model})."guard_confirm: "⚠️ **{title}**\n\n{message}\n\n_Cúltaca téacs: freagair `{prefix}approve` chun athrú nó `{prefix}cancel` chun an tsamhail reatha a choinneáil._"+ err_once_local: "`--once` is not available in this session; use `/model <name>` and switch back after the turn."+ local_next_turn: "Applies from your next message."agents:header: "🤖 **Gníomhairí & Tascanna Gníomhacha**"active_agents: "**Gníomhairí gníomhacha:** {count}"diff --git a/locales/hu.yaml b/locales/hu.yamlindex 6f7ebb685bc..52b233f3906 100644--- a/locales/hu.yaml+++ b/locales/hu.yaml@@ -73,6 +73,8 @@ gateway:next_turn_only: " (csak a következő körre — egy válasz után visszaáll)"switch_cancelled: "🟡 Modellváltás megszakítva. A jelenlegi modell változatlan ({model})."guard_confirm: "⚠️ **{title}**\n\n{message}\n\n_Szöveges mód: írd be: `{prefix}approve` a váltáshoz, `{prefix}cancel` a jelenlegi modell megtartásához._"+ err_once_local: "`--once` is not available in this session; use `/model <name>` and switch back after the turn."+ local_next_turn: "Applies from your next message."agents:header: "🤖 **Aktív ügynökök és feladatok**"active_agents: "**Aktív ügynökök:** {count}"diff --git a/locales/it.yaml b/locales/it.yamlindex ec61b32a429..504edea4b85 100644--- a/locales/it.yaml+++ b/locales/it.yaml@@ -73,6 +73,8 @@ gateway:next_turn_only: " (solo per il prossimo turno — viene ripristinato dopo una risposta)"switch_cancelled: "🟡 Cambio di modello annullato. Modello attuale invariato ({model})."guard_confirm: "⚠️ **{title}**\n\n{message}\n\n_Fallback testuale: rispondi `{prefix}approve` per cambiare o `{prefix}cancel` per mantenere il modello attuale._"+ err_once_local: "`--once` is not available in this session; use `/model <name>` and switch back after the turn."+ local_next_turn: "Applies from your next message."agents:header: "🤖 **Agenti e attività attivi**"active_agents: "**Agenti attivi:** {count}"diff --git a/locales/ja.yaml b/locales/ja.yamlindex 975695a522a..0eccdc8dd48 100644--- a/locales/ja.yaml+++ b/locales/ja.yaml@@ -73,6 +73,8 @@ gateway:next_turn_only: " (次のターンのみ — 1 回応答した後に元へ戻ります)"switch_cancelled: "🟡 モデルの切り替えをキャンセルしました。現在のモデルは変わりません ({model})。"guard_confirm: "⚠️ **{title}**\n\n{message}\n\n_テキスト代替: 切り替えるには `{prefix}approve`、現在のモデルを維持するには `{prefix}cancel` と返信してください。_"+ err_once_local: "`--once` is not available in this session; use `/model <name>` and switch back after the turn."+ local_next_turn: "Applies from your next message."agents:header: "🤖 **アクティブなエージェントとタスク**"active_agents: "**アクティブなエージェント:** {count}"diff --git a/locales/ko.yaml b/locales/ko.yamlindex 2d0da98f856..74cbac00d91 100644--- a/locales/ko.yaml+++ b/locales/ko.yaml@@ -73,6 +73,8 @@ gateway:next_turn_only: " (다음 턴에만 적용 — 응답 한 번 후 복원돼요)"switch_cancelled: "🟡 모델 전환이 취소됐어요. 현재 모델은 그대로예요({model})."guard_confirm: "⚠️ **{title}**\n\n{message}\n\n_텍스트로 답하려면: 전환은 `{prefix}approve`, 현재 모델 유지는 `{prefix}cancel`이라고 답해 주세요._"+ err_once_local: "`--once` is not available in this session; use `/model <name>` and switch back after the turn."+ local_next_turn: "Applies from your next message."agents:header: "🤖 **활성 에이전트 및 작업**"active_agents: "**활성 에이전트:** {count}"diff --git a/locales/pt.yaml b/locales/pt.yamlindex 019facea8ec..f4e4a7b17c3 100644--- a/locales/pt.yaml+++ b/locales/pt.yaml@@ -73,6 +73,8 @@ gateway:next_turn_only: " (apenas no próximo turno — volta ao normal após uma resposta)"switch_cancelled: "🟡 Troca de modelo cancelada. Modelo atual inalterado ({model})."guard_confirm: "⚠️ **{title}**\n\n{message}\n\n_Alternativa em texto: responda `{prefix}approve` para trocar ou `{prefix}cancel` para manter o modelo atual._"+ err_once_local: "`--once` is not available in this session; use `/model <name>` and switch back after the turn."+ local_next_turn: "Applies from your next message."agents:header: "🤖 **Agentes e tarefas ativos**"active_agents: "**Agentes ativos:** {count}"diff --git a/locales/ru.yaml b/locales/ru.yamlindex 10b1e1bb4fe..1f8b092b0a1 100644--- a/locales/ru.yaml+++ b/locales/ru.yaml@@ -73,6 +73,8 @@ gateway:next_turn_only: " (только на следующий ход — вернётся после одного ответа)"switch_cancelled: "🟡 Смена модели отменена. Текущая модель не изменилась ({model})."guard_confirm: "⚠️ **{title}**\n\n{message}\n\n_Текстовый вариант: ответьте `{prefix}approve`, чтобы переключиться, или `{prefix}cancel`, чтобы оставить текущую модель._"+ err_once_local: "`--once` is not available in this session; use `/model <name>` and switch back after the turn."+ local_next_turn: "Applies from your next message."agents:header: "🤖 **Активные агенты и задачи**"active_agents: "**Активные агенты:** {count}"diff --git a/locales/tr.yaml b/locales/tr.yamlindex ba5154bf5b5..8b5ab233f80 100644--- a/locales/tr.yaml+++ b/locales/tr.yaml@@ -73,6 +73,8 @@ gateway:next_turn_only: " (yalnızca sonraki tur — bir yanıttan sonra geri döner)"switch_cancelled: "🟡 Model değişikliği iptal edildi. Geçerli model değişmedi ({model})."guard_confirm: "⚠️ **{title}**\n\n{message}\n\n_Metin alternatifi: geçmek için `{prefix}approve`, geçerli modeli korumak için `{prefix}cancel` yazın._"+ err_once_local: "`--once` is not available in this session; use `/model <name>` and switch back after the turn."+ local_next_turn: "Applies from your next message."agents:header: "🤖 **Aktif Ajanlar ve Görevler**"active_agents: "**Aktif ajanlar:** {count}"diff --git a/locales/uk.yaml b/locales/uk.yamlindex 350f639cc75..8c9826c7b20 100644--- a/locales/uk.yaml+++ b/locales/uk.yaml@@ -73,6 +73,8 @@ gateway:next_turn_only: " (лише на наступний хід — відновиться після однієї відповіді)"switch_cancelled: "🟡 Перемикання моделі скасовано. Поточна модель без змін ({model})."guard_confirm: "⚠️ **{title}**\n\n{message}\n\n_Текстова альтернатива: відповідайте `{prefix}approve`, щоб перемкнути, або `{prefix}cancel`, щоб залишити поточну модель._"+ err_once_local: "`--once` is not available in this session; use `/model <name>` and switch back after the turn."+ local_next_turn: "Applies from your next message."agents:header: "🤖 **Активні агенти та завдання**"active_agents: "**Активні агенти:** {count}"diff --git a/locales/zh-hant.yaml b/locales/zh-hant.yamlindex c9fb6cb24cc..f07de039594 100644--- a/locales/zh-hant.yaml+++ b/locales/zh-hant.yaml@@ -73,6 +73,8 @@ gateway:next_turn_only: " (僅下一輪有效 — 回應一次後即還原)"switch_cancelled: "🟡 已取消切換模型。目前模型不變({model})。"guard_confirm: "⚠️ **{title}**\n\n{message}\n\n_文字備援:回覆 `{prefix}approve` 以切換,或 `{prefix}cancel` 以保留目前模型。_"+ err_once_local: "`--once` is not available in this session; use `/model <name>` and switch back after the turn."+ local_next_turn: "Applies from your next message."agents:header: "🤖 **作用中的代理與任務**"active_agents: "**作用中代理:** {count}"diff --git a/locales/zh.yaml b/locales/zh.yamlindex 83e4ed5c1da..67984c7c4ed 100644--- a/locales/zh.yaml+++ b/locales/zh.yaml@@ -73,6 +73,8 @@ gateway:next_turn_only: " (仅下一回合生效——一次响应后恢复)"switch_cancelled: "🟡 已取消切换模型。当前模型不变({model})。"guard_confirm: "⚠️ **{title}**\n\n{message}\n\n_文字回退方式:回复 `{prefix}approve` 切换,或回复 `{prefix}cancel` 保留当前模型。_"+ err_once_local: "`--once` is not available in this session; use `/model <name>` and switch back after the turn."+ local_next_turn: "Applies from your next message."agents:header: "🤖 **活跃代理与任务**"active_agents: "**活跃代理:** {count}"diff --git a/tests/gateway/test_session_model_command_commits.py b/tests/gateway/test_session_model_command_commits.pynew file mode 100644index 00000000000..ba7de2b0804--- /dev/null+++ b/tests/gateway/test_session_model_command_commits.py@@ -0,0 +1,71 @@+"""A typed ``/model`` admitted as a prompt on a local session commits the session's policy (#138814)."""+import asyncio+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import sqlite3+import threading++import pytest++from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket+from tests.gateway.test_session_mutation_model import CatalogModel+from tests.waiting import async_wait_until++[email protected]("linux")+def test_typed_model_command_on_a_local_session_moves_the_next_request(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), CatalogModel)+ peer.requests = []+ peer.blocked, peer.release = threading.Event(), threading.Event()+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ cfg = {'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'original', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}}, 'platform_toolsets': {'cli': []}}+ (home / 'config.yaml').write_text(json.dumps(cfg))+ (home / 'models_dev_cache.json').write_text(json.dumps({'custom': {'id': 'custom', 'models': {+ name: {'id': name, 'name': name, 'limit': {'context': 100000, 'output': 4000}}+ for name in ('original', 'switched')}}}))+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}+ 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')++ async def run(desc):+ async with websocket(home, desc) as ws:+ async def call(method, **params):+ response = await rpc(ws, method, **params)+ assert 'result' in response, response+ return response['result']++ async def turn(sid, text):+ await call('prompt.submit', session_id=sid, input_id=text, text=text)++ def terminal():+ with sqlite3.connect(home / 'state.db') as db:+ row = db.execute('SELECT status FROM session_admissions WHERE request_id=?', (text,)).fetchone()+ return row and row[0] == 'terminal'+ await async_wait_until(terminal, timeout=30, what=f'{text} terminal')++ sid = (await call('session.create', source='tui', request_id='owner', toolsets=[]))['session_id']+ await turn(sid, 'BEFORE')+ await turn(sid, '/model switched')+ await turn(sid, 'AFTER')+ assert [r['model'] for r in peer.requests] == ['original', 'switched'], [(r['model'], r['messages'][-1]['content']) for r in peer.requests]+ assert (await call('session.info', session_id=sid))['model'] == 'switched'+ with sqlite3.connect(home / 'state.db') as db:+ assert db.execute('SELECT model FROM sessions WHERE id=?', (sid,)).fetchone()[0] == 'switched'+ try:+ with daemon(root, home, env, barrier=False) as (_, desc):+ asyncio.run(run(desc))+ finally:+ peer.release.set()+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)diff --git a/tests/gateway/test_session_mutation_model_busy.py b/tests/gateway/test_session_mutation_model_busy.pyindex 63596381142..97da18d16f8 100644--- a/tests/gateway/test_session_mutation_model_busy.py+++ b/tests/gateway/test_session_mutation_model_busy.py@@ -23,7 +23,8 @@ def _owner(tmp_path, monkeypatch, handle):store = SessionStore(tmp_path / 'sessions', GatewayConfig())db = store._dbrunner = SimpleNamespace(session_store=store, _session_db=db, adapters={}, _draining=False,- _evict_cached_agent=lambda route: None, _handle_message=handle,+ _evict_cached_agent=lambda route: None, _cached_agent_for=lambda route: None,+ _handle_message=handle,_resolve_session_agent_runtime=lambda **k: ('frozen', {}))runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)authority = SessionAuthority(runner, profile_id='owned', instance_id='owner', db=db,