The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli,acp): collect the owner's guarded-model confirmation on the classic chat view and ACP
Teknium10e2b6226d74
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.pyindex 2bec951f5be..dd61c2f3575 100644--- a/acp_adapter/gateway_server.py+++ b/acp_adapter/gateway_server.py@@ -356,11 +356,41 @@ class GatewayACPAgent(acp.Agent):session_id = self._aliases.get(session_id, session_id)client = await self._client()payload = {'model': model_id}- await self._mutations.apply(client, session_id, 'model', payload)+ result = await self._mutations.apply(client, session_id, 'model', payload,+ confirm=self._model_confirmer(session_id))+ if result.get('status') == 'cancelled':+ # Declined: nothing was written; the editor's picker must not show the target as active.+ raise GatewayClientError('model_switch_cancelled')self._snapshots[session_id] = await client.rpc('session.resume', session_id=session_id)self._mutations.acknowledge(session_id, 'model', payload)return SetSessionModelResponse()+ def _model_confirmer(self, session_id):+ """The owner's guarded-model confirmation as an ACP permission request (the mechanism+ approvals use): "Switch anyway" re-sends the mutation once with the owner's token; deny,+ dismissal or a lost editor keeps the current model. None without an editor connection."""+ if self._conn is None:+ return None++ async def confirm(refusal):+ from acp.schema import AllowedOutcome, PermissionOption+ from agent.i18n import t+ from hermes_cli.gateway_mutations import confirmation_title+ title = confirmation_title(refusal)+ tool_call = acp.update_tool_call(+ f"model-confirm-{uuid.uuid4().hex[:12]}", title=f"{title}: {refusal.get('target_model', '')}",+ kind="other", status="pending",+ content=[acp.tool_content(acp.text_block(refusal['confirm_message']))],+ raw_input={'model': refusal.get('target_model'), 'provider': refusal.get('target_provider'),+ 'guards': [w.get('kind') for w in refusal.get('warnings') or []]})+ options = [PermissionOption(option_id="allow_once", kind="allow_once",+ name=t("cli.model.choice_switch_anyway")),+ PermissionOption(option_id="deny", kind="reject_once", name=t("cli.model.choice_cancel"))]+ response = await self._conn.request_permission(session_id=self._editor_id(session_id),+ tool_call=tool_call, options=options)+ return isinstance(response.outcome, AllowedOutcome) and response.outcome.option_id == "allow_once"+ return confirm+async def set_session_mode(self, mode_id, session_id, **kwargs):raise GatewayClientError("acp_edit_policy_mutation_unavailable")@@ -394,8 +424,13 @@ class GatewayACPAgent(acp.Agent):if operation == 'branch':raise GatewayClientError('use_acp_fork_session')client = await self._client()- result = await self._mutations.apply(client, session_id, operation, payload)- if result.get('status') == 'preview':+ result = await self._mutations.apply(client, session_id, operation, payload,+ confirm=self._model_confirmer(session_id) if operation == 'model' else None)+ if result.get('status') == 'cancelled':+ from agent.i18n import t+ await self._conn.session_update(session_id=held_id,+ update=acp.update_agent_message_text(t('cli.model.switch_cancelled') + '\n'))+ elif result.get('status') == 'preview':# Read-only report: nothing changed, so the editor's snapshot is still current.await self._conn.session_update(session_id=held_id,update=acp.update_agent_message_text('\n'.join(result['lines']) + '\n'))diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.pyindex 016aaf8844a..2158a5aee5c 100644--- a/hermes_cli/gateway_chat_view.py+++ b/hermes_cli/gateway_chat_view.py@@ -42,6 +42,9 @@ class GatewayChatView:self.failed = asyncio.Event()from hermes_cli.gateway_mutations import PreparedMutationsself.mutations = PreparedMutations()+ # The interactive composer (set by ``run``); None in one-shot / non-TTY runs, where a+ # guarded model switch stays a refusal instead of a prompt.+ self._composer = Nonedef unknown_admissions(self):return [row["admission_id"] for row in self.pending if row["status"] == "unknown"]@@ -236,7 +239,10 @@ class GatewayChatView:from hermes_cli.gateway_mutations import slash_mutationoperation, payload = slash_mutation(command, rest.strip())original = self.session_id- result = await self.mutations.apply(self.client, original, operation, payload)+ confirm = self._confirm_model_switch if operation == 'model' and self._composer is not None else None+ result = await self.mutations.apply(self.client, original, operation, payload, confirm=confirm)+ if result.get('status') == 'cancelled':+ return Trueif result.get('status') == 'preview':self.mutations.acknowledge(original, operation, payload)print('\n'.join(result['lines']))@@ -247,6 +253,8 @@ class GatewayChatView:self.generation = snapshot['execution_generation']self.prompts = {p['prompt_id']: p for p in snapshot.get('prompts', [])}self.mutations.acknowledge(original, operation, payload)+ if operation == 'model' and result.get('model'):+ self.model = str(result['model']).split('/')[-1]print(f"{operation}: {target}")return Trueif command == "/yolo":@@ -263,6 +271,26 @@ class GatewayChatView:return Trueraise GatewayClientError("Unsupported gateway CLI command; use /help. No local command was run.")+ async def _confirm_model_switch(self, refusal):+ """The owner refused a guarded model target (cost / data policy / large context): ask as+ the in-process CLI does (``_confirm_expensive_model_switch``: switch anyway once, or cancel)+ on this composer. Only an explicit yes applies; anything else keeps the current model."""+ from agent.i18n import t+ from hermes_cli.gateway_mutations import confirm_choice, confirmation_title+ choices = [("once", t("cli.model.choice_switch_anyway"), t("cli.model.desc_switch_anyway")),+ ("cancel", t("cli.model.choice_cancel"), t("cli.model.desc_keep_current_model"))]+ print(f"\n!!! {confirmation_title(refusal)} !!!\n{refusal['confirm_message']}\n")+ for index, (_, label, detail) in enumerate(choices, 1):+ print(f" {index}. {label} \u2014 {detail}")+ try:+ raw = await self._read_line(self._composer, t("cli.model.confirm_choice_prompt"))+ except (KeyboardInterrupt, EOFError):+ raw = ""+ if not self.failure and confirm_choice(raw, choices) == "once":+ return True+ print(t("cli.model.switch_cancelled"))+ return False+def _detach(self, message):"""One-shot cannot go on without a human: say why on stderr, exit 3, and in stream-jsonmode close the protocol with a failed ``result`` (a consumer parsing stdout must never be@@ -378,6 +406,7 @@ class GatewayChatView:prompt = PromptSession(erase_when_done=True,bottom_toolbar=lambda: f" \u2624 {self.model} \u2502 {self.session_id} ")prompt_symbol = get_active_prompt_symbol("❯ ")+ self._composer = prompt if sys.stdin.isatty() else Nonewith patch_stdout():while not self.failure:try:diff --git a/hermes_cli/gateway_mutations.py b/hermes_cli/gateway_mutations.pyindex ff1bf4e2bf1..de2a15d4258 100644--- a/hermes_cli/gateway_mutations.py+++ b/hermes_cli/gateway_mutations.py@@ -8,7 +8,15 @@ class PreparedMutations:def __init__(self):self.pending = {}- async def apply(self, client, session_id, operation, payload):+ async def apply(self, client, session_id, operation, payload, *, confirm=None):+ """The owner's answer for this prepared mutation (retained across ambiguous replies).++ A guarded model target answers ``status: confirmation_required`` and writes nothing.+ ``confirm`` (``async (refusal) -> bool``) is the surface's prompt: yes re-sends the same+ retained mutation once with ``payload.confirm`` = the owner's token (under the original+ key, so an ambiguous reply to the confirmed send retries that exact request); no answers+ ``status: cancelled``. Without a prompt (non-interactive) the refusal is an error, and a+ confirmed send refused again (another switch or a turn landed first) is never re-asked."""encoded = json.dumps(payload, sort_keys=True)key = (session_id, operation, encoded)if key not in self.pending:@@ -17,7 +25,7 @@ class PreparedMutations:payload=json.loads(encoded), request_id=uuid.uuid4().hex,expected_revision=snapshot['revision'], expected_generation=snapshot['execution_generation'])}entry = self.pending[key]- if 'result' not in entry:+ while 'result' not in entry:try:# A compression answers after its summary + commit; the default budget would report# a timeout while the owner (which shields the mutation) still commits it.@@ -32,19 +40,55 @@ class PreparedMutations:'unsupported_compress_options'}:self.pending.pop(key)raise- if entry['result'].get('status') == 'confirmation_required':- # The owner wrote nothing: a guarded model target needs the user's confirmation- # (payload ``confirm`` = the returned token). These surfaces cannot collect it- # yet, so say so instead of reporting the switch as done.+ refusal = entry['result']+ if refusal.get('status') != 'confirmation_required':+ break+ # The owner wrote nothing (no receipt): the same tuple may be re-sent with the token.+ del entry['result']+ if confirm is None or 'confirm' in entry['params']['payload']:+ self.pending.pop(key)+ raise GatewayClientError(model_refusal_text(refusal, confirmed=confirm is not None))+ try:+ accepted = await confirm(refusal)+ except BaseException:+ self.pending.pop(key)+ raise+ if not accepted:self.pending.pop(key)- raise GatewayClientError(entry['result']['confirm_message'] + '\n\nModel not switched: '- 'this target needs a confirmation this client cannot collect yet.')+ return {'status': 'cancelled', 'session_id': session_id, 'operation': operation}+ entry['params'] = {**entry['params'], 'request_id': uuid.uuid4().hex,+ 'payload': {**entry['params']['payload'], 'confirm': refusal['confirm']}}return entry['result']def acknowledge(self, session_id, operation, payload):self.pending.pop((session_id, operation, json.dumps(payload, sort_keys=True)), None)+def model_refusal_text(refusal, *, confirmed=False):+ """Why a guarded model target was not applied (the owner's guard text first)."""+ reason = ('the session changed before the confirmation landed; run /model again.' if confirmed else+ 'this target needs a confirmation; run /model in an interactive session to confirm it.')+ return f"{refusal['confirm_message']}\n\nModel not switched: {reason}"+++def confirmation_title(refusal):+ """The one prompt title for the owner's guard warnings (as ``combined_selection_warning``)."""+ warnings = refusal.get('warnings') or []+ return warnings[0]['title'] if len(warnings) == 1 else 'Model Selection Warning'+++def confirm_choice(raw, choices):+ """``once`` / ``cancel`` (or None) for a typed answer: the choice's number or the classic+ CLI's confirm aliases (y/yes/once, n/no/cancel)."""+ from hermes_cli.cli_modal_mixin import _CONFIRM_ALIASES+ answer = (raw or '').strip().lower()+ if answer.isdigit() and 0 < int(answer) <= len(choices):+ return choices[int(answer) - 1][0]+ allowed = {choice[0] for choice in choices}+ normalized = _CONFIRM_ALIASES.get(answer, answer)+ return normalized if normalized in allowed else None++def compress_payload(arg):"""Structured ``session.mutate(compress)`` payload from the raw ``/compress`` arguments.diff --git a/locales/af.yaml b/locales/af.yamlindex 31af11a4c84..75cb03d39b6 100644--- a/locales/af.yaml+++ b/locales/af.yaml@@ -1972,6 +1972,7 @@ cli:desc_switch_anyway: "Gebruik hierdie model vir die huidige Hermes-sessie."choice_cancel: "Kanselleer"desc_keep_current_model: "Behou die huidige model."+ confirm_choice_prompt: "Keuse [1/2]: "switch_cancelled: "Modelverandering gekanselleer."selection_failed: "✗ Modelkeuse het misluk: {error}"switch_failed: "⚠ Modelverandering na {model} het misluk ({error}); bly op {old_model}."diff --git a/locales/ar.yaml b/locales/ar.yamlindex 044d6504482..5951fc73cce 100644--- a/locales/ar.yaml+++ b/locales/ar.yaml@@ -1972,6 +1972,7 @@ cli:desc_switch_anyway: "استخدام هذا النموذج لجلسة Hermes الحالية."choice_cancel: "إلغاء"desc_keep_current_model: "الاحتفاظ بالنموذج الحالي."+ confirm_choice_prompt: "الاختيار [1/2]: "switch_cancelled: "أُلغي تبديل النموذج."selection_failed: "✗ فشل اختيار النموذج: {error}"switch_failed: "⚠ فشل التبديل إلى النموذج {model} ({error})؛ البقاء على {old_model}."diff --git a/locales/de.yaml b/locales/de.yamlindex 17c884bb465..3858fcc2c57 100644--- a/locales/de.yaml+++ b/locales/de.yaml@@ -1972,6 +1972,7 @@ cli:desc_switch_anyway: "Dieses Modell für die aktuelle Hermes-Sitzung verwenden."choice_cancel: "Abbrechen"desc_keep_current_model: "Das aktuelle Modell beibehalten."+ confirm_choice_prompt: "Auswahl [1/2]: "switch_cancelled: "Modellwechsel abgebrochen."selection_failed: "✗ Modellauswahl fehlgeschlagen: {error}"switch_failed: "⚠ Modellwechsel zu {model} fehlgeschlagen ({error}); {old_model} bleibt aktiv."diff --git a/locales/en.yaml b/locales/en.yamlindex 8318c471db4..11caa9a7b2c 100644--- a/locales/en.yaml+++ b/locales/en.yaml@@ -2066,6 +2066,7 @@ cli:desc_switch_anyway: "Use this model for the current Hermes session."choice_cancel: "Cancel"desc_keep_current_model: "Keep the current model."+ confirm_choice_prompt: "Choice [1/2]: "switch_cancelled: "Model switch cancelled."selection_failed: "✗ Model selection failed: {error}"switch_failed: "⚠ Model switch to {model} failed ({error}); staying on {old_model}."diff --git a/locales/es.yaml b/locales/es.yamlindex 54b600dbede..3c1d14fc0e8 100644--- a/locales/es.yaml+++ b/locales/es.yaml@@ -1972,6 +1972,7 @@ cli:desc_switch_anyway: "Usar este modelo en la sesión actual de Hermes."choice_cancel: "Cancelar"desc_keep_current_model: "Mantener el modelo actual."+ confirm_choice_prompt: "Opción [1/2]: "switch_cancelled: "Cambio de modelo cancelado."selection_failed: "✗ Falló la selección de modelo: {error}"switch_failed: "⚠ Falló el cambio al modelo {model} ({error}); se mantiene {old_model}."diff --git a/locales/fr.yaml b/locales/fr.yamlindex 07c542af8e6..07c3be971c3 100644--- a/locales/fr.yaml+++ b/locales/fr.yaml@@ -2224,6 +2224,7 @@ cli:desc_switch_anyway: "Utiliser ce modèle pour la session Hermes en cours."choice_cancel: "Annuler"desc_keep_current_model: "Conserver le modèle actuel."+ confirm_choice_prompt: "Choix [1/2] : "switch_cancelled: "Changement de modèle annulé."selection_failed: "✗ Échec de la sélection du modèle : {error}"switch_failed: "⚠ Échec du passage au modèle {model} ({error}) ; {old_model} est conservé."diff --git a/locales/ga.yaml b/locales/ga.yamlindex ba573336628..409e4977999 100644--- a/locales/ga.yaml+++ b/locales/ga.yaml@@ -1972,6 +1972,7 @@ cli:desc_switch_anyway: "Úsáid an tsamhail seo don seisiún Hermes reatha."choice_cancel: "Cealaigh"desc_keep_current_model: "Coinnigh an tsamhail reatha."+ confirm_choice_prompt: "Rogha [1/2]: "switch_cancelled: "Athrú samhla cealaithe."selection_failed: "✗ Theip ar roghnú samhla: {error}"switch_failed: "⚠ Theip ar athrú samhla go {model} ({error}); ag fanacht ar {old_model}."diff --git a/locales/hu.yaml b/locales/hu.yamlindex f6136215b41..fc28f3227ff 100644--- a/locales/hu.yaml+++ b/locales/hu.yaml@@ -1989,6 +1989,7 @@ cli:desc_switch_anyway: "Ennek a modellnek a használata a jelenlegi Hermes-munkamenetben."choice_cancel: "Mégse"desc_keep_current_model: "A jelenlegi modell megtartása."+ confirm_choice_prompt: "Választás [1/2]: "switch_cancelled: "Modellváltás megszakítva."selection_failed: "✗ A modell kiválasztása nem sikerült: {error}"switch_failed: "⚠ Nem sikerült átváltani a(z) {model} modellre ({error}); marad: {old_model}."diff --git a/locales/it.yaml b/locales/it.yamlindex 407f781019f..d5a58bb23c6 100644--- a/locales/it.yaml+++ b/locales/it.yaml@@ -1972,6 +1972,7 @@ cli:desc_switch_anyway: "Usa questo modello per la sessione Hermes corrente."choice_cancel: "Annulla"desc_keep_current_model: "Mantieni il modello attuale."+ confirm_choice_prompt: "Scelta [1/2]: "switch_cancelled: "Cambio di modello annullato."selection_failed: "✗ Selezione del modello non riuscita: {error}"switch_failed: "⚠ Passaggio al modello {model} non riuscito ({error}); resto su {old_model}."diff --git a/locales/ja.yaml b/locales/ja.yamlindex 31b16313623..32775995999 100644--- a/locales/ja.yaml+++ b/locales/ja.yaml@@ -1972,6 +1972,7 @@ cli:desc_switch_anyway: "現在の Hermes セッションでこのモデルを使用します。"choice_cancel: "キャンセル"desc_keep_current_model: "現在のモデルを維持します。"+ confirm_choice_prompt: "選択 [1/2]: "switch_cancelled: "モデルの切り替えをキャンセルしました。"selection_failed: "✗ モデルの選択に失敗しました: {error}"switch_failed: "⚠ {model} への切り替えに失敗しました({error})。{old_model} を引き続き使用します。"diff --git a/locales/ko.yaml b/locales/ko.yamlindex 9cd83fbad36..ae13786eaa6 100644--- a/locales/ko.yaml+++ b/locales/ko.yaml@@ -1972,6 +1972,7 @@ cli:desc_switch_anyway: "현재 Hermes 세션에서 이 모델을 사용해요."choice_cancel: "취소"desc_keep_current_model: "현재 모델을 유지해요."+ confirm_choice_prompt: "선택 [1/2]: "switch_cancelled: "모델 전환이 취소됐어요."selection_failed: "✗ 모델 선택 실패: {error}"switch_failed: "⚠ {model}(으)로 모델 전환 실패 ({error}); {old_model}을(를) 계속 사용해요."diff --git a/locales/pt.yaml b/locales/pt.yamlindex 77a9a44b573..964ab4b517d 100644--- a/locales/pt.yaml+++ b/locales/pt.yaml@@ -1972,6 +1972,7 @@ cli:desc_switch_anyway: "Usar este modelo na sessão atual do Hermes."choice_cancel: "Cancelar"desc_keep_current_model: "Manter o modelo atual."+ confirm_choice_prompt: "Escolha [1/2]: "switch_cancelled: "Troca de modelo cancelada."selection_failed: "✗ Falha na seleção de modelo: {error}"switch_failed: "⚠ Falha ao trocar para o modelo {model} ({error}); permanecendo em {old_model}."diff --git a/locales/ru.yaml b/locales/ru.yamlindex 86abc7e1698..3acf881a2c0 100644--- a/locales/ru.yaml+++ b/locales/ru.yaml@@ -1972,6 +1972,7 @@ cli:desc_switch_anyway: "Использовать эту модель в текущем сеансе Hermes."choice_cancel: "Отмена"desc_keep_current_model: "Оставить текущую модель."+ confirm_choice_prompt: "Выбор [1/2]: "switch_cancelled: "Переключение модели отменено."selection_failed: "✗ Не удалось выбрать модель: {error}"switch_failed: "⚠ Не удалось переключиться на {model} ({error}); остаёмся на {old_model}."diff --git a/locales/tr.yaml b/locales/tr.yamlindex 3b07045b465..71d37a4a6be 100644--- a/locales/tr.yaml+++ b/locales/tr.yaml@@ -1972,6 +1972,7 @@ cli:desc_switch_anyway: "Bu modeli geçerli Hermes oturumu için kullanın."choice_cancel: "İptal"desc_keep_current_model: "Geçerli modeli koruyun."+ confirm_choice_prompt: "Seçim [1/2]: "switch_cancelled: "Model değişikliği iptal edildi."selection_failed: "✗ Model seçimi başarısız oldu: {error}"switch_failed: "⚠ {model} modeline geçiş başarısız oldu ({error}); {old_model} modelinde kalınıyor."diff --git a/locales/uk.yaml b/locales/uk.yamlindex 3e34c79350e..72142f58b9c 100644--- a/locales/uk.yaml+++ b/locales/uk.yaml@@ -1972,6 +1972,7 @@ cli:desc_switch_anyway: "Використати цю модель для поточного сеансу Hermes."choice_cancel: "Скасувати"desc_keep_current_model: "Залишити поточну модель."+ confirm_choice_prompt: "Вибір [1/2]: "switch_cancelled: "Зміну моделі скасовано."selection_failed: "✗ Не вдалося вибрати модель: {error}"switch_failed: "⚠ Не вдалося змінити модель на {model} ({error}); залишаємося на {old_model}."diff --git a/locales/zh-hant.yaml b/locales/zh-hant.yamlindex 309bba5da2d..f0d16a3d8fc 100644--- a/locales/zh-hant.yaml+++ b/locales/zh-hant.yaml@@ -1972,6 +1972,7 @@ cli:desc_switch_anyway: "在目前的 Hermes 工作階段使用此模型。"choice_cancel: "取消"desc_keep_current_model: "保留目前的模型。"+ confirm_choice_prompt: "選擇 [1/2]:"switch_cancelled: "已取消切換模型。"selection_failed: "✗ 選擇模型失敗:{error}"switch_failed: "⚠ 切換至模型 {model} 失敗({error});維持使用 {old_model}。"diff --git a/locales/zh.yaml b/locales/zh.yamlindex e8904057641..71dfcbc3954 100644--- a/locales/zh.yaml+++ b/locales/zh.yaml@@ -1972,6 +1972,7 @@ cli:desc_switch_anyway: "在当前 Hermes 会话中使用此模型。"choice_cancel: "取消"desc_keep_current_model: "保留当前模型。"+ confirm_choice_prompt: "选择 [1/2]: "switch_cancelled: "已取消切换模型。"selection_failed: "✗ 选择模型失败:{error}"switch_failed: "⚠ 切换到模型 {model} 失败({error});继续使用 {old_model}。"diff --git a/tests/gateway/test_model_confirmation_clients.py b/tests/gateway/test_model_confirmation_clients.pynew file mode 100644index 00000000000..a9d5cd93370--- /dev/null+++ b/tests/gateway/test_model_confirmation_clients.py@@ -0,0 +1,139 @@+"""Every native surface collects the owner's guarded-model confirmation (same as main's CLI).++The real session authority answers a flagged ``session.mutate operation=model`` with+``confirmation_required`` and a one-time token; the classic CLI chat view and the ACP adapter must+ask, re-send once with the token on yes, and leave the session untouched on no.+"""+from types import SimpleNamespace++import pytest++from hermes_cli.gateway_client import GatewayClientError+++class _Owner:+ """A real SessionAuthority behind the client ``rpc`` surface the viewers use."""++ def __init__(self, tmp_path, monkeypatch):+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import SessionAuthority+ from gateway.session_controls import AuthorityConnection+ from gateway.session_local import create_local_session+ from hermes_cli import model_cost_guard, model_switch+ import hermes_state_runtime as rt+ monkeypatch.setattr(run, '_load_gateway_config', lambda *a: {})+ monkeypatch.setattr(model_switch, 'switch_model', lambda **k: model_switch.ModelSwitchResult(+ success=True, new_model=k['raw_input'], target_provider='custom', base_url='http://127.0.0.1:9/v1'))+ monkeypatch.setattr(model_cost_guard, 'expensive_model_warning', lambda model, **k: (+ model_cost_guard.ExpensiveModelWarning(model, 'custom', None, None, 'test', f'{model} IS EXPENSIVE')+ if model.startswith('pricey') else None))+ self.store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ self.db = self.store._db+ runner = SimpleNamespace(session_store=self.store, _session_db=self.db, adapters={}, _draining=False,+ _evict_cached_agent=lambda route: None, _cached_agent_for=lambda route: None,+ _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=self.db,+ epoch=rt.begin_runtime_epoch(self.db, instance_id='owner'))+ self.connection = AuthorityConnection(authority, object(), {'user_id': 'human'})+ self.sid = create_local_session(authority, self.connection.actor, dict(+ request_id='m', source='cli', cwd=str(tmp_path), model='frozen', toolsets=[])).session_id+ self.mutations = []++ async def rpc(self, method, **params):+ if method == 'session.mutate':+ self.mutations.append(params['payload'])+ response = await self.connection.dispatch({'id': 1, 'method': method, 'params': params})+ if 'error' in response:+ raise GatewayClientError((response['error'].get('data') or {}).get('reason') or response['error']['message'])+ return response['result']++ def state(self):+ row = self.db.get_session(self.sid)+ return row['model'], row['runtime_revision'], row['runtime_generation']++ async def close(self):+ await self.connection.close()+ self.store.close_all_db_handles()+++async def test_cli_chat_view_asks_and_applies_a_guarded_model_once_with_the_token(tmp_path, monkeypatch, capsys):+ from hermes_cli.gateway_chat_view import GatewayChatView+ owner = _Owner(tmp_path, monkeypatch)++ class Composer:+ def __init__(self, answer):+ self.answer, self.asked = answer, 0++ async def prompt_async(self, symbol):+ self.asked += 1+ return self.answer+ try:+ before = owner.state()+ view = GatewayChatView(owner, {'stored_session_id': owner.sid})+ view._composer = Composer('2') # cancel+ assert await view.command('/model pricey') is True+ assert view._composer.asked == 1 and owner.state() == before, 'declined switch changed the session'+ assert 'pricey IS EXPENSIVE' in capsys.readouterr().out+ assert [p.get('confirm') for p in owner.mutations] == [None], 'a declined switch was re-sent'++ owner.mutations.clear()+ view._composer = Composer('y')+ assert await view.command('/model pricey') is True+ assert view._composer.asked == 1+ token = owner.mutations[1].get('confirm')+ assert token and [p.get('confirm') for p in owner.mutations] == [None, token]+ assert owner.state() == ('pricey', before[1] + 1, before[2] + 1), 'confirmed switch not applied once'+ assert view.model == 'pricey'++ # Non-interactive (`-q`, no TTY): no prompt, a refusal naming the message; nothing written.+ owner.mutations.clear()+ view._composer = None+ with pytest.raises(GatewayClientError, match='pricey-xl IS EXPENSIVE'):+ await view.command('/model pricey-xl')+ assert len(owner.mutations) == 1 and owner.state()[0] == 'pricey'+ finally:+ await owner.close()+++async def test_acp_set_session_model_asks_through_request_permission(tmp_path, monkeypatch):+ from acp.schema import AllowedOutcome, DeniedOutcome+ from acp_adapter.gateway_server import GatewayACPAgent+ owner = _Owner(tmp_path, monkeypatch)+ asked = []++ class Editor:+ def __init__(self, outcome):+ self.outcome = outcome++ async def request_permission(self, session_id, tool_call, options):+ asked.append((session_id, [o.option_id for o in options], tool_call))+ return SimpleNamespace(outcome=self.outcome)++ agent = GatewayACPAgent()+ agent._gateway = owner+ agent._client = lambda: _ready(owner)+ try:+ before = owner.state()+ agent._conn = Editor(DeniedOutcome(outcome='cancelled'))+ with pytest.raises(GatewayClientError, match='model_switch_cancelled'):+ await agent.set_session_model(model_id='pricey', session_id=owner.sid)+ assert owner.state() == before and [p.get('confirm') for p in owner.mutations] == [None]+ assert asked[0][0] == owner.sid and asked[0][1] == ['allow_once', 'deny']++ owner.mutations.clear()+ agent._conn = Editor(AllowedOutcome(outcome='selected', option_id='allow_once'))+ await agent.set_session_model(model_id='pricey', session_id=owner.sid)+ token = owner.mutations[1].get('confirm')+ assert token and [p.get('confirm') for p in owner.mutations] == [None, token]+ assert owner.state() == ('pricey', before[1] + 1, before[2] + 1)+ finally:+ await owner.close()+++async def _ready(value):+ return value