The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): Bot Chat follow_profile_config follows the profile's current route
Teknium70e09da88272
diff --git a/apps/desktop/src/api/canonical-create-options.test.ts b/apps/desktop/src/api/canonical-create-options.test.tsindex da1164833c7..2bb0d073cb9 100644--- a/apps/desktop/src/api/canonical-create-options.test.ts+++ b/apps/desktop/src/api/canonical-create-options.test.ts@@ -21,6 +21,7 @@ const CASES: Array<[string, Record<string, unknown>, Record<string, unknown> | R['picked workspace', { ...BASE, cwd: '/w', cwd_explicit: true, fast: false }, { cwd: '/w' }],['composer effort', { ...BASE, cwd: '/w', cwd_explicit: false, reasoning_effort: 'high', fast: false }, { cwd: '/w', reasoning: 'high' }],['onboarding minimal effort', { ...BASE, reasoning_effort: 'minimal', fast: false, title: 'Welcome' }, { reasoning: 'minimal', title: 'Welcome' }],+ ['Bot Chat', { ...BASE, title: 'Bot Chat', hidden: true, follow_profile_config: true }, { follow_profile_config: true, hidden: true }],['Fast speed', { ...BASE, cwd: '/w', cwd_explicit: false, fast: true }, /fast speed is not available on the shared gateway yet/],['Ultrafast speed', { ...BASE, fast: true, service_tier: 'ultrafast' }, /ultrafast speed is not available on the shared gateway yet/]]diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.tsindex 1ad5920d873..32a3db7adc6 100644--- a/apps/desktop/src/api/canonical-protocol.ts+++ b/apps/desktop/src/api/canonical-protocol.ts@@ -401,7 +401,7 @@ export class CanonicalDesktopProtocol {if (unsupported.length) { throw new Error(`Canonical gateway does not support explicit session options: ${unsupported.join(', ')}`) }const result = Object.fromEntries(Object.entries(params).filter(([key, value]) =>- ['request_id', 'cwd', 'model', 'toolsets', 'reasoning', 'title', 'hidden'].includes(key) || (key === 'profile' && siblingRoute(value))))+ ['request_id', 'cwd', 'model', 'toolsets', 'reasoning', 'title', 'hidden', 'follow_profile_config'].includes(key) || (key === 'profile' && siblingRoute(value))))const key = JSON.stringify(result)const requestId = params.request_id ?? this.creates.get(key) ?? crypto.randomUUID()diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex b235e64b1fe..bea5119ed27 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -1675,10 +1675,11 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gatewayself._evict_cached_agent(session_key)return# A LOCAL session runs its frozen launch policy's model, not the gateway's configured one.+ from gateway.session_authorities import active_authorityfrom gateway.session_policy import policy_for_sourcepolicy = policy_for_source(self, turn_ctx.source)_cfg_model = self._fallback_baseline_model(- session_key, turn_ctx.source, _agent, policy_model=policy.model if policy and policy.model else None)+ session_key, turn_ctx.source, _agent, policy_model=policy.current_model(active_authority(self)) if policy and policy.model else None)if _agent.model != _cfg_model and not self._is_intentional_model_switch(session_key, _agent, _cfg_model):self._evict_cached_agent(session_key)diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.pyindex 621858ab404..a0e7460c051 100644--- a/gateway/run_turn_prepare.py+++ b/gateway/run_turn_prepare.py@@ -50,21 +50,23 @@ def _resolve_policy_agent_runtime(runner, policy) -> tuple[str, dict]:from gateway.session_authorities import active_authorityauthority = active_authority(runner)frozen = policy.config(authority)+ # A follow_profile_config session's route is the profile's current one (frozen == live sections).+ model, provider = policy.current_model(authority), (frozen.get('model') or {}).get('provider')key = launch_key(authority, policy)launch_url = json.loads(policy.request_json).get('base_url')if launch_url:# The creation request is immutable identity, not the current selection: once a canonical# model mutation moved the route off the launch endpoint, the policy's selection wins.from hermes_cli.route_identity import normalize_route_base_url- if normalize_route_base_url(launch_url) != normalize_route_base_url(policy.base_url):+ if normalize_route_base_url(launch_url) != normalize_route_base_url((frozen.get('model') or {}).get('base_url')):launch_url = None# Every rung reads the session's FROZEN config, never live config.yaml: a later# ``model.base_url`` edit must not carry this route's frozen credential to the new host# (R2-M2). The auth-store pool is not config, so refresh/rotation still applies.with frozen_runtime_config(frozen):- runtime = _resolve_named_custom_runtime(requested_provider=policy.provider,+ runtime = _resolve_named_custom_runtime(requested_provider=provider,explicit_api_key=key, explicit_base_url=launch_url,- target_model=policy.model, config=frozen)+ target_model=model, config=frozen)if runtime is None:# Only a bound launch key is explicit: the frozen ``model.api_key`` is config, which the# resolver already reads from the frozen scope, so a URL-matched credential pool still@@ -74,18 +76,18 @@ def _resolve_policy_agent_runtime(runner, policy) -> tuple[str, dict]:# route's own ``fallback_providers`` before the turn is refused. Only a launch URL is# explicit (classic one-shot parity): the frozen ``model.base_url`` is resolved by# the provider chain, which keeps the credential pool an explicit URL would drop.- runtime, fallback_entry = resolve_runtime_with_fallback(frozen, requested=policy.provider,- explicit_api_key=key, explicit_base_url=launch_url, target_model=policy.model)+ runtime, fallback_entry = resolve_runtime_with_fallback(frozen, requested=provider,+ explicit_api_key=key, explicit_base_url=launch_url, target_model=model)else:fallback_entry = Noneif fallback_entry is not None:from hermes_cli.fallback_config import pre_agent_fallback_noticerunner._pre_agent_fallback_notice = pre_agent_fallback_notice(- policy.provider or '', policy.model or '',+ provider or '', model or '',runtime.get('provider') or fallback_entry.get('provider') or 'unknown',fallback_entry.get('model') or 'default')return fallback_entry['model'], _runtime_agent_kwargs(runtime)- return policy.model, _runtime_agent_kwargs(runtime)+ return model, _runtime_agent_kwargs(runtime)def _recover_or_remember_model(runner, skey, model):diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 19e9b48108b..d84b4744ca2 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -1132,7 +1132,8 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):if policy and policy.model and not pending_fallback_notice:# The frozen route's model, unless resolution just fell back: the fallback entry's# model is the one this agent must send (#112600).- model = policy.model+ from gateway.session_authorities import active_authority+ model = policy.current_model(active_authority(runner))logger.debug("run_agent resolved: model=%s provider=%s session=%s",model, runtime_kwargs.get("provider"), ctx.session_key or "",@@ -1169,7 +1170,7 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):return _unresolved(f"⚠️ {exc}")return _unresolved(t("gateway.errors.no_credentials"))pr = runner._provider_routing- reasoning_config = (policy.reasoning_config if policy else+ reasoning_config = (policy.current_reasoning_config(runner) if policy elserunner._resolve_session_reasoning_config(source=ctx.source, session_key=ctx.session_key, model=model))runner._service_tier = runner._resolve_session_service_tier(source=ctx.source, session_key=ctx.session_key)from gateway.session_api_turn import api_executiondiff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 27896596a46..62db845486a 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -263,11 +263,9 @@ class AuthorityConnection:from gateway.session_local_title import resolve_titled_session, title_new_sessionfrom gateway.session_runtime_workers import tracked_writefrom hermes_state_local import commit_local_session- # Bot Mode's forever-chat mint: born hidden from the sidebar; `follow_profile_config` is- # the canonical default (a local session's runtime is built from the profile's current- # config on every attach), so the flag is accepted for the legacy contract and implied.+ # Bot Mode's forever-chat mint: born hidden from the sidebar. `follow_profile_config` stays in+ # the frozen request: the policy re-reads the profile's current route every turn.hidden = params.pop('hidden', False)- params.pop('follow_profile_config', None)if type(hidden) is not bool:raise RuntimeStoreError('invalid_params')ref = title and resolve_titled_session(self.authority, self.actor, title, missing_ok=True)diff --git a/gateway/session_local.py b/gateway/session_local.pyindex f14db919dea..5faed74bde3 100644--- a/gateway/session_local.py+++ b/gateway/session_local.py@@ -232,7 +232,7 @@ def _lazy_model(authority, policy):"""The model a not-yet-built session will run: with no provider pinned, the free tier's agentbuild pins ``nous/welcome`` (``pin_model_for_route``), so the configured default is not it."""import json- model = policy.model if policy else None+ model = policy.current_model(authority) if policy else Noneif (policy is None or json.loads(policy.request_json).get('model')or str(policy.provider or '').strip().lower() not in {'', 'auto'}):return model@@ -279,7 +279,7 @@ def local_session_info(authority, ref):from gateway.session_policy import policy_for_sourcepolicy = policy_for_source(authority.runner, live.source)info = {'source': policy.source if policy else live.source.platform.value,- 'model': (getattr(agent, 'model', policy.model if policy else None) if agent is not None+ 'model': (getattr(agent, 'model', policy.current_model(authority) if policy else None) if agent is not Noneelse _lazy_model(authority, policy)),'lazy': agent is None,'profile_id': authority.profile_id, 'desktop_protocol': CANONICAL_GATEWAY_PROTOCOL,diff --git a/gateway/session_mutation_model.py b/gateway/session_mutation_model.pyindex 6fa3f3ca5f0..5ec5092d3d8 100644--- a/gateway/session_mutation_model.py+++ b/gateway/session_mutation_model.py@@ -33,6 +33,15 @@ async def prepare_model(authority, live, payload, prepared):# and the endpoint-bound credential fields (inline key, key_env/api_key_env) drop on a route change.# Off-loop: the context-pin check can do cold-start disk I/O.frozen['model'] = await asyncio.to_thread(apply_model_selection, frozen.get('model'), result)+ if old.follows_profile:+ # A committed /model holds while the profile still targets what it targets now (main's+ # composer_override_profile); a later profile edit supersedes it.+ from pathlib import Path+ from gateway.run import _load_gateway_config+ from gateway.session_policy import present_sections, profile_target+ live = await asyncio.to_thread(+ lambda: _load_gateway_config(Path(authority.db.db_path).resolve().parent / 'config.yaml'))+ frozen['model']['selection_profile'] = list(profile_target(present_sections(live)))# A direct alias's own credential is part of the selection (never ``result.api_key``, which the# switch resolved for its probe): its env pointer is committed and re-read every turn; a literal# key is a private config secret at the alias entry's own path (what a restarted owner re-reads)diff --git a/gateway/session_policy.py b/gateway/session_policy.pyindex 6a1547072ec..b1b012fd67a 100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@ -10,7 +10,11 @@ from hermes_state_runtime import RuntimeStoreErrorCREATE_FIELDS = frozenset({'request_id', 'source', 'cwd', 'model', 'toolsets','provider', 'base_url', 'reasoning', 'max_turns', 'ignore_rules', 'api_key', 'editor','yolo', 'safe_mode', 'ignore_user_config',- 'skills', 'checkpoints', 'accept_hooks', 'pass_session_id'})+ 'skills', 'checkpoints', 'accept_hooks', 'pass_session_id', 'follow_profile_config'})+# Sections a ``follow_profile_config`` session re-reads from the owning profile's CURRENT config each+# turn (main's Bot Chat row), credentials included: a frozen key never crosses a profile route change.+FOLLOW_SECTIONS = ('model', 'providers', 'custom_providers', 'fallback_providers', 'fallback_model', 'model_aliases')+FOLLOW_AGENT_KEYS = ('reasoning_effort', 'reasoning_overrides', 'service_tier')BYPASS_FIELDS = ('safe_mode', 'ignore_user_config')_ACTIVE_POLICY: ContextVar = ContextVar('local_session_policy', default=None)# Creation label -> agent surface. ``tool`` (third-party integrations, ``hermes chat --source tool``) and@@ -43,9 +47,10 @@ class LocalSessionPolicy:def config(self, authority=None):config = present_sections(json.loads(self.config_json))+ live = self._live_profile(authority, config)if self.config_secret_ref is not None and authority is not None:from gateway.session_policy_credentials import recover_config_secrets- secrets = recover_config_secrets(authority, self)+ secrets = recover_config_secrets(authority, self, skip=FOLLOW_SECTIONS if live is not None else ())for path, value in secrets.items():if path[0] is None: # private terminal projection, not configcontinue@@ -58,8 +63,54 @@ class LocalSessionPolicy:# ``/model <alias>`` with a literal key: the receipt points at the alias entry's secret.if isinstance(model, dict) and model.get('api_key_from') and 'api_key' in model:model['api_key'] = secrets.get(tuple(model['api_key_from']))+ if live is not None:+ for key in FOLLOW_SECTIONS:+ if key in live:+ config[key] = live[key]+ else:+ config.pop(key, None)+ agent, live_agent = config.setdefault('agent', {}), live.get('agent') or {}+ for key in FOLLOW_AGENT_KEYS:+ if key in live_agent:+ agent[key] = live_agent[key]+ else:+ agent.pop(key, None)return config+ @property+ def follows_profile(self):+ return json.loads(self.request_json).get('follow_profile_config') is True++ def _live_profile(self, authority, frozen):+ """The owning profile's current config for a following session, or None when the frozen route+ applies: not following, or an explicit pick (create-time model / committed /model) made while+ the profile still targets what it targeted then (main's ``composer_override_profile``)."""+ if authority is None or not self.follows_profile:+ return None+ from gateway.run import _load_gateway_config+ live = present_sections(_load_gateway_config(Path(authority.db.db_path).resolve().parent / 'config.yaml'))+ pick = (frozen.get('model') or {}).get('selection_profile')+ if not live or (pick is not None and pick == list(profile_target(live))):+ return None+ return live++ def current_reasoning_config(self, runner):+ """The next turn's reasoning: the profile's current effort when following, else the frozen one."""+ if not self.follows_profile:+ return self.reasoning_config+ from gateway.session_authorities import active_authority+ from hermes_constants import resolve_reasoning_config+ authority = active_authority(runner)+ return resolve_reasoning_config(self.config(authority), self.current_model(authority) or '')++ def current_model(self, authority):+ """The model this session's next turn runs: the profile's current default when following."""+ live = self._live_profile(authority, present_sections(json.loads(self.config_json)))+ if live is None:+ return self.model+ from gateway.run import _resolve_gateway_model+ return _resolve_gateway_model(live) or self.model+@propertydef provider(self):return self.config().get('model', {}).get('provider')@@ -101,6 +152,15 @@ class LocalSessionPolicy:return resolve_reasoning_config(self.config(), self.model or '')+def profile_target(config):+ """(model, provider) a profile config selects; 'auto' is no provider (main's _config_model_target)."""+ model = config.get('model')+ if isinstance(model, dict):+ provider = str(model.get('provider') or '').strip()+ return str(model.get('default') or '').strip(), '' if provider.lower() == 'auto' else provider+ return (model.strip() if isinstance(model, str) else ''), ''++def present_sections(config):"""A bare ``gateway:`` key parses as YAML null; like load_config's merge (#58277), treat it as absent so``cfg.get('gateway', {}).get(...)`` reads the default instead of crashing a fresh install's first turn."""@@ -138,6 +198,10 @@ def build_policy(params, config, *, private_secrets=None, profile_terminal=True)validate_editor(source, params.get('editor'))launch_skills(params)config = present_sections(json.loads(json.dumps(config)))+ if params.get('follow_profile_config') is True and 'model' in params:+ # The pick's provenance, recorded before the launch route folds in: it holds while the profile+ # still targets this, and a later profile edit supersedes it.+ config.setdefault('model', {})['selection_profile'] = list(profile_target(config))_apply_launch_overrides(params, config)enabled = _resolve_toolsets(params, config, source, safe_mode)terminal = build_profile_terminal_scope(get_hermes_home()) if profile_terminal else default_terminal_scope()@@ -169,7 +233,7 @@ def _apply_launch_overrides(params, config):or url.username or url.password or url.query or url.fragment):raise RuntimeStoreError('invalid_params')config.setdefault('model', {})[key] = value- for flag in ('ignore_rules', 'yolo', 'checkpoints', 'accept_hooks', 'pass_session_id'):+ for flag in ('ignore_rules', 'yolo', 'checkpoints', 'accept_hooks', 'pass_session_id', 'follow_profile_config'):if flag in params and type(params[flag]) is not bool:raise RuntimeStoreError('invalid_params')if params.get('checkpoints'):diff --git a/gateway/session_policy_credentials.py b/gateway/session_policy_credentials.pyindex 5e7c70dccaa..986e1784935 100644--- a/gateway/session_policy_credentials.py+++ b/gateway/session_policy_credentials.py@@ -32,13 +32,16 @@ def config_reference(authority, session_id, policy, secrets):sort_keys=True)-def recover_config_secrets(authority, policy):+def recover_config_secrets(authority, policy, skip=()):+ """The frozen config secrets; entries under a *skip* section are neither re-read nor checked (a+ following session overwrites those sections from the live profile, so a key rotation there is not+ a revoked launch credential)."""ref = policy.config_secret_refif not ref.startswith(PREFIX):values = getattr(authority, '_local_config_secrets', {}).get(ref)if values is None:raise RuntimeStoreError('launch_credentials_unavailable')- return values+ return {path: value for path, value in values.items() if path[0] not in skip}try:source = json.loads(ref[len(PREFIX):])home = Path(authority.db.db_path).resolve().parent@@ -47,11 +50,13 @@ def recover_config_secrets(authority, policy):raise ValueError('scope mismatch')cached = getattr(authority, '_local_config_secrets', {}).get(ref)if cached is not None:- return cached+ return {path: value for path, value in cached.items() if path[0] not in skip}from gateway.run import _load_gateway_configconfig = _load_gateway_config(home / 'config.yaml')values = {}for path, fingerprint in source['entries']:+ if path[0] in skip:+ continuevalue = configlookup = pathif path[0] is None:diff --git a/tests/gateway/test_session_follow_profile_config.py b/tests/gateway/test_session_follow_profile_config.pynew file mode 100644index 00000000000..e540ca3e68e--- /dev/null+++ b/tests/gateway/test_session_follow_profile_config.py@@ -0,0 +1,76 @@+"""Bot Chat's ``follow_profile_config`` on the shared owner (B23 / C-hx-4).++Main's follow row rebuilt its route from the profile's CURRENT config on every turn; an explicit pick+held only while the profile still targeted what it targeted at pick time. The owner freezes a policy,+so the frozen request says "follow" and each turn re-reads the profile's model sections (credentials+included). Real SessionStore/SessionAuthority and a real config.yaml; ``_load_gateway_config`` is not+patched.+"""+from types import SimpleNamespace++import pytest+import json+++def _profile(home, model, port, key):+ (home / "config.yaml").write_text(json.dumps({'model': {+ 'provider': 'custom', 'base_url': f'http://127.0.0.1:{port}/v1', 'default': model, 'api_key': key}}))+++def _owner(home):+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import SessionAuthority+ from gateway.session_controls import AuthorityConnection+ import hermes_state_runtime as rt+ store = SessionStore(home / 'sessions', GatewayConfig())+ db = store._db+ runner = SimpleNamespace(session_store=store, _session_db=db, adapters={}, _draining=False,+ _evict_cached_agent=lambda route: None, _cached_agent_for=lambda route: None,+ _handle_message=None)+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)+ authority = SessionAuthority(runner, profile_id='owned', instance_id='owner', db=db,+ epoch=rt.begin_runtime_epoch(db, instance_id='owner'))+ runner.session_authority = authority+ return store, runner, authority, AuthorityConnection(authority, object(), {'user_id': 'human'})+++async def _create(owner, authority, home, request_id, **extra):+ response = await owner.dispatch({'id': request_id, 'method': 'session.create', 'params': dict(+ request_id=request_id, source='gui', cwd=str(home), toolsets=[],+ follow_profile_config=True, **extra)})+ assert 'result' in response, response+ return authority.sessions[response['result']['session_id']]+++def _route(runner, live):+ from gateway.run_turn_prepare import GatewayTurnPrepareMixin+ model, runtime = GatewayTurnPrepareMixin._resolve_session_agent_runtime(runner, source=live.source)+ return model, runtime.get('base_url'), runtime.get('api_key')+++async def test_follow_profile_session_runs_the_profiles_current_route_and_a_pick_until_superseded(monkeypatch):+ from gateway import run+ from hermes_constants import get_hermes_home+ home = get_hermes_home()+ home.mkdir(parents=True, exist_ok=True)+ # gateway.run binds its home at first import; another test module may have imported it under+ # a different HERMES_HOME. The loader itself is real.+ monkeypatch.setattr(run, '_hermes_home', home)+ _profile(home, 'old', 1, 'k-old')+ store, runner, authority, owner = _owner(home)+ try:+ assert authority.db.db_path.parent.resolve() == home.resolve()+ follow = await _create(owner, authority, home, 'follow')+ pick = await _create(owner, authority, home, 'pick', model='pick')+ assert _route(runner, follow) == ('old', 'http://127.0.0.1:1/v1', 'k-old')+ assert _route(runner, pick)[0] == 'pick'+ # The profile moves to another endpoint with another key: the follow session's next turn runs+ # it (the old key never reaches the new host), and the pick is superseded, as on main.+ _profile(home, 'new', 2, 'k-new')+ assert _route(runner, follow) == ('new', 'http://127.0.0.1:2/v1', 'k-new')+ assert _route(runner, pick) == ('new', 'http://127.0.0.1:2/v1', 'k-new')+ finally:+ await owner.close()+ store.close_all_db_handles()